Skip to main content

gadk_session/
event.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The `Event` family: the events of a session and their JSON encoding: the same keys and
17//! omission rules as ADK, RFC 3339 timestamps, numeric (adk-python) timestamps and
18//! case-insensitive (legacy) key matching on decode.
19
20use std::collections::BTreeMap;
21
22use chrono::{DateTime, Utc};
23use gadk_genai::Content;
24use gadk_genai::serde_util::is_zero;
25use gadk_model::LlmResponse;
26use gadk_platform::Platform;
27use serde::de::Error as _;
28use serde::ser::SerializeMap;
29use serde::{Deserialize, Deserializer, Serialize, Serializer};
30use serde_json::{Map, Value};
31
32use crate::legacy::normalize_keys;
33use crate::tool_confirmation::ToolConfirmation;
34
35/// The zero time, `0001-01-01T00:00:00Z`.
36pub fn zero_time() -> DateTime<Utc> {
37    DateTime::from_timestamp(ZERO_TIME_SECS, 0).unwrap_or(DateTime::<Utc>::MIN_UTC)
38}
39
40/// Unix seconds of `0001-01-01T00:00:00Z`.
41const ZERO_TIME_SECS: i64 = -62_135_596_800;
42/// Unix seconds of `9999-12-31T23:59:59Z`.
43const MAX_TIME_SECS: i64 = 253_402_300_799;
44
45/// Encodes and decodes a `DateTime<Utc>` as RFC 3339 with trailing-zero-trimmed nanoseconds;
46/// `null` decodes to [`zero_time`].
47pub(crate) mod go_time {
48    use chrono::{DateTime, Datelike, Utc};
49    use serde::{Deserialize, Deserializer, Serializer};
50
51    /// Formats `t` as RFC 3339 with trailing-zero-trimmed nanoseconds; `None` outside years
52    /// 0..=9999, which cannot be marshalled.
53    pub(crate) fn format(t: &DateTime<Utc>) -> Option<String> {
54        if !(0..=9999).contains(&t.year()) {
55            return None;
56        }
57        Some(gadk_platform::go_format_rfc3339_nano(t))
58    }
59
60    pub(crate) fn serialize<S: Serializer>(t: &DateTime<Utc>, s: S) -> Result<S::Ok, S::Error> {
61        match format(t) {
62            Some(v) => s.serialize_str(&v),
63            None => Err(serde::ser::Error::custom(
64                "Time.MarshalJSON: year outside of range [0,9999]",
65            )),
66        }
67    }
68
69    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<DateTime<Utc>, D::Error> {
70        match Option::<String>::deserialize(d)? {
71            None => Ok(super::zero_time()),
72            Some(s) => DateTime::parse_from_rfc3339(&s)
73                .map(|t| t.with_timezone(&Utc))
74                .map_err(serde::de::Error::custom),
75        }
76    }
77}
78
79/// An interaction in a conversation between agents and users.
80#[derive(Debug, Clone, PartialEq, Serialize)]
81pub struct Event {
82    /// The model response this event carries, flattened into the event's JSON.
83    #[serde(flatten)]
84    pub response: LlmResponse,
85    /// Set by storage.
86    pub id: String,
87    /// Set by storage; the zero time when unset.
88    #[serde(serialize_with = "go_time::serialize")]
89    pub timestamp: DateTime<Utc>,
90    /// Set by the agent context implementation.
91    #[serde(rename = "invocationId")]
92    pub invocation_id: String,
93    /// The branch of the event, like `agent_1.agent_2.agent_3`.
94    #[serde(skip_serializing_if = "is_zero")]
95    pub branch: String,
96    /// When set, the event is visible only to agent contexts with this exact isolation scope.
97    #[serde(rename = "isolationScope", skip_serializing_if = "is_zero")]
98    pub isolation_scope: String,
99    /// The name of the event's author.
100    pub author: String,
101    /// The actions taken by the agent.
102    pub actions: EventActions,
103    /// IDs of the long-running function calls.
104    #[serde(rename = "longRunningToolIds", skip_serializing_if = "Vec::is_empty")]
105    pub long_running_tool_ids: Vec<String>,
106    /// Routing information for workflow execution.
107    #[serde(skip_serializing_if = "Vec::is_empty")]
108    pub routes: Vec<String>,
109    /// When set, the emitting workflow node asks for human input and is about to pause.
110    #[serde(rename = "requestedInput", skip_serializing_if = "Option::is_none")]
111    pub requested_input: Option<RequestInput>,
112    /// Generic data output from a workflow node.
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub output: Option<Value>,
115    /// Workflow-node metadata; `None` for non-workflow events.
116    #[serde(rename = "nodeInfo", skip_serializing_if = "Option::is_none")]
117    pub node_info: Option<NodeInfo>,
118}
119
120impl Default for Event {
121    fn default() -> Self {
122        Self {
123            response: LlmResponse::default(),
124            id: String::new(),
125            timestamp: zero_time(),
126            invocation_id: String::new(),
127            branch: String::new(),
128            isolation_scope: String::new(),
129            author: String::new(),
130            actions: EventActions::default(),
131            long_running_tool_ids: Vec::new(),
132            routes: Vec::new(),
133            requested_input: None,
134            output: None,
135            node_info: None,
136        }
137    }
138}
139
140/// JSON names of `Event` and of its flattened `LlmResponse`, for case-insensitive decoding.
141const EVENT_KEYS: &[&str] = &[
142    "id",
143    "timestamp",
144    "invocationId",
145    "branch",
146    "isolationScope",
147    "author",
148    "actions",
149    "longRunningToolIds",
150    "routes",
151    "requestedInput",
152    "output",
153    "nodeInfo",
154    "content",
155    "citationMetadata",
156    "groundingMetadata",
157    "usageMetadata",
158    "customMetadata",
159    "logprobsResult",
160    "inputTranscription",
161    "outputTranscription",
162    "modelVersion",
163    "partial",
164    "turnComplete",
165    "interrupted",
166    "sessionResumptionHandle",
167    "errorCode",
168    "errorMessage",
169    "finishReason",
170    "avgLogprobs",
171];
172
173/// Bounds on a decoded numeric event timestamp, in microseconds: years 1 and 9999.
174const MIN_TIMESTAMP_MICROS: f64 = ZERO_TIME_SECS as f64 * 1e6;
175const MAX_TIMESTAMP_MICROS: f64 = MAX_TIME_SECS as f64 * 1e6;
176
177/// Decodes an event timestamp: an RFC 3339 string, a JSON number of epoch seconds
178/// (adk-python) resolved to microseconds, or `null`/absent for the zero time.
179fn decode_timestamp(raw: Option<Value>) -> Result<DateTime<Utc>, String> {
180    let raw = match raw {
181        None | Some(Value::Null) => return Ok(zero_time()),
182        Some(v) => v,
183    };
184    match &raw {
185        Value::String(s) => DateTime::parse_from_rfc3339(s)
186            .map(|t| t.with_timezone(&Utc))
187            .map_err(|e| format!("session: decoding event timestamp {raw}: {e}")),
188        Value::Number(n) => {
189            let secs = n
190                .as_f64()
191                .ok_or_else(|| format!("session: decoding event timestamp {raw}: not a number"))?;
192            let micros = (secs * 1e6).round();
193            let implausible = || format!("session: event timestamp {raw} is not a plausible date");
194            if micros.is_nan() || !(MIN_TIMESTAMP_MICROS..=MAX_TIMESTAMP_MICROS).contains(&micros) {
195                return Err(implausible());
196            }
197            // In range by the check above, so the conversion is exact.
198            DateTime::from_timestamp_micros(micros as i64).ok_or_else(implausible)
199        }
200        _ => Err(format!(
201            "session: decoding event timestamp {raw}: not a string or number"
202        )),
203    }
204}
205
206/// A `null` member decodes as if the key were absent, so a fresh value keeps its default;
207/// dropping null members gives that for every field.
208fn drop_nulls(map: &mut Map<String, Value>) {
209    map.retain(|_, v| !v.is_null());
210}
211
212/// `Event` minus `timestamp`, decoded after key normalization.
213#[derive(Default, Deserialize)]
214#[serde(default)]
215struct EventWire {
216    #[serde(flatten)]
217    response: LlmResponse,
218    id: String,
219    #[serde(rename = "invocationId")]
220    invocation_id: String,
221    branch: String,
222    #[serde(rename = "isolationScope")]
223    isolation_scope: String,
224    author: String,
225    actions: EventActions,
226    #[serde(rename = "longRunningToolIds")]
227    long_running_tool_ids: Vec<String>,
228    routes: Vec<String>,
229    #[serde(rename = "requestedInput")]
230    requested_input: Option<RequestInput>,
231    output: Option<Value>,
232    #[serde(rename = "nodeInfo")]
233    node_info: Option<NodeInfo>,
234}
235
236impl<'de> Deserialize<'de> for Event {
237    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
238        let mut map = Map::<String, Value>::deserialize(d)?;
239        normalize_keys(&mut map, EVENT_KEYS);
240        let timestamp = decode_timestamp(map.remove("timestamp")).map_err(D::Error::custom)?;
241        drop_nulls(&mut map);
242        let w: EventWire = serde_json::from_value(Value::Object(map)).map_err(D::Error::custom)?;
243        // adk-python writes a nodeInfo object on every event; an all-zero NodeInfo carries no
244        // information, so it is indistinguishable from absent.
245        let node_info = w.node_info.filter(|ni| *ni != NodeInfo::default());
246        Ok(Event {
247            response: w.response,
248            id: w.id,
249            timestamp,
250            invocation_id: w.invocation_id,
251            branch: w.branch,
252            isolation_scope: w.isolation_scope,
253            author: w.author,
254            actions: w.actions,
255            long_running_tool_ids: w.long_running_tool_ids,
256            routes: w.routes,
257            requested_input: w.requested_input,
258            output: w.output,
259            node_info,
260        })
261    }
262}
263
264impl Event {
265    /// Creates an event with an ID and timestamp from `platform` and both action delta maps
266    /// allocated.
267    ///
268    /// ```
269    /// use gadk_platform::Platform;
270    /// let p = Platform::deterministic(1);
271    /// let a = gadk_session::Event::new(&p, "inv");
272    /// let b = gadk_session::Event::new(&Platform::deterministic(1), "inv");
273    /// assert_eq!((a.id.clone(), a.timestamp), (b.id.clone(), b.timestamp));
274    /// assert_eq!(a.actions.state_delta, Some(Default::default()));
275    /// ```
276    pub fn new(platform: &Platform, invocation_id: impl Into<String>) -> Self {
277        Self {
278            id: platform.new_uuid(),
279            invocation_id: invocation_id.into(),
280            timestamp: platform.now(),
281            actions: EventActions {
282                state_delta: Some(Map::new()),
283                artifact_delta: Some(BTreeMap::new()),
284                ..Default::default()
285            },
286            ..Default::default()
287        }
288    }
289
290    /// Whether the event is the final response of an agent.
291    ///
292    /// When multiple agents participate in one invocation, each may produce a final response.
293    pub fn is_final_response(&self) -> bool {
294        // A compaction event is bookkeeping, not conversation.
295        if self.actions.compaction.is_some() {
296            return false;
297        }
298        if self.actions.skip_summarization || !self.long_running_tool_ids.is_empty() {
299            return true;
300        }
301        let parts = self
302            .response
303            .content
304            .as_ref()
305            .map(|c| c.parts.as_slice())
306            .unwrap_or_default();
307        let has_function_calls = parts.iter().any(|p| p.function_call.is_some());
308        let has_function_responses = parts.iter().any(|p| p.function_response.is_some());
309        // A complete error event ends the turn even when it carries a function response or a
310        // code execution result; only a function call keeps it open.
311        if !self.response.error_code.is_empty() && !self.response.partial && !has_function_calls {
312            return true;
313        }
314        let has_trailing_code_execution_result = parts
315            .last()
316            .is_some_and(|p| p.code_execution_result.is_some());
317        !has_function_calls
318            && !has_function_responses
319            && !self.response.partial
320            && !has_trailing_code_execution_result
321    }
322}
323
324/// The actions attached to an event.
325///
326/// `state_delta` and `artifact_delta` keep the `None`/empty distinction on the wire: `None`
327/// omits the key and `Some` writes it, even when empty; `null` is never written.
328#[derive(Debug, Clone, Default, PartialEq)]
329pub struct EventActions {
330    /// State changes, set by the agent context implementation.
331    pub state_delta: Option<Map<String, Value>>,
332    /// Artifact updates: filename to version.
333    pub artifact_delta: Option<BTreeMap<String, i64>>,
334    /// Tool confirmations requested, keyed by function call ID.
335    pub requested_tool_confirmations: BTreeMap<String, ToolConfirmation>,
336    /// The credential requests that tools made in this event, keyed by function call ID, since
337    /// one function response event can answer several calls.
338    ///
339    /// Session services persist a request and the Agent Engine server sends it to clients
340    /// unredacted, so it must not carry the secrets the tool was configured with: store the
341    /// output of [`crate::toolauth::Config::without_secrets`]. The in-memory, database and
342    /// Vertex AI session services refuse to append an event whose request does not decode as a
343    /// [`crate::toolauth::Config`] (see [`crate::state_util::check_requested_auth_configs`]).
344    pub requested_auth_configs: BTreeMap<String, crate::toolauth::Config>,
345    /// If true, the model is not called to summarize the function response.
346    pub skip_summarization: bool,
347    /// If set, the event transfers to the named agent.
348    pub transfer_to_agent: String,
349    /// The agent is escalating to a higher-level agent.
350    pub escalate: bool,
351    /// Marks this event as a context-compaction summary; written by the framework only.
352    pub compaction: Option<EventCompaction>,
353}
354
355/// JSON names of `EventActions`, for case-insensitive decoding.
356const ACTIONS_KEYS: &[&str] = &[
357    "stateDelta",
358    "artifactDelta",
359    "requestedToolConfirmations",
360    "requestedAuthConfigs",
361    "skipSummarization",
362    "transferToAgent",
363    "escalate",
364    "compaction",
365];
366
367impl Serialize for EventActions {
368    /// Writes keys in a fixed order: the promoted fields first, then the two delta-map
369    /// fields.
370    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
371        let mut m = s.serialize_map(None)?;
372        if !self.requested_tool_confirmations.is_empty() {
373            m.serialize_entry(
374                "requestedToolConfirmations",
375                &self.requested_tool_confirmations,
376            )?;
377        }
378        if !self.requested_auth_configs.is_empty() {
379            m.serialize_entry("requestedAuthConfigs", &self.requested_auth_configs)?;
380        }
381        if self.skip_summarization {
382            m.serialize_entry("skipSummarization", &true)?;
383        }
384        if !self.transfer_to_agent.is_empty() {
385            m.serialize_entry("transferToAgent", &self.transfer_to_agent)?;
386        }
387        if self.escalate {
388            m.serialize_entry("escalate", &true)?;
389        }
390        if let Some(c) = &self.compaction {
391            m.serialize_entry("compaction", c)?;
392        }
393        if let Some(d) = &self.state_delta {
394            m.serialize_entry("stateDelta", d)?;
395        }
396        if let Some(d) = &self.artifact_delta {
397            m.serialize_entry("artifactDelta", d)?;
398        }
399        m.end()
400    }
401}
402
403#[derive(Default, Deserialize)]
404#[serde(default, rename_all = "camelCase")]
405struct EventActionsWire {
406    state_delta: Option<Map<String, Value>>,
407    artifact_delta: Option<BTreeMap<String, i64>>,
408    requested_tool_confirmations: BTreeMap<String, ToolConfirmation>,
409    requested_auth_configs: BTreeMap<String, crate::toolauth::Config>,
410    skip_summarization: bool,
411    transfer_to_agent: String,
412    escalate: bool,
413    compaction: Option<EventCompaction>,
414}
415
416impl<'de> Deserialize<'de> for EventActions {
417    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
418        let mut map = Map::<String, Value>::deserialize(d)?;
419        normalize_keys(&mut map, ACTIONS_KEYS);
420        drop_nulls(&mut map);
421        let w: EventActionsWire =
422            serde_json::from_value(Value::Object(map)).map_err(D::Error::custom)?;
423        Ok(EventActions {
424            state_delta: w.state_delta,
425            artifact_delta: w.artifact_delta,
426            requested_tool_confirmations: w.requested_tool_confirmations,
427            requested_auth_configs: w.requested_auth_configs,
428            skip_summarization: w.skip_summarization,
429            transfer_to_agent: w.transfer_to_agent,
430            escalate: w.escalate,
431            compaction: w.compaction,
432        })
433    }
434}
435
436/// Records that a contiguous range of events has been replaced by one piece of content,
437/// typically a model-generated summary. Both bounds are inclusive.
438#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
439#[serde(rename_all = "camelCase")]
440pub struct EventCompaction {
441    /// Timestamp of the earliest covered event (inclusive).
442    #[serde(with = "go_time", default = "zero_time")]
443    pub start_timestamp: DateTime<Utc>,
444    /// Timestamp of the latest covered event (inclusive); never before `start_timestamp`.
445    #[serde(with = "go_time", default = "zero_time")]
446    pub end_timestamp: DateTime<Utc>,
447    /// The content that replaces the covered events in the prompt (`null` when `None`).
448    #[serde(default)]
449    pub compacted_content: Option<Content>,
450    /// Events inside the range that this summary does NOT stand in for.
451    #[serde(default, skip_serializing_if = "Vec::is_empty")]
452    pub excluded_events: Vec<EventRef>,
453}
454
455/// Identifies a stored event by fields that survive a storage round trip.
456#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
457#[serde(rename_all = "camelCase")]
458pub struct EventRef {
459    /// The event's invocation ID.
460    #[serde(default)]
461    pub invocation_id: String,
462    /// The event's timestamp.
463    #[serde(with = "go_time", default = "zero_time")]
464    pub timestamp: DateTime<Utc>,
465}
466
467/// Per-event metadata identifying the workflow node that emitted it.
468#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
469#[serde(default, rename_all = "camelCase")]
470pub struct NodeInfo {
471    /// Composite path of the emitting node within its workflow activation.
472    #[serde(skip_serializing_if = "is_zero")]
473    pub path: String,
474    /// This event's content is the node's output.
475    #[serde(skip_serializing_if = "is_zero")]
476    pub message_as_output: bool,
477    /// Node paths this event's output counts for.
478    #[serde(skip_serializing_if = "Vec::is_empty")]
479    pub output_for: Vec<String>,
480}
481
482/// A single human-in-the-loop prompt emitted by a workflow node.
483#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
484#[serde(default, rename_all = "camelCase")]
485pub struct RequestInput {
486    /// Correlates this request with the response that resumes it.
487    pub interrupt_id: String,
488    /// Human-readable description of what is being asked.
489    #[serde(skip_serializing_if = "is_zero")]
490    pub message: String,
491    /// JSON schema the response payload must conform to.
492    #[serde(skip_serializing_if = "Option::is_none")]
493    pub response_schema: Option<Value>,
494    /// Optional context the UI may render alongside the prompt.
495    #[serde(skip_serializing_if = "Option::is_none")]
496    pub payload: Option<Value>,
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502
503    #[test]
504    fn go_time_format_matches_rfc3339_nano() {
505        assert_eq!(
506            go_time::format(&zero_time()).as_deref(),
507            Some("0001-01-01T00:00:00Z")
508        );
509        let t = DateTime::from_timestamp(1733040000, 500_000_000).unwrap_or_default();
510        assert_eq!(
511            go_time::format(&t).as_deref(),
512            Some("2024-12-01T08:00:00.5Z")
513        );
514        let t = DateTime::from_timestamp(1733040000, 123_456_789).unwrap_or_default();
515        assert_eq!(
516            go_time::format(&t).as_deref(),
517            Some("2024-12-01T08:00:00.123456789Z")
518        );
519    }
520
521    #[test]
522    fn event_actions_key_order_matches_go() {
523        let a = EventActions {
524            state_delta: Some(Map::new()),
525            artifact_delta: Some(BTreeMap::new()),
526            transfer_to_agent: "w".into(),
527            escalate: true,
528            ..Default::default()
529        };
530        assert_eq!(
531            serde_json::to_string(&a).ok().as_deref(),
532            Some(r#"{"transferToAgent":"w","escalate":true,"stateDelta":{},"artifactDelta":{}}"#)
533        );
534    }
535
536    #[test]
537    fn is_final_response_ports_go() {
538        let mut e = Event::default();
539        assert!(e.is_final_response());
540        e.response.partial = true;
541        assert!(!e.is_final_response());
542        e.long_running_tool_ids = vec!["t".into()];
543        assert!(e.is_final_response());
544        e.actions.compaction = Some(EventCompaction {
545            start_timestamp: zero_time(),
546            end_timestamp: zero_time(),
547            compacted_content: None,
548            excluded_events: Vec::new(),
549        });
550        assert!(!e.is_final_response());
551    }
552}