adk_core/event.rs
1use crate::context::{ToolConfirmationDecision, ToolConfirmationRequest};
2use crate::model::LlmResponse;
3use crate::types::Content;
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use uuid::Uuid;
8
9// State scope prefixes
10/// Key prefix for application-scoped state (persists across sessions).
11pub const KEY_PREFIX_APP: &str = "app:";
12/// Key prefix for temporary state (cleared each turn).
13pub const KEY_PREFIX_TEMP: &str = "temp:";
14/// Key prefix for user-scoped state (persists across sessions).
15pub const KEY_PREFIX_USER: &str = "user:";
16
17/// Event-level `provider_metadata` key marking a tool-progress event and naming
18/// its output stream (e.g. `"stdout"`, `"stderr"`). Present only on events
19/// produced by [`ToolContext::emit_progress`](crate::ToolContext::emit_progress).
20pub const TOOL_PROGRESS_STREAM_KEY: &str = "adk.tool_progress.stream";
21
22/// Event-level `provider_metadata` key carrying the originating tool's
23/// function-call id on a tool-progress event.
24pub const TOOL_PROGRESS_CALL_ID_KEY: &str = "adk.tool_progress.call_id";
25
26/// Event represents a single interaction in a conversation.
27/// This struct embeds LlmResponse to match ADK-Go's design pattern.
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct Event {
30 /// Unique identifier for this event.
31 pub id: String,
32 /// When this event was created.
33 pub timestamp: DateTime<Utc>,
34 /// The invocation that produced this event.
35 pub invocation_id: String,
36 /// The conversation branch this event belongs to.
37 pub branch: String,
38 /// The agent or role that authored this event.
39 pub author: String,
40 /// The LLM response containing content and metadata.
41 /// Access content via `event.llm_response.content`.
42 #[serde(flatten)]
43 pub llm_response: LlmResponse,
44 /// Actions to apply (state changes, transfers, confirmations).
45 pub actions: EventActions,
46 /// IDs of long-running tools associated with this event.
47 #[serde(default)]
48 pub long_running_tool_ids: Vec<String>,
49 /// LLM request data for UI display (JSON string)
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub llm_request: Option<String>,
52 /// Provider-specific metadata (e.g., GCP Vertex, Azure OpenAI).
53 /// Keeps the core Event struct provider-agnostic.
54 /// Serialized as `"event_metadata"` to avoid collision with
55 /// [`LlmResponse::provider_metadata`](crate::LlmResponse) when flattened.
56 #[serde(default, skip_serializing_if = "HashMap::is_empty", rename = "event_metadata")]
57 pub provider_metadata: HashMap<String, String>,
58}
59
60/// Metadata for a compacted (summarized) event.
61/// When context compaction is enabled, older events are summarized into a single
62/// compacted event containing this metadata.
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct EventCompaction {
65 /// Timestamp of the earliest event that was compacted.
66 pub start_timestamp: DateTime<Utc>,
67 /// Timestamp of the latest event that was compacted.
68 pub end_timestamp: DateTime<Utc>,
69 /// The summarized content replacing the original events.
70 pub compacted_content: Content,
71}
72
73/// Actions to apply as side effects of an event.
74#[derive(Debug, Clone, Default, Serialize, Deserialize)]
75pub struct EventActions {
76 /// State key-value changes to apply.
77 pub state_delta: HashMap<String, serde_json::Value>,
78 /// Artifact version changes.
79 pub artifact_delta: HashMap<String, i64>,
80 /// Whether to skip summarization for this event.
81 pub skip_summarization: bool,
82 /// Agent name to transfer control to.
83 pub transfer_to_agent: Option<String>,
84 /// Whether to escalate to a human operator.
85 pub escalate: bool,
86 /// Tool confirmation request awaiting human approval.
87 ///
88 /// A tool that sets it on its context's actions holds its own call for the request,
89 /// as an agent tool does when its delegate holds a call: the agent answers the call as
90 /// pending, ends the run on the request, and resumes the call once the request has a
91 /// decision.
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub tool_confirmation: Option<ToolConfirmationRequest>,
94 /// Decision for a pending tool confirmation.
95 #[serde(skip_serializing_if = "Option::is_none")]
96 pub tool_confirmation_decision: Option<ToolConfirmationDecision>,
97 /// Present when this event is a compaction summary replacing older events.
98 #[serde(skip_serializing_if = "Option::is_none")]
99 pub compaction: Option<EventCompaction>,
100 /// Target node names for dynamic route dispatch in graph workflows.
101 /// When non-empty, the graph executor routes to these nodes instead of
102 /// following static edges.
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub route: Option<Vec<String>>,
105 /// Set on a user message that the runner screened with its agents' input guardrails
106 /// before saving it.
107 ///
108 /// A saved user message without it — saved by an earlier release, or appended to the
109 /// session directly — is screened again before any model sees it. See
110 /// [`Agent::screen_user_input`](crate::Agent::screen_user_input).
111 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
112 pub input_screened: bool,
113 /// Set on a confirmation event: where each workflow agent the event passed through had
114 /// reached when the call was held, keyed by the workflow agent's name.
115 ///
116 /// A workflow agent whose last run stopped on a hold that is still held resumes at
117 /// this position instead of starting over. See
118 /// [`workflow_resume_positions`](crate::workflow_resume_positions).
119 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
120 pub workflow_positions: HashMap<String, WorkflowPosition>,
121 /// Set on a user message that reached the run while it ran, through `Runner::steer`.
122 ///
123 /// The message is a user turn like any other in later history, but it is not the run's
124 /// own message: an agent never stands the run's message in for it, and compaction does
125 /// not count it as an invocation. See [`steering`](crate::steering).
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub steering: Option<crate::SteeringMarker>,
128 /// Sources a tool call retrieved and gave the model, recorded with
129 /// [`record_grounding_sources`](crate::record_grounding_sources).
130 ///
131 /// An agent counts a citation in its final answer only if it names one of the sources
132 /// its run recorded. See [`grounding`](crate::grounding).
133 #[serde(default, skip_serializing_if = "Vec::is_empty")]
134 pub grounding_sources: Vec<crate::GroundingSource>,
135}
136
137/// Where a workflow agent was when a call held for confirmation stopped it.
138///
139/// Recorded in [`EventActions::workflow_positions`] by `SequentialAgent`, `LoopAgent`,
140/// `ParallelAgent`, `ConditionalAgent` and `LlmConditionalAgent`.
141///
142/// # Example
143///
144/// ```rust
145/// use adk_core::WorkflowPosition;
146///
147/// let position = WorkflowPosition::new(1, "reviewer");
148/// assert_eq!(position.iteration, 1);
149/// assert_eq!(position.sub_agent, "reviewer");
150/// ```
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152pub struct WorkflowPosition {
153 /// The loop iteration, counted from 0; always 0 for a workflow that does not loop.
154 #[serde(default)]
155 pub iteration: u32,
156 /// The sub-agent that held the call, or that contains the agent that did.
157 pub sub_agent: String,
158}
159
160impl WorkflowPosition {
161 /// Creates a position at `sub_agent` in loop iteration `iteration`.
162 pub fn new(iteration: u32, sub_agent: impl Into<String>) -> Self {
163 Self { iteration, sub_agent: sub_agent.into() }
164 }
165}
166
167/// A typed, borrowed view of a single tool call carried by an [`Event`].
168///
169/// Produced by [`Event::tool_calls`]. Lets UI/event consumers render the tool a
170/// model requested without matching on [`Part::FunctionCall`](crate::Part::FunctionCall)
171/// internals.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct ToolCallView<'a> {
174 /// Provider-assigned call id (OpenAI-style). `None` for providers that omit
175 /// it (e.g. Gemini); fall back to [`name`](Self::name) for correlation.
176 pub call_id: Option<&'a str>,
177 /// The tool/function name the model requested.
178 pub name: &'a str,
179 /// The call arguments as raw JSON.
180 pub args: &'a serde_json::Value,
181}
182
183/// A typed, borrowed view of a single tool result carried by an [`Event`].
184///
185/// Produced by [`Event::tool_results`]. Surfaces a completed tool's output
186/// generically so any tool — streaming or not — can be rendered from the event
187/// stream without walking [`Part::FunctionResponse`](crate::Part::FunctionResponse)
188/// internals.
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub struct ToolResultView<'a> {
191 /// Provider-assigned call id (OpenAI-style), correlating this result with
192 /// its originating [`ToolCallView`] and progress chunks. `None` for
193 /// providers that omit it (e.g. Gemini); fall back to [`name`](Self::name).
194 pub call_id: Option<&'a str>,
195 /// The tool/function name that produced this result.
196 pub name: &'a str,
197 /// The tool's JSON response payload.
198 pub response: &'a serde_json::Value,
199}
200
201impl Event {
202 /// Creates a new event with a generated UUID and current timestamp.
203 pub fn new(invocation_id: impl Into<String>) -> Self {
204 Self {
205 id: Uuid::new_v4().to_string(),
206 timestamp: Utc::now(),
207 invocation_id: invocation_id.into(),
208 branch: String::new(),
209 author: String::new(),
210 llm_response: LlmResponse::default(),
211 actions: EventActions::default(),
212 long_running_tool_ids: Vec::new(),
213 llm_request: None,
214 provider_metadata: HashMap::new(),
215 }
216 }
217
218 /// Create an event with a specific ID.
219 /// Use this for streaming events where all chunks should share the same event ID.
220 pub fn with_id(id: impl Into<String>, invocation_id: impl Into<String>) -> Self {
221 Self {
222 id: id.into(),
223 timestamp: Utc::now(),
224 invocation_id: invocation_id.into(),
225 branch: String::new(),
226 author: String::new(),
227 llm_response: LlmResponse::default(),
228 actions: EventActions::default(),
229 long_running_tool_ids: Vec::new(),
230 llm_request: None,
231 provider_metadata: HashMap::new(),
232 }
233 }
234
235 /// Creates a streaming tool-progress event.
236 ///
237 /// Tools emit these via [`ToolContext::emit_progress`](crate::ToolContext::emit_progress)
238 /// to push intermediate stdout/stderr to the client *while the tool is still
239 /// running*. The event carries the chunk as partial text content (role
240 /// `"tool"`) and is tagged with [`TOOL_PROGRESS_STREAM_KEY`] /
241 /// [`TOOL_PROGRESS_CALL_ID_KEY`] so consumers can distinguish it from a
242 /// final tool result and route it to the right terminal widget.
243 ///
244 /// # Example
245 ///
246 /// ```
247 /// use adk_core::Event;
248 ///
249 /// let event = Event::tool_progress("inv-1", "agent", "call-7", "stdout", "compiling...\n");
250 /// assert_eq!(event.tool_progress_stream(), Some("stdout"));
251 /// assert!(event.llm_response.partial);
252 /// ```
253 pub fn tool_progress(
254 invocation_id: impl Into<String>,
255 author: impl Into<String>,
256 function_call_id: impl Into<String>,
257 stream: impl Into<String>,
258 chunk: impl Into<String>,
259 ) -> Self {
260 let mut event = Event::new(invocation_id);
261 event.author = author.into();
262 event.llm_response.content = Some(Content {
263 role: "tool".to_string(),
264 parts: vec![crate::types::Part::Text { text: chunk.into() }],
265 });
266 // Partial so downstream aggregation/persistence treats it as a streaming
267 // chunk, never as the agent's final response.
268 event.llm_response.partial = true;
269 event.provider_metadata.insert(TOOL_PROGRESS_STREAM_KEY.to_string(), stream.into());
270 event
271 .provider_metadata
272 .insert(TOOL_PROGRESS_CALL_ID_KEY.to_string(), function_call_id.into());
273 event
274 }
275
276 /// Returns the progress stream name (`"stdout"`, `"stderr"`, …) if this is a
277 /// tool-progress event produced by [`ToolContext::emit_progress`](crate::ToolContext::emit_progress),
278 /// otherwise `None`.
279 pub fn tool_progress_stream(&self) -> Option<&str> {
280 self.provider_metadata.get(TOOL_PROGRESS_STREAM_KEY).map(String::as_str)
281 }
282
283 /// Returns the tool calls carried by this event, as a typed, render-ready view.
284 ///
285 /// A UI consuming the agent's `EventStream` can call this on every event to
286 /// detect when the model requested one or more tools, without matching on
287 /// [`Part::FunctionCall`](crate::Part::FunctionCall) internals. Pair it with
288 /// [`tool_results`](Self::tool_results) and [`tool_progress_stream`](Self::tool_progress_stream)
289 /// to render a complete tool lifecycle (call → live progress → result).
290 ///
291 /// Returns an empty vector for events that contain no tool calls.
292 ///
293 /// # Correlation
294 ///
295 /// Use [`ToolCallView::call_id`] to correlate a call with its progress chunks
296 /// and final result. For providers that omit call ids (e.g. Gemini), fall
297 /// back to [`ToolCallView::name`].
298 ///
299 /// # Example
300 ///
301 /// ```
302 /// use adk_core::{Content, Event, Part};
303 ///
304 /// let mut event = Event::new("inv-1");
305 /// event.llm_response.content = Some(Content {
306 /// role: "model".to_string(),
307 /// parts: vec![Part::FunctionCall {
308 /// name: "bash".to_string(),
309 /// args: serde_json::json!({ "command": "ls" }),
310 /// id: Some("call_1".to_string()),
311 /// thought_signature: None,
312 /// }],
313 /// });
314 ///
315 /// let calls = event.tool_calls();
316 /// assert_eq!(calls.len(), 1);
317 /// assert_eq!(calls[0].name, "bash");
318 /// assert_eq!(calls[0].call_id, Some("call_1"));
319 /// ```
320 pub fn tool_calls(&self) -> Vec<ToolCallView<'_>> {
321 let Some(content) = &self.llm_response.content else {
322 return Vec::new();
323 };
324 content
325 .parts
326 .iter()
327 .filter_map(|part| match part {
328 crate::types::Part::FunctionCall { name, args, id, .. } => {
329 Some(ToolCallView { call_id: id.as_deref(), name, args })
330 }
331 _ => None,
332 })
333 .collect()
334 }
335
336 /// Returns the tool results carried by this event, as a typed, render-ready view.
337 ///
338 /// After a tool executes, the agent yields its result on the same
339 /// `EventStream` as everything else, as a `function`-role event holding a
340 /// [`Part::FunctionResponse`](crate::Part::FunctionResponse). This accessor
341 /// surfaces those results generically so a UI can render the output of *any*
342 /// tool — streaming or not — without walking part internals.
343 ///
344 /// Returns an empty vector for events that contain no tool results.
345 ///
346 /// # Correlation
347 ///
348 /// Use [`ToolResultView::call_id`] to attach a result to the originating
349 /// [`tool_calls`](Self::tool_calls) entry and its progress chunks. For
350 /// providers that omit call ids, fall back to [`ToolResultView::name`].
351 ///
352 /// # Example
353 ///
354 /// ```
355 /// use adk_core::{Content, Event, FunctionResponseData, Part};
356 ///
357 /// let mut event = Event::new("inv-1");
358 /// event.llm_response.content = Some(Content {
359 /// role: "function".to_string(),
360 /// parts: vec![Part::FunctionResponse {
361 /// function_response: FunctionResponseData::new(
362 /// "bash",
363 /// serde_json::json!({ "stdout": "ok\n", "exit_code": 0 }),
364 /// ),
365 /// id: Some("call_1".to_string()),
366 /// annotations: None,
367 /// }],
368 /// });
369 ///
370 /// let results = event.tool_results();
371 /// assert_eq!(results.len(), 1);
372 /// assert_eq!(results[0].name, "bash");
373 /// assert_eq!(results[0].call_id, Some("call_1"));
374 /// assert_eq!(results[0].response["exit_code"], 0);
375 /// ```
376 pub fn tool_results(&self) -> Vec<ToolResultView<'_>> {
377 let Some(content) = &self.llm_response.content else {
378 return Vec::new();
379 };
380 content
381 .parts
382 .iter()
383 .filter_map(|part| match part {
384 crate::types::Part::FunctionResponse { function_response, id, .. } => {
385 Some(ToolResultView {
386 call_id: id.as_deref(),
387 name: &function_response.name,
388 response: &function_response.response,
389 })
390 }
391 _ => None,
392 })
393 .collect()
394 }
395
396 /// Convenience method to access content directly.
397 pub fn content(&self) -> Option<&Content> {
398 self.llm_response.content.as_ref()
399 }
400
401 /// Convenience method to set content directly.
402 pub fn set_content(&mut self, content: Content) {
403 self.llm_response.content = Some(content);
404 }
405
406 /// Returns the Interactions API interaction id for this event, if present.
407 ///
408 /// Reads the id from the flattened [`LlmResponse`], mirroring ADK-Python's
409 /// `event.interaction_id`. Returns `None` for events produced by the
410 /// generateContent transport and non-Gemini providers.
411 ///
412 /// # Example
413 ///
414 /// ```
415 /// use adk_core::Event;
416 ///
417 /// let mut event = Event::new("inv-123");
418 /// assert_eq!(event.interaction_id(), None);
419 ///
420 /// event.llm_response.interaction_id = Some("v1_abc".to_string());
421 /// assert_eq!(event.interaction_id(), Some("v1_abc"));
422 /// ```
423 pub fn interaction_id(&self) -> Option<&str> {
424 self.llm_response.interaction_id.as_deref()
425 }
426
427 /// Returns whether the event is the final response of an agent.
428 ///
429 /// Tool-start notifications, provider-native continuation pauses and compaction records
430 /// ([`EventActions::compaction`](crate::EventActions::compaction)) are not final.
431 ///
432 /// An event is considered final if:
433 /// - It has skip_summarization set, OR
434 /// - It has long_running_tool_ids (indicating async operations), OR
435 /// - It has no function calls, no function responses, is not partial,
436 /// and has no trailing code execution results.
437 ///
438 /// Note: When multiple agents participate in one invocation, there could be
439 /// multiple events with is_final_response() as true, for each participating agent.
440 pub fn is_final_response(&self) -> bool {
441 // A compaction record is not a response.
442 if self.actions.compaction.is_some() {
443 return false;
444 }
445 if self.provider_metadata.contains_key("adk_tool_started")
446 || self
447 .llm_response
448 .provider_metadata
449 .as_ref()
450 .and_then(|metadata| metadata.get("continue_turn"))
451 .and_then(serde_json::Value::as_bool)
452 == Some(true)
453 {
454 return false;
455 }
456
457 // If skip_summarization is set or we have long-running tools, it's final
458 if self.actions.skip_summarization || !self.long_running_tool_ids.is_empty() {
459 return true;
460 }
461
462 // Check content for function calls/responses
463 let has_function_calls = self.has_function_calls();
464 let has_function_responses = self.has_function_responses();
465 let is_partial = self.llm_response.partial;
466 let has_trailing_code_result = self.has_trailing_code_execution_result();
467
468 !has_function_calls && !has_function_responses && !is_partial && !has_trailing_code_result
469 }
470
471 /// Returns true if the event content contains function calls.
472 fn has_function_calls(&self) -> bool {
473 if let Some(content) = &self.llm_response.content {
474 for part in &content.parts {
475 if matches!(part, crate::Part::FunctionCall { .. }) {
476 return true;
477 }
478 }
479 }
480 false
481 }
482
483 /// Returns true if the event content contains function responses.
484 fn has_function_responses(&self) -> bool {
485 if let Some(content) = &self.llm_response.content {
486 for part in &content.parts {
487 if matches!(part, crate::Part::FunctionResponse { .. }) {
488 return true;
489 }
490 }
491 }
492 false
493 }
494
495 /// Returns true if the event has a trailing code execution result.
496 #[allow(clippy::match_like_matches_macro)]
497 fn has_trailing_code_execution_result(&self) -> bool {
498 if let Some(content) = &self.llm_response.content
499 && let Some(last_part) = content.parts.last()
500 {
501 // FunctionResponse as the last part indicates a code execution result
502 // that the model still needs to process.
503 return matches!(last_part, crate::Part::FunctionResponse { .. });
504 }
505 false
506 }
507
508 /// Extracts function call IDs from this event's content.
509 /// Used to identify which function calls are associated with long-running tools.
510 pub fn function_call_ids(&self) -> Vec<String> {
511 let mut ids = Vec::new();
512 if let Some(content) = &self.llm_response.content {
513 for part in &content.parts {
514 if let crate::Part::FunctionCall { name, id, .. } = part {
515 // Use the actual call ID when available (OpenAI-style),
516 // fall back to name for providers that don't emit IDs (Gemini).
517 ids.push(id.as_deref().unwrap_or(name).to_string());
518 }
519 }
520 }
521 ids
522 }
523}
524
525/// Whether an event is visible from a given conversation branch.
526///
527/// An event is visible when its branch equals `invocation_branch` or is an
528/// *ancestor* of it. Siblings and descendants are excluded, which is what keeps
529/// concurrent `ParallelAgent` branches from seeing each other's output while
530/// still letting each one see the conversation that led to the fan-out.
531///
532/// An empty branch on either side means "unscoped" and matches everything, so
533/// events written without a branch stay globally visible and callers that never
534/// set a branch are unaffected.
535///
536/// Branch segments are delimited by `.`, and the prefix test requires that
537/// delimiter explicitly: without it `agent_0` would match `agent_00`. This
538/// mirrors ADK Python's `_is_event_belongs_to_branch` and ADK Go's
539/// `eventBelongsToBranch`.
540///
541/// # Example
542///
543/// ```
544/// use adk_core::event_belongs_to_branch;
545///
546/// // Own branch and ancestors are visible.
547/// assert!(event_belongs_to_branch("parent.parallel.a", "parent.parallel.a"));
548/// assert!(event_belongs_to_branch("parent.parallel.a", "parent"));
549///
550/// // A sibling branch is not.
551/// assert!(!event_belongs_to_branch("parent.parallel.a", "parent.parallel.b"));
552///
553/// // Unscoped events remain visible.
554/// assert!(event_belongs_to_branch("parent.parallel.a", ""));
555/// ```
556pub fn event_belongs_to_branch(invocation_branch: &str, event_branch: &str) -> bool {
557 if invocation_branch.is_empty() || event_branch.is_empty() {
558 return true;
559 }
560 if event_branch == invocation_branch {
561 return true;
562 }
563 // Require the delimiter so `agent_0` does not match `agent_00`.
564 invocation_branch.starts_with(event_branch)
565 && invocation_branch.as_bytes().get(event_branch.len()) == Some(&b'.')
566}
567
568#[cfg(test)]
569mod branch_visibility_tests {
570 use super::event_belongs_to_branch;
571
572 #[test]
573 fn own_branch_is_visible() {
574 assert!(event_belongs_to_branch("root.parallel.a", "root.parallel.a"));
575 }
576
577 #[test]
578 fn ancestor_branches_are_visible() {
579 assert!(event_belongs_to_branch("root.parallel.a", "root"));
580 assert!(event_belongs_to_branch("root.parallel.a", "root.parallel"));
581 }
582
583 #[test]
584 fn sibling_branches_are_hidden() {
585 assert!(!event_belongs_to_branch("root.parallel.a", "root.parallel.b"));
586 assert!(!event_belongs_to_branch("root.parallel.b", "root.parallel.a"));
587 }
588
589 #[test]
590 fn descendant_branches_are_hidden() {
591 // A parent must not see what a nested child produced in its own branch.
592 assert!(!event_belongs_to_branch("root", "root.parallel.a"));
593 }
594
595 #[test]
596 fn empty_branch_on_either_side_matches() {
597 assert!(event_belongs_to_branch("", "root.parallel.a"));
598 assert!(event_belongs_to_branch("root.parallel.a", ""));
599 assert!(event_belongs_to_branch("", ""));
600 }
601
602 #[test]
603 fn prefix_match_requires_the_delimiter() {
604 // The bug the delimiter guards against: `agent_0` vs `agent_00`.
605 assert!(!event_belongs_to_branch("root.agent_00", "root.agent_0"));
606 assert!(event_belongs_to_branch("root.agent_0.child", "root.agent_0"));
607 }
608}
609
610#[cfg(test)]
611mod tests {
612 use super::*;
613 use crate::Part;
614
615 #[test]
616 fn test_event_creation() {
617 let event = Event::new("inv-123");
618 assert_eq!(event.invocation_id, "inv-123");
619 assert!(!event.id.is_empty());
620 }
621
622 #[test]
623 fn test_event_actions_default() {
624 let actions = EventActions::default();
625 assert!(actions.state_delta.is_empty());
626 assert!(!actions.skip_summarization);
627 assert!(actions.tool_confirmation.is_none());
628 assert!(actions.tool_confirmation_decision.is_none());
629 }
630
631 #[test]
632 fn test_state_prefixes() {
633 assert_eq!(KEY_PREFIX_APP, "app:");
634 assert_eq!(KEY_PREFIX_TEMP, "temp:");
635 assert_eq!(KEY_PREFIX_USER, "user:");
636 }
637
638 #[test]
639 fn test_is_final_response_no_content() {
640 let event = Event::new("inv-123");
641 // No content, no function calls -> final
642 assert!(event.is_final_response());
643 }
644
645 #[test]
646 fn tool_start_is_not_final() {
647 let mut event = Event::new("inv-123");
648 event.provider_metadata.insert(
649 "adk_tool_started".into(),
650 serde_json::json!({"id": "call-1", "name": "search"}).to_string(),
651 );
652 assert!(!event.llm_response.partial);
653 assert!(!event.is_final_response());
654 }
655
656 #[test]
657 fn provider_continuation_is_not_final() {
658 for content in [None, Some(Content::new("model").with_text("Searching"))] {
659 let mut event = Event::new("inv-123");
660 event.llm_response.content = content;
661 event.llm_response.provider_metadata = Some(serde_json::json!({"continue_turn": true}));
662 assert!(!event.is_final_response());
663 event.llm_response.provider_metadata =
664 Some(serde_json::json!({"continue_turn": false}));
665 assert!(event.is_final_response());
666 }
667 }
668
669 #[test]
670 fn test_is_final_response_text_only() {
671 let mut event = Event::new("inv-123");
672 event.llm_response.content = Some(Content {
673 role: "model".to_string(),
674 parts: vec![Part::Text { text: "Hello!".to_string() }],
675 });
676 // Text only, no function calls -> final
677 assert!(event.is_final_response());
678 }
679
680 #[test]
681 fn test_is_final_response_with_function_call() {
682 let mut event = Event::new("inv-123");
683 event.llm_response.content = Some(Content {
684 role: "model".to_string(),
685 parts: vec![Part::FunctionCall {
686 name: "get_weather".to_string(),
687 args: serde_json::json!({"city": "NYC"}),
688 id: Some("call_123".to_string()),
689 thought_signature: None,
690 }],
691 });
692 // Has function call -> NOT final (need to execute it)
693 assert!(!event.is_final_response());
694 }
695
696 #[test]
697 fn test_is_final_response_with_function_response() {
698 let mut event = Event::new("inv-123");
699 event.llm_response.content = Some(Content {
700 role: "function".to_string(),
701 parts: vec![Part::FunctionResponse {
702 function_response: crate::FunctionResponseData::new(
703 "get_weather",
704 serde_json::json!({"temp": 72}),
705 ),
706 id: Some("call_123".to_string()),
707 annotations: None,
708 }],
709 });
710 // Has function response -> NOT final (model needs to respond)
711 assert!(!event.is_final_response());
712 }
713
714 #[test]
715 fn test_is_final_response_partial() {
716 let mut event = Event::new("inv-123");
717 event.llm_response.partial = true;
718 event.llm_response.content = Some(Content {
719 role: "model".to_string(),
720 parts: vec![Part::Text { text: "Hello...".to_string() }],
721 });
722 // Partial response -> NOT final
723 assert!(!event.is_final_response());
724 }
725
726 #[test]
727 fn test_is_final_response_skip_summarization() {
728 let mut event = Event::new("inv-123");
729 event.actions.skip_summarization = true;
730 event.llm_response.content = Some(Content {
731 role: "function".to_string(),
732 parts: vec![Part::FunctionResponse {
733 function_response: crate::FunctionResponseData::new(
734 "tool",
735 serde_json::json!({"result": "done"}),
736 ),
737 id: Some("call_tool".to_string()),
738 annotations: None,
739 }],
740 });
741 // Even with function response, skip_summarization makes it final
742 assert!(event.is_final_response());
743 }
744
745 #[test]
746 fn test_is_final_response_long_running_tool_ids() {
747 let mut event = Event::new("inv-123");
748 event.long_running_tool_ids = vec!["process_video".to_string()];
749 event.llm_response.content = Some(Content {
750 role: "model".to_string(),
751 parts: vec![Part::FunctionCall {
752 name: "process_video".to_string(),
753 args: serde_json::json!({"file": "video.mp4"}),
754 id: Some("call_process".to_string()),
755 thought_signature: None,
756 }],
757 });
758 // Has long_running_tool_ids -> final (async operation started)
759 assert!(event.is_final_response());
760 }
761
762 #[test]
763 fn test_function_call_ids() {
764 let mut event = Event::new("inv-123");
765 event.llm_response.content = Some(Content {
766 role: "model".to_string(),
767 parts: vec![
768 Part::FunctionCall {
769 name: "get_weather".to_string(),
770 args: serde_json::json!({}),
771 id: Some("call_1".to_string()),
772 thought_signature: None,
773 },
774 Part::Text { text: "I'll check the weather".to_string() },
775 Part::FunctionCall {
776 name: "get_time".to_string(),
777 args: serde_json::json!({}),
778 id: Some("call_2".to_string()),
779 thought_signature: None,
780 },
781 ],
782 });
783
784 let ids = event.function_call_ids();
785 assert_eq!(ids.len(), 2);
786 // Should use actual call IDs, not function names
787 assert!(ids.contains(&"call_1".to_string()));
788 assert!(ids.contains(&"call_2".to_string()));
789 }
790
791 #[test]
792 fn test_function_call_ids_falls_back_to_name() {
793 let mut event = Event::new("inv-123");
794 event.llm_response.content = Some(Content {
795 role: "model".to_string(),
796 parts: vec![Part::FunctionCall {
797 name: "get_weather".to_string(),
798 args: serde_json::json!({}),
799 id: None, // Gemini-style: no explicit ID
800 thought_signature: None,
801 }],
802 });
803
804 let ids = event.function_call_ids();
805 assert_eq!(ids, vec!["get_weather".to_string()]);
806 }
807
808 #[test]
809 fn test_function_call_ids_empty() {
810 let event = Event::new("inv-123");
811 let ids = event.function_call_ids();
812 assert!(ids.is_empty());
813 }
814
815 #[test]
816 fn test_is_final_response_trailing_function_response() {
817 // Text followed by a function response as the last part —
818 // has_trailing_code_execution_result should catch this even though
819 // has_function_responses also catches it.
820 let mut event = Event::new("inv-123");
821 event.llm_response.content = Some(Content {
822 role: "model".to_string(),
823 parts: vec![
824 Part::Text { text: "Running code...".to_string() },
825 Part::FunctionResponse {
826 function_response: crate::FunctionResponseData::new(
827 "code_exec",
828 serde_json::json!({"output": "42"}),
829 ),
830 id: Some("call_exec".to_string()),
831 annotations: None,
832 },
833 ],
834 });
835 // Trailing function response -> NOT final
836 assert!(!event.is_final_response());
837 }
838
839 #[test]
840 fn test_event_roundtrip_with_both_provider_metadata() {
841 let mut event = Event::new("inv-1");
842 event.provider_metadata.insert("adk.tool_progress.stream".into(), "stdout".into());
843 event.provider_metadata.insert("adk.tool_progress.call_id".into(), "call-7".into());
844 event.llm_response.provider_metadata = Some(serde_json::json!({"response_id": "resp-xyz"}));
845
846 let json = serde_json::to_string(&event).expect("serialize");
847 // Round-trip must succeed — regression test for the duplicate
848 // `provider_metadata` flatten collision with LlmResponse.
849 let back: Event = serde_json::from_str(&json)
850 .expect("round-trip must succeed without duplicate field error");
851
852 assert_eq!(
853 back.provider_metadata.get("adk.tool_progress.stream").map(String::as_str),
854 Some("stdout"),
855 );
856 assert_eq!(
857 back.provider_metadata.get("adk.tool_progress.call_id").map(String::as_str),
858 Some("call-7"),
859 );
860 assert_eq!(
861 back.llm_response.provider_metadata,
862 Some(serde_json::json!({"response_id": "resp-xyz"})),
863 );
864 }
865
866 #[test]
867 fn test_is_final_response_text_after_function_response() {
868 // Function response followed by text — the trailing part is text,
869 // so has_trailing_code_execution_result is false, but
870 // has_function_responses is still true.
871 let mut event = Event::new("inv-123");
872 event.llm_response.content = Some(Content {
873 role: "model".to_string(),
874 parts: vec![
875 Part::FunctionResponse {
876 function_response: crate::FunctionResponseData::new(
877 "tool",
878 serde_json::json!({}),
879 ),
880 id: Some("call_1".to_string()),
881 annotations: None,
882 },
883 Part::Text { text: "Done".to_string() },
884 ],
885 });
886 // Still has function responses -> NOT final
887 assert!(!event.is_final_response());
888 }
889}