1use 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
35pub fn zero_time() -> DateTime<Utc> {
37 DateTime::from_timestamp(ZERO_TIME_SECS, 0).unwrap_or(DateTime::<Utc>::MIN_UTC)
38}
39
40const ZERO_TIME_SECS: i64 = -62_135_596_800;
42const MAX_TIME_SECS: i64 = 253_402_300_799;
44
45pub(crate) mod go_time {
48 use chrono::{DateTime, Datelike, Utc};
49 use serde::{Deserialize, Deserializer, Serializer};
50
51 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#[derive(Debug, Clone, PartialEq, Serialize)]
81pub struct Event {
82 #[serde(flatten)]
84 pub response: LlmResponse,
85 pub id: String,
87 #[serde(serialize_with = "go_time::serialize")]
89 pub timestamp: DateTime<Utc>,
90 #[serde(rename = "invocationId")]
92 pub invocation_id: String,
93 #[serde(skip_serializing_if = "is_zero")]
95 pub branch: String,
96 #[serde(rename = "isolationScope", skip_serializing_if = "is_zero")]
98 pub isolation_scope: String,
99 pub author: String,
101 pub actions: EventActions,
103 #[serde(rename = "longRunningToolIds", skip_serializing_if = "Vec::is_empty")]
105 pub long_running_tool_ids: Vec<String>,
106 #[serde(skip_serializing_if = "Vec::is_empty")]
108 pub routes: Vec<String>,
109 #[serde(rename = "requestedInput", skip_serializing_if = "Option::is_none")]
111 pub requested_input: Option<RequestInput>,
112 #[serde(skip_serializing_if = "Option::is_none")]
114 pub output: Option<Value>,
115 #[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
140const 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
173const MIN_TIMESTAMP_MICROS: f64 = ZERO_TIME_SECS as f64 * 1e6;
175const MAX_TIMESTAMP_MICROS: f64 = MAX_TIME_SECS as f64 * 1e6;
176
177fn 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(µs) {
195 return Err(implausible());
196 }
197 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
206fn drop_nulls(map: &mut Map<String, Value>) {
209 map.retain(|_, v| !v.is_null());
210}
211
212#[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 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 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 pub fn is_final_response(&self) -> bool {
294 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 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#[derive(Debug, Clone, Default, PartialEq)]
329pub struct EventActions {
330 pub state_delta: Option<Map<String, Value>>,
332 pub artifact_delta: Option<BTreeMap<String, i64>>,
334 pub requested_tool_confirmations: BTreeMap<String, ToolConfirmation>,
336 pub requested_auth_configs: BTreeMap<String, crate::toolauth::Config>,
345 pub skip_summarization: bool,
347 pub transfer_to_agent: String,
349 pub escalate: bool,
351 pub compaction: Option<EventCompaction>,
353}
354
355const 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
439#[serde(rename_all = "camelCase")]
440pub struct EventCompaction {
441 #[serde(with = "go_time", default = "zero_time")]
443 pub start_timestamp: DateTime<Utc>,
444 #[serde(with = "go_time", default = "zero_time")]
446 pub end_timestamp: DateTime<Utc>,
447 #[serde(default)]
449 pub compacted_content: Option<Content>,
450 #[serde(default, skip_serializing_if = "Vec::is_empty")]
452 pub excluded_events: Vec<EventRef>,
453}
454
455#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
457#[serde(rename_all = "camelCase")]
458pub struct EventRef {
459 #[serde(default)]
461 pub invocation_id: String,
462 #[serde(with = "go_time", default = "zero_time")]
464 pub timestamp: DateTime<Utc>,
465}
466
467#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
469#[serde(default, rename_all = "camelCase")]
470pub struct NodeInfo {
471 #[serde(skip_serializing_if = "is_zero")]
473 pub path: String,
474 #[serde(skip_serializing_if = "is_zero")]
476 pub message_as_output: bool,
477 #[serde(skip_serializing_if = "Vec::is_empty")]
479 pub output_for: Vec<String>,
480}
481
482#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
484#[serde(default, rename_all = "camelCase")]
485pub struct RequestInput {
486 pub interrupt_id: String,
488 #[serde(skip_serializing_if = "is_zero")]
490 pub message: String,
491 #[serde(skip_serializing_if = "Option::is_none")]
493 pub response_schema: Option<Value>,
494 #[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}