Skip to main content

adk_server/agent_engine/
operations.rs

1//! Class-method dispatch for the Agent Engine runtime contract.
2//!
3//! # Anti-corruption layer
4//!
5//! This module deliberately contains a Python-reflection-shaped protocol: the
6//! platform dispatches on method-name strings because adk-python resolves
7//! operations with `getattr`. The foreignness stays here — typed request
8//! structs are produced at the boundary and nothing string-dispatched leaks
9//! into `adk-core` or `adk-runner`.
10//!
11//! # Sync/async name pairs
12//!
13//! `create_session` / `async_create_session` (and the other session CRUD
14//! pairs) are wire-parity aliases mapping to the same handler. adk-rust is
15//! async throughout; the [`ApiMode`] split exists only because adk-python
16//! exposes both sync and async Python methods and the platform routes them
17//! through different API modes.
18//!
19//! # asyncQuery (durable query jobs)
20//!
21//! The platform also exposes `reasoningEngines:asyncQuery`
22//! (`AsyncQueryReasoningEngine`). It is **not** registered here: the
23//! capability must be declared at engine create time and cannot be added to
24//! an engine post-create (google/adk-python#6220), and adk-python's `AdkApp`
25//! does not register it either — strict parity excludes it. Deployments that
26//! need durable query jobs must front the engine with their own job store.
27
28use 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
35/// Maximum number of events serialized into a session dump, mirroring the
36/// cap used by the REST session controller.
37const MAX_EVENTS: usize = 10_000;
38
39/// The platform API mode an operation is registered under.
40///
41/// Wire values are the keys of the `register_operations` map: `""`, `async`,
42/// `stream`, and `async_stream`.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum ApiMode {
45    /// Default (unary) mode, registered under `""`.
46    Sync,
47    /// Async unary mode, registered under `"async"`.
48    Async,
49    /// Streaming mode, registered under `"stream"`.
50    Stream,
51    /// Async streaming mode, registered under `"async_stream"`.
52    AsyncStream,
53}
54
55impl ApiMode {
56    /// Returns the wire key for this mode in the `register_operations` map.
57    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    /// Whether operations in this mode stream newline-delimited JSON.
67    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/// One dispatchable operation of the Agent Engine contract.
76///
77/// The variant set is the exact operation set adk-python's `AdkApp` registers
78/// (verification task V2, `google-cloud-aiplatform` 1.112 / `google-adk`
79/// 2.6.3), plus `register_operations` itself.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum ClassMethod {
82    /// `create_session` — session CRUD, default mode.
83    CreateSession,
84    /// `async_create_session` — wire-parity alias of [`Self::CreateSession`].
85    AsyncCreateSession,
86    /// `get_session` — session CRUD, default mode.
87    GetSession,
88    /// `async_get_session` — wire-parity alias of [`Self::GetSession`].
89    AsyncGetSession,
90    /// `list_sessions` — session CRUD, default mode.
91    ListSessions,
92    /// `async_list_sessions` — wire-parity alias of [`Self::ListSessions`].
93    AsyncListSessions,
94    /// `delete_session` — session CRUD, default mode.
95    DeleteSession,
96    /// `async_delete_session` — wire-parity alias of [`Self::DeleteSession`].
97    AsyncDeleteSession,
98    /// `stream_query` — run the agent, streaming ADK events.
99    StreamQuery,
100    /// `async_stream_query` — wire-parity alias of [`Self::StreamQuery`].
101    AsyncStreamQuery,
102    /// `streaming_agent_run_with_events` — run the agent from an ADK
103    /// `AgentRunRequest` JSON string (console Playground path).
104    StreamingAgentRunWithEvents,
105    /// `async_add_session_to_memory` — extract a session's events into the
106    /// configured memory service.
107    AsyncAddSessionToMemory,
108    /// `async_search_memory` — search the configured memory service.
109    AsyncSearchMemory,
110    /// `register_operations` — advertise the operation map to the host.
111    RegisterOperations,
112}
113
114impl ClassMethod {
115    /// Every dispatchable operation, in registration order.
116    ///
117    /// The `register_operations` output is derived from this list, so the
118    /// advertised operation set and the dispatcher cannot drift.
119    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    /// Returns the wire name of this operation.
137    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    /// Returns the platform API mode this operation is registered under.
157    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// ── Typed inputs ─────────────────────────────────────────────────────────
211//
212// Each operation deserializes its `input` value into one of these structs
213// immediately at the dispatch boundary; handlers never see raw JSON.
214
215/// Input for `create_session` / `async_create_session`.
216#[derive(Debug, Deserialize)]
217pub struct CreateSessionInput {
218    /// Session owner.
219    pub user_id: String,
220    /// Optional caller-chosen session ID; generated when absent.
221    pub session_id: Option<String>,
222    /// Optional initial session state.
223    pub state: Option<Map<String, Value>>,
224}
225
226/// Input for `get_session` / `async_get_session`.
227#[derive(Debug, Deserialize)]
228pub struct GetSessionInput {
229    /// Session owner.
230    pub user_id: String,
231    /// Session to retrieve.
232    pub session_id: String,
233}
234
235/// Input for `list_sessions` / `async_list_sessions`.
236#[derive(Debug, Deserialize)]
237pub struct ListSessionsInput {
238    /// User whose sessions are listed.
239    pub user_id: String,
240}
241
242/// Input for `delete_session` / `async_delete_session`.
243#[derive(Debug, Deserialize)]
244pub struct DeleteSessionInput {
245    /// Session owner.
246    pub user_id: String,
247    /// Session to delete.
248    pub session_id: String,
249}
250
251/// Input for `stream_query` / `async_stream_query`.
252#[derive(Debug, Deserialize)]
253pub struct StreamQueryInput {
254    /// Session owner.
255    pub user_id: String,
256    /// Optional session to continue; a new session is created when absent.
257    pub session_id: Option<String>,
258    /// The user message: either a plain string or a `Content` object,
259    /// matching adk-python's `str | dict` parameter.
260    pub message: Value,
261}
262
263/// Input for `streaming_agent_run_with_events`.
264#[derive(Debug, Deserialize)]
265pub struct StreamingAgentRunWithEventsInput {
266    /// An ADK `AgentRunRequest` as a JSON **string** — the console Playground
267    /// sends the request pre-serialized, matching adk-python's
268    /// `streaming_agent_run_with_events(request_json: str)`.
269    pub request_json: String,
270}
271
272/// The ADK `AgentRunRequest` carried inside
273/// [`StreamingAgentRunWithEventsInput::request_json`].
274///
275/// google-adk's model accepts both snake_case field names and camelCase
276/// aliases (`populate_by_name=True`); the serde aliases mirror that.
277#[derive(Debug, Deserialize)]
278pub struct AgentRunRequest {
279    /// Application name; accepted for wire parity. The runner's own app name
280    /// governs session scoping, so a mismatched value is not an error.
281    #[serde(default, alias = "appName")]
282    pub app_name: Option<String>,
283    /// Session owner.
284    #[serde(alias = "userId")]
285    pub user_id: String,
286    /// Session to run in; created when it does not exist.
287    #[serde(alias = "sessionId")]
288    pub session_id: String,
289    /// The user message.
290    #[serde(alias = "newMessage")]
291    pub new_message: Content,
292    /// Accepted for wire parity; HTTP framing (unary vs streaming endpoint)
293    /// decides the response shape, not this flag.
294    #[serde(default)]
295    pub streaming: bool,
296    /// Optional state delta applied to the session before the run.
297    #[serde(default, alias = "stateDelta")]
298    pub state_delta: Option<Map<String, Value>>,
299}
300
301/// Input for `async_add_session_to_memory`.
302#[derive(Debug, Deserialize)]
303pub struct AddSessionToMemoryInput {
304    /// Session owner.
305    pub user_id: String,
306    /// Session whose events are extracted into memory.
307    pub session_id: String,
308}
309
310/// Input for `async_search_memory`.
311#[derive(Debug, Deserialize)]
312pub struct SearchMemoryInput {
313    /// User whose memory is searched.
314    pub user_id: String,
315    /// Search query.
316    pub query: String,
317}
318
319/// Deserializes an operation's `input` into its typed request struct.
320///
321/// A missing `input` is treated as `{}` so operations whose fields are all
322/// optional (and `register_operations`, which takes none) accept an absent
323/// field.
324pub(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
336// ── Handlers ─────────────────────────────────────────────────────────────
337
338/// Serializes a session in the `AdkApp` dump shape: snake_case keys, events
339/// inline, `last_update_time` as float seconds (Python parity).
340pub(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
358/// Handles `create_session` / `async_create_session`.
359pub(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
377/// Handles `get_session` / `async_get_session`.
378pub(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
395/// Handles `list_sessions` / `async_list_sessions`.
396pub(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
414/// Handles `delete_session` / `async_delete_session`.
415pub(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
430/// Handles `register_operations`.
431///
432/// The map is derived from [`ClassMethod::ALL`] grouped by
433/// [`ClassMethod::api_mode`], so it cannot drift from the dispatcher.
434pub(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
447/// The error returned by the memory class methods when no memory service is
448/// configured — every deployment until the Memory Bank backend lands.
449fn 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
460/// Handles `async_add_session_to_memory`.
461///
462/// Fetches the session, converts its content-bearing events into
463/// [`adk_memory::MemoryEntry`] items, and adds them to the memory service —
464/// the trait takes pre-extracted entries, not a session.
465pub(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
499/// Handles `async_search_memory`.
500pub(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
531/// Resolves the message value of `stream_query` into a [`Content`].
532///
533/// A JSON string becomes a single-part user message; an object is
534/// deserialized as a full `Content`, matching adk-python's `str | dict`.
535pub(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
555/// Returns the session ID to run in, creating the session when it does not
556/// exist (or when no ID was supplied), and whether it was created.
557///
558/// Matches `AdkApp.stream_query`: a supplied ID that has no session record is
559/// created with that ID rather than rejected.
560pub(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                // A concurrent request created it first.
595                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
603/// Applies a state delta to an existing session by appending a
604/// state-delta-only event, mirroring the REST runtime's behavior.
605pub(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
628/// Validates and types the identity pair for a runner invocation.
629pub(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        // Same multiset: every variant advertised exactly once.
664        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}