1use super::AgentEngineState;
29use adk_core::{AdkError, Content, ErrorCategory, ErrorComponent, Result, SessionId, UserId};
30use serde::Deserialize;
31use serde_json::{Map, Value, json};
32use std::collections::HashMap;
33use std::str::FromStr;
34
35const MAX_EVENTS: usize = 10_000;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum ApiMode {
45 Sync,
47 Async,
49 Stream,
51 AsyncStream,
53}
54
55impl ApiMode {
56 pub fn as_str(&self) -> &'static str {
58 match self {
59 ApiMode::Sync => "",
60 ApiMode::Async => "async",
61 ApiMode::Stream => "stream",
62 ApiMode::AsyncStream => "async_stream",
63 }
64 }
65
66 pub fn is_streaming(&self) -> bool {
68 match self {
69 ApiMode::Sync | ApiMode::Async => false,
70 ApiMode::Stream | ApiMode::AsyncStream => true,
71 }
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum ClassMethod {
82 CreateSession,
84 AsyncCreateSession,
86 GetSession,
88 AsyncGetSession,
90 ListSessions,
92 AsyncListSessions,
94 DeleteSession,
96 AsyncDeleteSession,
98 StreamQuery,
100 AsyncStreamQuery,
102 StreamingAgentRunWithEvents,
105 AsyncAddSessionToMemory,
108 AsyncSearchMemory,
110 RegisterOperations,
112}
113
114impl ClassMethod {
115 pub const ALL: [ClassMethod; 14] = [
120 ClassMethod::CreateSession,
121 ClassMethod::AsyncCreateSession,
122 ClassMethod::GetSession,
123 ClassMethod::AsyncGetSession,
124 ClassMethod::ListSessions,
125 ClassMethod::AsyncListSessions,
126 ClassMethod::DeleteSession,
127 ClassMethod::AsyncDeleteSession,
128 ClassMethod::StreamQuery,
129 ClassMethod::AsyncStreamQuery,
130 ClassMethod::StreamingAgentRunWithEvents,
131 ClassMethod::AsyncAddSessionToMemory,
132 ClassMethod::AsyncSearchMemory,
133 ClassMethod::RegisterOperations,
134 ];
135
136 pub fn as_str(&self) -> &'static str {
138 match self {
139 ClassMethod::CreateSession => "create_session",
140 ClassMethod::AsyncCreateSession => "async_create_session",
141 ClassMethod::GetSession => "get_session",
142 ClassMethod::AsyncGetSession => "async_get_session",
143 ClassMethod::ListSessions => "list_sessions",
144 ClassMethod::AsyncListSessions => "async_list_sessions",
145 ClassMethod::DeleteSession => "delete_session",
146 ClassMethod::AsyncDeleteSession => "async_delete_session",
147 ClassMethod::StreamQuery => "stream_query",
148 ClassMethod::AsyncStreamQuery => "async_stream_query",
149 ClassMethod::StreamingAgentRunWithEvents => "streaming_agent_run_with_events",
150 ClassMethod::AsyncAddSessionToMemory => "async_add_session_to_memory",
151 ClassMethod::AsyncSearchMemory => "async_search_memory",
152 ClassMethod::RegisterOperations => "register_operations",
153 }
154 }
155
156 pub fn api_mode(&self) -> ApiMode {
158 match self {
159 ClassMethod::CreateSession
160 | ClassMethod::GetSession
161 | ClassMethod::ListSessions
162 | ClassMethod::DeleteSession
163 | ClassMethod::RegisterOperations => ApiMode::Sync,
164 ClassMethod::AsyncCreateSession
165 | ClassMethod::AsyncGetSession
166 | ClassMethod::AsyncListSessions
167 | ClassMethod::AsyncDeleteSession
168 | ClassMethod::AsyncAddSessionToMemory
169 | ClassMethod::AsyncSearchMemory => ApiMode::Async,
170 ClassMethod::StreamQuery => ApiMode::Stream,
171 ClassMethod::AsyncStreamQuery | ClassMethod::StreamingAgentRunWithEvents => {
172 ApiMode::AsyncStream
173 }
174 }
175 }
176}
177
178impl FromStr for ClassMethod {
179 type Err = AdkError;
180
181 fn from_str(s: &str) -> Result<Self> {
182 match s {
183 "create_session" => Ok(ClassMethod::CreateSession),
184 "async_create_session" => Ok(ClassMethod::AsyncCreateSession),
185 "get_session" => Ok(ClassMethod::GetSession),
186 "async_get_session" => Ok(ClassMethod::AsyncGetSession),
187 "list_sessions" => Ok(ClassMethod::ListSessions),
188 "async_list_sessions" => Ok(ClassMethod::AsyncListSessions),
189 "delete_session" => Ok(ClassMethod::DeleteSession),
190 "async_delete_session" => Ok(ClassMethod::AsyncDeleteSession),
191 "stream_query" => Ok(ClassMethod::StreamQuery),
192 "async_stream_query" => Ok(ClassMethod::AsyncStreamQuery),
193 "streaming_agent_run_with_events" => Ok(ClassMethod::StreamingAgentRunWithEvents),
194 "async_add_session_to_memory" => Ok(ClassMethod::AsyncAddSessionToMemory),
195 "async_search_memory" => Ok(ClassMethod::AsyncSearchMemory),
196 "register_operations" => Ok(ClassMethod::RegisterOperations),
197 unknown => Err(AdkError::new(
198 ErrorComponent::Server,
199 ErrorCategory::InvalidInput,
200 "agent_engine.unknown_class_method",
201 format!(
202 "unknown class_method '{unknown}'; call register_operations for the \
203 supported operation set"
204 ),
205 )),
206 }
207 }
208}
209
210#[derive(Debug, Deserialize)]
217pub struct CreateSessionInput {
218 pub user_id: String,
220 pub session_id: Option<String>,
222 pub state: Option<Map<String, Value>>,
224}
225
226#[derive(Debug, Deserialize)]
228pub struct GetSessionInput {
229 pub user_id: String,
231 pub session_id: String,
233}
234
235#[derive(Debug, Deserialize)]
237pub struct ListSessionsInput {
238 pub user_id: String,
240}
241
242#[derive(Debug, Deserialize)]
244pub struct DeleteSessionInput {
245 pub user_id: String,
247 pub session_id: String,
249}
250
251#[derive(Debug, Deserialize)]
253pub struct StreamQueryInput {
254 pub user_id: String,
256 pub session_id: Option<String>,
258 pub message: Value,
261}
262
263#[derive(Debug, Deserialize)]
265pub struct StreamingAgentRunWithEventsInput {
266 pub request_json: String,
270}
271
272#[derive(Debug, Deserialize)]
278pub struct AgentRunRequest {
279 #[serde(default, alias = "appName")]
282 pub app_name: Option<String>,
283 #[serde(alias = "userId")]
285 pub user_id: String,
286 #[serde(alias = "sessionId")]
288 pub session_id: String,
289 #[serde(alias = "newMessage")]
291 pub new_message: Content,
292 #[serde(default)]
295 pub streaming: bool,
296 #[serde(default, alias = "stateDelta")]
298 pub state_delta: Option<Map<String, Value>>,
299}
300
301#[derive(Debug, Deserialize)]
303pub struct AddSessionToMemoryInput {
304 pub user_id: String,
306 pub session_id: String,
308}
309
310#[derive(Debug, Deserialize)]
312pub struct SearchMemoryInput {
313 pub user_id: String,
315 pub query: String,
317}
318
319pub(crate) fn typed_input<T: serde::de::DeserializeOwned>(input: Option<Value>) -> Result<T> {
325 let value = input.unwrap_or_else(|| Value::Object(Map::new()));
326 serde_json::from_value(value).map_err(|err| {
327 AdkError::new(
328 ErrorComponent::Server,
329 ErrorCategory::InvalidInput,
330 "agent_engine.invalid_input",
331 format!("input does not match the class_method's schema: {err}"),
332 )
333 })
334}
335
336pub(crate) fn session_to_value(session: &dyn adk_session::Session) -> Value {
341 let events: Vec<Value> = session
342 .events()
343 .all()
344 .into_iter()
345 .take(MAX_EVENTS)
346 .map(|event| serde_json::to_value(event).unwrap_or(Value::Null))
347 .collect();
348 json!({
349 "id": session.id(),
350 "app_name": session.app_name(),
351 "user_id": session.user_id(),
352 "state": session.state().all(),
353 "events": events,
354 "last_update_time": session.last_update_time().timestamp_millis() as f64 / 1000.0,
355 })
356}
357
358pub(crate) async fn handle_create_session(
360 state: &AgentEngineState,
361 input: CreateSessionInput,
362) -> Result<Value> {
363 let initial_state: HashMap<String, Value> =
364 input.state.unwrap_or_default().into_iter().collect();
365 let session = state
366 .session_service()
367 .create(adk_session::CreateRequest {
368 app_name: state.app_name().to_string(),
369 user_id: input.user_id,
370 session_id: input.session_id,
371 state: initial_state,
372 })
373 .await?;
374 Ok(session_to_value(session.as_ref()))
375}
376
377pub(crate) async fn handle_get_session(
379 state: &AgentEngineState,
380 input: GetSessionInput,
381) -> Result<Value> {
382 let session = state
383 .session_service()
384 .get(adk_session::GetRequest {
385 app_name: state.app_name().to_string(),
386 user_id: input.user_id,
387 session_id: input.session_id,
388 num_recent_events: None,
389 after: None,
390 })
391 .await?;
392 Ok(session_to_value(session.as_ref()))
393}
394
395pub(crate) async fn handle_list_sessions(
397 state: &AgentEngineState,
398 input: ListSessionsInput,
399) -> Result<Value> {
400 let sessions = state
401 .session_service()
402 .list(adk_session::ListRequest {
403 app_name: state.app_name().to_string(),
404 user_id: input.user_id,
405 limit: None,
406 offset: None,
407 })
408 .await?;
409 let sessions: Vec<Value> =
410 sessions.iter().map(|session| session_to_value(session.as_ref())).collect();
411 Ok(json!({ "sessions": sessions }))
412}
413
414pub(crate) async fn handle_delete_session(
416 state: &AgentEngineState,
417 input: DeleteSessionInput,
418) -> Result<Value> {
419 state
420 .session_service()
421 .delete(adk_session::DeleteRequest {
422 app_name: state.app_name().to_string(),
423 user_id: input.user_id,
424 session_id: input.session_id,
425 })
426 .await?;
427 Ok(Value::Null)
428}
429
430pub(crate) fn handle_register_operations() -> Value {
435 let mut map = Map::new();
436 for mode in [ApiMode::Sync, ApiMode::Async, ApiMode::Stream, ApiMode::AsyncStream] {
437 let names: Vec<Value> = ClassMethod::ALL
438 .iter()
439 .filter(|method| method.api_mode() == mode)
440 .map(|method| Value::String(method.as_str().to_string()))
441 .collect();
442 map.insert(mode.as_str().to_string(), Value::Array(names));
443 }
444 Value::Object(map)
445}
446
447fn memory_unavailable() -> AdkError {
450 AdkError::new(
451 ErrorComponent::Server,
452 ErrorCategory::Unsupported,
453 "agent_engine.memory_unavailable",
454 "no memory service is configured on this engine; configure one via \
455 AgentEngineState::with_memory_service (Memory Bank support arrives with the \
456 vertex memory backend)",
457 )
458}
459
460pub(crate) async fn handle_add_session_to_memory(
466 state: &AgentEngineState,
467 input: AddSessionToMemoryInput,
468) -> Result<Value> {
469 let Some(memory_service) = state.memory_service() else {
470 return Err(memory_unavailable());
471 };
472 let session = state
473 .session_service()
474 .get(adk_session::GetRequest {
475 app_name: state.app_name().to_string(),
476 user_id: input.user_id.clone(),
477 session_id: input.session_id.clone(),
478 num_recent_events: None,
479 after: None,
480 })
481 .await?;
482 let entries: Vec<adk_memory::MemoryEntry> = session
483 .events()
484 .all()
485 .into_iter()
486 .filter_map(|event| {
487 event.llm_response.content.clone().map(|content| {
488 adk_memory::MemoryEntry::new(content, event.author.clone())
489 .with_timestamp(event.timestamp)
490 })
491 })
492 .collect();
493 memory_service
494 .add_session(state.app_name(), &input.user_id, &input.session_id, entries)
495 .await?;
496 Ok(Value::Null)
497}
498
499pub(crate) async fn handle_search_memory(
501 state: &AgentEngineState,
502 input: SearchMemoryInput,
503) -> Result<Value> {
504 let Some(memory_service) = state.memory_service() else {
505 return Err(memory_unavailable());
506 };
507 let response = memory_service
508 .search(adk_memory::SearchRequest {
509 query: input.query,
510 user_id: input.user_id,
511 app_name: state.app_name().to_string(),
512 limit: None,
513 min_score: None,
514 project_id: None,
515 })
516 .await?;
517 let memories: Vec<Value> = response
518 .memories
519 .into_iter()
520 .map(|entry| {
521 json!({
522 "content": entry.content,
523 "author": entry.author,
524 "timestamp": entry.timestamp,
525 })
526 })
527 .collect();
528 Ok(json!({ "memories": memories }))
529}
530
531pub(crate) fn message_to_content(message: Value) -> Result<Content> {
536 match message {
537 Value::String(text) => Ok(Content::new("user").with_text(text)),
538 Value::Object(_) => serde_json::from_value(message).map_err(|err| {
539 AdkError::new(
540 ErrorComponent::Server,
541 ErrorCategory::InvalidInput,
542 "agent_engine.invalid_message",
543 format!("message object is not a valid Content: {err}"),
544 )
545 }),
546 other => Err(AdkError::new(
547 ErrorComponent::Server,
548 ErrorCategory::InvalidInput,
549 "agent_engine.invalid_message",
550 format!("message must be a string or a Content object, got {other}"),
551 )),
552 }
553}
554
555pub(crate) async fn resolve_session(
561 state: &AgentEngineState,
562 user_id: &str,
563 session_id: Option<String>,
564 initial_state: HashMap<String, Value>,
565) -> Result<(String, bool)> {
566 let session_id = match session_id {
567 Some(id) => id,
568 None => uuid::Uuid::new_v4().to_string(),
569 };
570 let existing = state
571 .session_service()
572 .get(adk_session::GetRequest {
573 app_name: state.app_name().to_string(),
574 user_id: user_id.to_string(),
575 session_id: session_id.clone(),
576 num_recent_events: None,
577 after: None,
578 })
579 .await;
580 match existing {
581 Ok(_) => Ok((session_id, false)),
582 Err(err) if err.is_not_found() => {
583 let created = state
584 .session_service()
585 .create(adk_session::CreateRequest {
586 app_name: state.app_name().to_string(),
587 user_id: user_id.to_string(),
588 session_id: Some(session_id.clone()),
589 state: initial_state,
590 })
591 .await;
592 match created {
593 Ok(_) => Ok((session_id, true)),
594 Err(err) if err.is_conflict() => Ok((session_id, false)),
596 Err(err) => Err(err),
597 }
598 }
599 Err(err) => Err(err),
600 }
601}
602
603pub(crate) async fn apply_state_delta(
606 state: &AgentEngineState,
607 user_id: &str,
608 session_id: &str,
609 state_delta: HashMap<String, Value>,
610) -> Result<()> {
611 if state_delta.is_empty() {
612 return Ok(());
613 }
614 let identity = adk_core::AdkIdentity {
615 app_name: adk_core::AppName::try_from(state.app_name())?,
616 user_id: adk_core::UserId::try_from(user_id)?,
617 session_id: adk_core::SessionId::try_from(session_id)?,
618 };
619 let mut event = adk_core::Event::new(format!("agent-engine-input-{}", uuid::Uuid::new_v4()));
620 event.author = "agent_engine_dispatch".to_string();
621 event.actions.state_delta = state_delta;
622 state
623 .session_service()
624 .append_event_for_identity(adk_session::AppendEventRequest { identity, event })
625 .await
626}
627
628pub(crate) fn typed_identity(user_id: &str, session_id: &str) -> Result<(UserId, SessionId)> {
630 let user_id = UserId::try_from(user_id)?;
631 let session_id = SessionId::try_from(session_id)?;
632 Ok((user_id, session_id))
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638
639 #[test]
640 fn class_method_round_trips_through_from_str() {
641 for method in ClassMethod::ALL {
642 assert_eq!(ClassMethod::from_str(method.as_str()).unwrap(), method);
643 }
644 }
645
646 #[test]
647 fn unknown_class_method_is_invalid_input() {
648 let err = ClassMethod::from_str("does_not_exist").unwrap_err();
649 assert_eq!(err.http_status_code(), 400);
650 }
651
652 #[test]
653 fn register_operations_covers_every_variant_exactly_once() {
654 let map = handle_register_operations();
655 let advertised: Vec<&str> = map
656 .as_object()
657 .unwrap()
658 .values()
659 .flat_map(|names| names.as_array().unwrap())
660 .map(|name| name.as_str().unwrap())
661 .collect();
662 let expected: Vec<&str> = ClassMethod::ALL.iter().map(ClassMethod::as_str).collect();
663 assert_eq!(advertised.len(), expected.len());
665 for name in expected {
666 assert_eq!(advertised.iter().filter(|n| **n == name).count(), 1, "{name}");
667 }
668 }
669
670 #[test]
671 fn api_modes_partition_the_streaming_endpoints() {
672 for method in ClassMethod::ALL {
673 let streaming = matches!(
674 method,
675 ClassMethod::StreamQuery
676 | ClassMethod::AsyncStreamQuery
677 | ClassMethod::StreamingAgentRunWithEvents
678 );
679 assert_eq!(method.api_mode().is_streaming(), streaming, "{}", method.as_str());
680 }
681 }
682
683 #[test]
684 fn agent_run_request_accepts_both_casings() {
685 let camel: AgentRunRequest = serde_json::from_str(
686 r#"{"appName":"a","userId":"u","sessionId":"s","newMessage":{"role":"user","parts":[{"text":"hi"}]}}"#,
687 )
688 .unwrap();
689 let snake: AgentRunRequest = serde_json::from_str(
690 r#"{"app_name":"a","user_id":"u","session_id":"s","new_message":{"role":"user","parts":[{"text":"hi"}]}}"#,
691 )
692 .unwrap();
693 assert_eq!(camel.user_id, snake.user_id);
694 assert_eq!(camel.session_id, snake.session_id);
695 assert_eq!(
696 serde_json::to_value(&camel.new_message).unwrap(),
697 serde_json::to_value(&snake.new_message).unwrap()
698 );
699 }
700}