Skip to main content

adk_server/agent_engine/
entrypoint.rs

1//! Turnkey entrypoint for Agent Engine BYOC containers.
2//!
3//! [`serve_agent_engine`] is the whole `main` of a deployable engine: it
4//! builds the dispatch app around an agent and serves it on `0.0.0.0:$PORT`.
5//! [`build_agent_engine_app`] exposes the same app as a plain [`Router`] for
6//! callers that manage their own listener or need to test without binding.
7
8use super::{AgentEngineState, agent_engine_router};
9use adk_core::{AdkError, Agent, ErrorCategory, ErrorComponent, Result};
10use axum::{Router, routing::get};
11use std::sync::Arc;
12use tracing::{info, warn};
13
14/// The port the platform assigns to the container.
15const ENV_PORT: &str = "PORT";
16/// GCP project of the deployment (set by the platform).
17const ENV_GOOGLE_CLOUD_PROJECT: &str = "GOOGLE_CLOUD_PROJECT";
18/// GCP location of the deployment (set by the platform).
19const ENV_GOOGLE_CLOUD_LOCATION: &str = "GOOGLE_CLOUD_LOCATION";
20/// The bare numeric engine ID (set by the platform inside deployed
21/// containers; not a full resource name).
22const ENV_GOOGLE_CLOUD_AGENT_ENGINE_ID: &str = "GOOGLE_CLOUD_AGENT_ENGINE_ID";
23
24/// The default port when neither `PORT` nor a port override is set.
25const DEFAULT_PORT: u16 = 8080;
26
27/// Options for [`serve_agent_engine`] and [`build_agent_engine_app`].
28///
29/// Every field is optional: the zero-configuration default serves the agent
30/// with an in-memory session service — enough to answer platform queries,
31/// but sessions do not survive a container restart. Production deployments
32/// configure managed backends:
33///
34/// - `session_service` — `VertexAiSessionService` (feature `vertex-session`
35///   in the consumer) picks up the platform's managed Sessions via
36///   `VertexAiSessionConfig::from_env()`, which reads the same
37///   `GOOGLE_CLOUD_*` variables the platform sets.
38/// - `artifact_service` — `GcsArtifactService` (feature `gcs` on
39///   `adk-artifact`) stores artifacts where the Gemini Enterprise console
40///   renders them; take the bucket from an environment variable or a flag.
41/// - `memory_service` — enables the `async_add_session_to_memory` /
42///   `async_search_memory` class methods; without one they return an
43///   `Unsupported` error.
44///
45/// # Example
46///
47/// ```rust,no_run
48/// use adk_server::agent_engine::AgentEngineOptions;
49///
50/// let opts = AgentEngineOptions::new().with_app_name("weather-agent");
51/// ```
52#[derive(Default)]
53pub struct AgentEngineOptions {
54    session_service: Option<Arc<dyn adk_session::SessionService>>,
55    memory_service: Option<Arc<dyn adk_memory::MemoryService>>,
56    artifact_service: Option<Arc<dyn adk_artifact::ArtifactService>>,
57    app_name: Option<String>,
58    port_override: Option<u16>,
59}
60
61impl AgentEngineOptions {
62    /// Creates empty options: in-memory sessions, no memory or artifact
63    /// service, app name from the agent, port from `$PORT`.
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    /// Sets the session persistence backend. Defaults to
69    /// `InMemorySessionService` when unset.
70    pub fn with_session_service(
71        mut self,
72        session_service: Arc<dyn adk_session::SessionService>,
73    ) -> Self {
74        self.session_service = Some(session_service);
75        self
76    }
77
78    /// Sets the memory service backing the memory class methods.
79    pub fn with_memory_service(
80        mut self,
81        memory_service: Arc<dyn adk_memory::MemoryService>,
82    ) -> Self {
83        self.memory_service = Some(memory_service);
84        self
85    }
86
87    /// Sets the artifact storage backend, wired into both the runner and the
88    /// dispatch state.
89    pub fn with_artifact_service(
90        mut self,
91        artifact_service: Arc<dyn adk_artifact::ArtifactService>,
92    ) -> Self {
93        self.artifact_service = Some(artifact_service);
94        self
95    }
96
97    /// Overrides the application name used for session scoping. Defaults to
98    /// the agent's name.
99    pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
100        self.app_name = Some(app_name.into());
101        self
102    }
103
104    /// Overrides the serving port, taking precedence over `$PORT`.
105    pub fn with_port(mut self, port: u16) -> Self {
106        self.port_override = Some(port);
107        self
108    }
109}
110
111/// The platform-reserved environment, read once at startup for logging and
112/// configuration hints.
113struct PlatformEnv {
114    project: Option<String>,
115    location: Option<String>,
116    engine_id: Option<String>,
117}
118
119impl PlatformEnv {
120    fn read() -> Self {
121        let read = |key: &str| {
122            std::env::var(key)
123                .ok()
124                .map(|value| value.trim().to_string())
125                .filter(|value| !value.is_empty())
126        };
127        Self {
128            project: read(ENV_GOOGLE_CLOUD_PROJECT),
129            location: read(ENV_GOOGLE_CLOUD_LOCATION),
130            engine_id: read(ENV_GOOGLE_CLOUD_AGENT_ENGINE_ID),
131        }
132    }
133
134    /// Whether the container appears to be running as a deployed engine.
135    fn is_managed(&self) -> bool {
136        self.engine_id.is_some()
137    }
138}
139
140/// Resolves the serving port: explicit override, then `$PORT`, then 8080.
141///
142/// # Errors
143///
144/// Returns an invalid-input error when `$PORT` is set but not a valid port
145/// number — a misconfigured port means the platform cannot reach the
146/// container, so failing at startup beats serving on the wrong port.
147fn resolve_port(port_override: Option<u16>) -> Result<u16> {
148    if let Some(port) = port_override {
149        return Ok(port);
150    }
151    match std::env::var(ENV_PORT) {
152        Ok(raw) => {
153            let trimmed = raw.trim();
154            if trimmed.is_empty() {
155                return Ok(DEFAULT_PORT);
156            }
157            trimmed.parse().map_err(|_| {
158                AdkError::new(
159                    ErrorComponent::Server,
160                    ErrorCategory::InvalidInput,
161                    "agent_engine.invalid_port",
162                    format!("PORT must be a port number in 1-65535, got '{trimmed}'"),
163                )
164            })
165        }
166        Err(_) => Ok(DEFAULT_PORT),
167    }
168}
169
170/// Builds the complete Agent Engine app for an agent: the dispatch router
171/// plus a `GET /health` liveness route.
172///
173/// Use this instead of [`serve_agent_engine`] when you manage the listener
174/// yourself (custom TLS, tests, graceful shutdown).
175///
176/// # Errors
177///
178/// Returns an error when the runner cannot be constructed — in practice,
179/// when the resolved app name fails identity validation.
180///
181/// # Example
182///
183/// ```rust,no_run
184/// use adk_server::agent_engine::{AgentEngineOptions, build_agent_engine_app};
185/// use std::sync::Arc;
186///
187/// # async fn serve(agent: Arc<dyn adk_core::Agent>) -> anyhow::Result<()> {
188/// let app = build_agent_engine_app(agent, AgentEngineOptions::new())?;
189/// let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
190/// axum::serve(listener, app).await?;
191/// # Ok(())
192/// # }
193/// ```
194pub fn build_agent_engine_app(agent: Arc<dyn Agent>, opts: AgentEngineOptions) -> Result<Router> {
195    let app_name = opts.app_name.unwrap_or_else(|| agent.name().to_string());
196    let env = PlatformEnv::read();
197    info!(
198        app.name = %app_name,
199        gcp.project = env.project.as_deref().unwrap_or(""),
200        gcp.location = env.location.as_deref().unwrap_or(""),
201        gcp.engine_id = env.engine_id.as_deref().unwrap_or(""),
202        "building agent engine app"
203    );
204
205    let session_service = match opts.session_service {
206        Some(session_service) => session_service,
207        None => {
208            if env.is_managed() {
209                // The platform sets GOOGLE_CLOUD_AGENT_ENGINE_ID inside deployed
210                // containers; an in-memory session store there loses every
211                // conversation on restart or scale-out.
212                warn!(
213                    "running as a deployed engine with in-memory sessions; conversations will \
214                     not survive restarts. Configure a managed backend, e.g. \
215                     VertexAiSessionService with VertexAiSessionConfig::from_env() (feature \
216                     `vertex-session`), via AgentEngineOptions::with_session_service"
217                );
218            }
219            Arc::new(adk_session::InMemorySessionService::new())
220        }
221    };
222
223    let mut runner_builder = adk_runner::Runner::builder()
224        .app_name(&app_name)
225        .agent(agent)
226        .session_service(session_service);
227    if let Some(artifact_service) = &opts.artifact_service {
228        runner_builder = runner_builder.artifact_service(artifact_service.clone());
229    }
230    let runner = Arc::new(runner_builder.build()?);
231
232    let mut state = AgentEngineState::new(runner);
233    if let Some(memory_service) = opts.memory_service {
234        state = state.with_memory_service(memory_service);
235    }
236    if let Some(artifact_service) = opts.artifact_service {
237        state = state.with_artifact_service(artifact_service);
238    }
239
240    Ok(agent_engine_router(state).route("/health", get(health)))
241}
242
243/// Liveness probe target for the platform's container health checks.
244async fn health() -> &'static str {
245    "ok"
246}
247
248/// Serves an agent as a complete Agent Engine container.
249///
250/// Binds `0.0.0.0:$PORT` (or [`AgentEngineOptions::with_port`], falling back
251/// to `8080`), installs the workspace crypto provider, and serves the
252/// dispatch endpoints until the process is stopped. This function is the
253/// whole `main` of a BYOC engine:
254///
255/// ```rust,no_run
256/// use adk_server::agent_engine::{AgentEngineOptions, serve_agent_engine};
257/// use std::sync::Arc;
258///
259/// # async fn run(agent: Arc<dyn adk_core::Agent>) -> adk_core::Result<()> {
260/// serve_agent_engine(agent, AgentEngineOptions::new()).await
261/// # }
262/// ```
263///
264/// # Errors
265///
266/// Returns an error when `$PORT` is invalid, the runner cannot be built, the
267/// listener cannot bind, or serving fails.
268pub async fn serve_agent_engine(agent: Arc<dyn Agent>, opts: AgentEngineOptions) -> Result<()> {
269    adk_core::ensure_crypto_provider();
270    let port = resolve_port(opts.port_override)?;
271    let app = build_agent_engine_app(agent, opts)?;
272
273    let addr = format!("0.0.0.0:{port}");
274    let listener = tokio::net::TcpListener::bind(&addr).await.map_err(|err| {
275        AdkError::new(
276            ErrorComponent::Server,
277            ErrorCategory::Unavailable,
278            "agent_engine.bind_failed",
279            format!("failed to bind {addr}: {err}"),
280        )
281    })?;
282    info!(server.address = %addr, "agent engine serving");
283    axum::serve(listener, app).await.map_err(|err| {
284        AdkError::new(
285            ErrorComponent::Server,
286            ErrorCategory::Internal,
287            "agent_engine.serve_failed",
288            format!("server terminated abnormally: {err}"),
289        )
290    })
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    // Env-var tests are safe under nextest (one process per test); they would
298    // race under plain `cargo test` threads.
299
300    #[test]
301    fn port_override_beats_env() {
302        unsafe { std::env::set_var(ENV_PORT, "9999") };
303        assert_eq!(resolve_port(Some(1234)).unwrap(), 1234);
304    }
305
306    #[test]
307    fn port_env_is_used_when_no_override() {
308        unsafe { std::env::set_var(ENV_PORT, "9042") };
309        assert_eq!(resolve_port(None).unwrap(), 9042);
310    }
311
312    #[test]
313    fn port_defaults_to_8080() {
314        unsafe { std::env::remove_var(ENV_PORT) };
315        assert_eq!(resolve_port(None).unwrap(), DEFAULT_PORT);
316    }
317
318    #[test]
319    fn blank_port_env_falls_back() {
320        unsafe { std::env::set_var(ENV_PORT, "  ") };
321        assert_eq!(resolve_port(None).unwrap(), DEFAULT_PORT);
322    }
323
324    #[test]
325    fn invalid_port_env_is_an_error() {
326        unsafe { std::env::set_var(ENV_PORT, "not-a-port") };
327        let err = resolve_port(None).unwrap_err();
328        assert_eq!(err.http_status_code(), 400);
329    }
330
331    #[test]
332    fn platform_env_detects_managed_deployments() {
333        unsafe { std::env::set_var(ENV_GOOGLE_CLOUD_AGENT_ENGINE_ID, "12345") };
334        assert!(PlatformEnv::read().is_managed());
335        unsafe { std::env::remove_var(ENV_GOOGLE_CLOUD_AGENT_ENGINE_ID) };
336        assert!(!PlatformEnv::read().is_managed());
337    }
338}