use std::any::Any;
use std::sync::Arc;
use async_trait::async_trait;
use chrono::{DateTime, TimeZone, Utc};
use gadk_genai::{Content, FunctionCall, FunctionResponse, Part};
use gadk_model::LlmResponse;
use gadk_platform::Platform;
use gadk_session::compaction::{Config, SummarizeResult, Summarizer};
use gadk_session::{
Event, EventActions, EventCompaction, EventRef, Session, SessionError, State, ToolConfirmation,
zero_time,
};
use parking_lot::Mutex;
use serde_json::{Map, Value, json};
use super::compactor::sliding_window;
use super::tail_retention::{TokenCounter, TurnScope, tail_retention};
use super::{BoxError, ProgressGate};
pub(crate) fn at(n: i64) -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap() + chrono::Duration::seconds(n)
}
pub(crate) fn ids(events: &[Event]) -> Vec<String> {
events.iter().map(|e| e.id.clone()).collect()
}
pub(crate) fn strs(v: &[&str]) -> Vec<String> {
v.iter().map(|s| (*s).to_owned()).collect()
}
pub(crate) fn new_event(
id: &str,
invocation_id: &str,
ts: i64,
author: &str,
parts: Vec<Part>,
) -> Event {
Event {
id: id.into(),
invocation_id: invocation_id.into(),
timestamp: at(ts),
author: author.into(),
response: LlmResponse {
content: (!parts.is_empty()).then(|| Content {
role: author.into(),
parts,
}),
..Default::default()
},
..Default::default()
}
}
pub(crate) fn text_event(id: &str, invocation_id: &str, ts: i64, text: &str) -> Event {
new_event(id, invocation_id, ts, "user", vec![Part::from_text(text)])
}
pub(crate) fn model_text_event(id: &str, invocation_id: &str, ts: i64, text: &str) -> Event {
new_event(id, invocation_id, ts, "model", vec![Part::from_text(text)])
}
fn call_part(call_id: &str) -> Part {
Part {
function_call: Some(FunctionCall {
id: call_id.into(),
name: format!("tool_{call_id}"),
..Default::default()
}),
..Default::default()
}
}
pub(crate) fn call_event(id: &str, invocation_id: &str, ts: i64, call_id: &str) -> Event {
new_event(id, invocation_id, ts, "model", vec![call_part(call_id)])
}
pub(crate) fn multi_call_event(id: &str, invocation_id: &str, ts: i64, call_ids: &[&str]) -> Event {
new_event(
id,
invocation_id,
ts,
"model",
call_ids.iter().map(|c| call_part(c)).collect(),
)
}
pub(crate) fn response_event(id: &str, invocation_id: &str, ts: i64, call_id: &str) -> Event {
let Value::Object(response) = json!({"result": "ok"}) else {
unreachable!()
};
new_event(
id,
invocation_id,
ts,
"user",
vec![Part {
function_response: Some(FunctionResponse {
id: call_id.into(),
name: format!("tool_{call_id}"),
response,
..Default::default()
}),
..Default::default()
}],
)
}
pub(crate) fn call_and_response_event(
id: &str,
invocation_id: &str,
ts: i64,
call_id: &str,
) -> Event {
new_event(
id,
invocation_id,
ts,
"model",
vec![
Part {
function_response: Some(FunctionResponse {
id: call_id.into(),
name: format!("tool_{call_id}"),
response: Map::new(),
..Default::default()
}),
..Default::default()
},
call_part(call_id),
],
)
}
pub(crate) fn confirmation_event(id: &str, invocation_id: &str, ts: i64, call_id: &str) -> Event {
let mut ev = new_event(id, invocation_id, ts, "model", vec![]);
ev.actions.requested_tool_confirmations.insert(
call_id.into(),
ToolConfirmation {
hint: "approve?".into(),
..Default::default()
},
);
ev
}
pub(crate) fn with_auth_request(mut ev: Event, call_id: &str) -> Event {
ev.actions.requested_auth_configs = [(
call_id.to_owned(),
gadk_session::toolauth::Config::default(),
)]
.into();
ev
}
pub(crate) fn compaction_event(
id: &str,
ts: i64,
start: i64,
end: i64,
summary: &str,
excluded: Vec<EventRef>,
) -> Event {
Event {
id: id.into(),
invocation_id: format!("compaction-{id}"),
timestamp: at(ts),
author: "user".into(),
actions: EventActions {
compaction: Some(EventCompaction {
start_timestamp: at(start),
end_timestamp: at(end),
compacted_content: Some(Content {
role: "model".into(),
parts: vec![Part::from_text(summary)],
}),
excluded_events: excluded,
}),
..Default::default()
},
..Default::default()
}
}
pub(crate) fn excl(invocation_id: &str, ts: i64) -> EventRef {
EventRef {
invocation_id: invocation_id.into(),
timestamp: at(ts),
}
}
pub(crate) async fn sliding_window_stored(
cfg: &Config,
sess: Option<&dyn Session>,
) -> Result<Option<Event>, BoxError> {
let (ev, finish) = sliding_window(&Platform::default(), cfg, sess, "").await?;
finish.finish(None, "");
Ok(ev)
}
pub(crate) async fn tail_retention_stored(
cfg: &Config,
sess: Option<&dyn Session>,
scope: &TurnScope,
estimate: Option<&TokenCounter>,
progress: Option<Arc<dyn ProgressGate>>,
) -> Result<Option<Event>, BoxError> {
let (ev, finish) =
tail_retention(&Platform::default(), cfg, sess, scope, estimate, progress).await?;
finish.finish(None, "");
Ok(ev)
}
struct EmptyState;
impl State for EmptyState {
fn get(&self, _key: &str) -> Result<Value, SessionError> {
Err(SessionError::StateKeyNotExist)
}
fn set(&self, _key: &str, _value: Value) -> Result<(), SessionError> {
Ok(())
}
fn all(&self) -> Vec<(String, Value)> {
Vec::new()
}
}
pub(crate) struct StaticSession {
events: Mutex<Vec<Event>>,
state: EmptyState,
}
impl StaticSession {
pub(crate) fn new(events: Vec<Event>) -> Arc<StaticSession> {
Arc::new(StaticSession {
events: Mutex::new(events),
state: EmptyState,
})
}
pub(crate) fn push(&self, ev: Event) {
self.events.lock().push(ev);
}
}
impl Session for StaticSession {
fn id(&self) -> &str {
"sess"
}
fn app_name(&self) -> &str {
"app"
}
fn user_id(&self) -> &str {
"user"
}
fn state(&self) -> &dyn State {
&self.state
}
fn events(&self) -> Vec<Event> {
self.events.lock().clone()
}
fn last_update_time(&self) -> DateTime<Utc> {
zero_time()
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[allow(non_camel_case_types)]
pub(crate) struct fakeSummarizer {
pub(crate) summary: String,
pub(crate) err: Option<String>,
windows: Mutex<Vec<Vec<String>>>,
}
impl fakeSummarizer {
pub(crate) fn new(summary: &str) -> Arc<fakeSummarizer> {
Arc::new(fakeSummarizer {
summary: summary.into(),
err: None,
windows: Mutex::new(Vec::new()),
})
}
pub(crate) fn failing(err: &str) -> Arc<fakeSummarizer> {
Arc::new(fakeSummarizer {
summary: String::new(),
err: Some(err.into()),
windows: Mutex::new(Vec::new()),
})
}
pub(crate) fn windows(&self) -> Vec<Vec<String>> {
self.windows.lock().clone()
}
}
#[async_trait]
impl Summarizer for fakeSummarizer {
async fn summarize_events(
&self,
events: &[Event],
) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>> {
self.windows.lock().push(ids(events));
if let Some(err) = &self.err {
return Err(err.clone().into());
}
if self.summary.is_empty() || events.is_empty() {
return Ok(SummarizeResult::default());
}
Ok(SummarizeResult {
content: Some(Content {
role: String::new(),
parts: vec![Part::from_text(self.summary.clone())],
}),
usage: None,
})
}
}