Skip to main content

adk_server/rest/
mod.rs

1pub mod controllers;
2mod routes;
3
4pub use controllers::{
5    A2aController, AppsController, ArtifactsController, DebugController, FreezeDelegate,
6    FreezeReport, GovernanceController, GovernanceStatus, RunningRuns, RuntimeController,
7    SessionController, a2a::A2aTaskRetention,
8};
9
10use crate::{
11    SecurityConfig, ServerConfig,
12    auth_bridge::{RequestContext, RequestContextError, RequestContextExtractor},
13};
14use axum::{
15    Json, Router,
16    body::Body,
17    extract::{DefaultBodyLimit, State},
18    http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode, header},
19    middleware::{self, Next},
20    response::{IntoResponse, Response},
21    routing::{get, post},
22};
23use serde::Serialize;
24use std::sync::Arc;
25use tokio_util::sync::CancellationToken;
26use tower::ServiceBuilder;
27use tower_http::{
28    cors::{AllowOrigin, CorsLayer},
29    set_header::SetResponseHeaderLayer,
30    trace::TraceLayer,
31};
32
33const REQUEST_ID_HEADER: &str = "x-request-id";
34
35#[derive(Clone)]
36struct HealthController {
37    session_service: Arc<dyn adk_session::SessionService>,
38    artifact_service: Option<Arc<dyn adk_artifact::ArtifactService>>,
39    memory_service: Option<Arc<dyn adk_core::Memory>>,
40}
41
42impl HealthController {
43    fn new(config: &ServerConfig) -> Self {
44        Self {
45            session_service: config.session_service.clone(),
46            artifact_service: config.artifact_service.clone(),
47            memory_service: config.memory_service.clone(),
48        }
49    }
50}
51
52#[derive(Clone, Debug)]
53struct RequestId(String);
54
55impl RequestId {
56    fn as_str(&self) -> &str {
57        &self.0
58    }
59}
60
61#[derive(Serialize)]
62#[serde(rename_all = "camelCase")]
63struct HealthResponse {
64    status: &'static str,
65    components: HealthComponents,
66}
67
68#[derive(Serialize)]
69#[serde(rename_all = "camelCase")]
70struct HealthComponents {
71    session: ComponentHealth,
72    memory: ComponentHealth,
73    artifact: ComponentHealth,
74}
75
76#[derive(Serialize)]
77#[serde(rename_all = "camelCase")]
78struct ComponentHealth {
79    status: &'static str,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    error: Option<String>,
82}
83
84impl ComponentHealth {
85    fn healthy() -> Self {
86        Self { status: "healthy", error: None }
87    }
88
89    fn unhealthy(error: impl Into<String>) -> Self {
90        Self { status: "unhealthy", error: Some(error.into()) }
91    }
92
93    fn not_configured() -> Self {
94        Self { status: "not_configured", error: None }
95    }
96}
97
98/// Builds the CORS layer: only [`SecurityConfig::allowed_origins`] get an
99/// `Access-Control-Allow-Origin`.
100fn build_cors_layer(security: &Arc<SecurityConfig>) -> CorsLayer {
101    let cors = CorsLayer::new()
102        .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::OPTIONS])
103        .allow_headers([
104            header::CONTENT_TYPE,
105            header::AUTHORIZATION,
106            HeaderName::from_static(REQUEST_ID_HEADER),
107            HeaderName::from_static("x-adk-ui-protocol"),
108            HeaderName::from_static("x-adk-ui-transport"),
109        ]);
110
111    if security.allowed_origins.iter().any(|origin| origin.trim() == "*") {
112        cors.allow_origin(AllowOrigin::any())
113    } else {
114        let security = Arc::clone(security);
115        cors.allow_origin(AllowOrigin::predicate(move |origin, _| {
116            origin.to_str().is_ok_and(|origin| security.allows_origin(origin))
117        }))
118    }
119}
120
121/// The authority a request names: the URI authority (HTTP/2) or the `Host` header.
122fn request_authority(request: &Request<Body>) -> Option<String> {
123    request.uri().authority().map(|authority| authority.as_str().to_string()).or_else(|| {
124        request
125            .headers()
126            .get(header::HOST)
127            .map(|host| String::from_utf8_lossy(host.as_bytes()).into_owned())
128    })
129}
130
131fn forbidden(error: &str, hint: &str) -> Response {
132    (StatusCode::FORBIDDEN, Json(serde_json::json!({ "error": error, "hint": hint })))
133        .into_response()
134}
135
136/// Refuses a request for a host the server does not answer.
137///
138/// A page on a DNS-rebinding domain reaches a loopback server as a same-origin request,
139/// so CORS never applies; the `Host` header still names the attacker's domain.
140/// Whether `path` names a route that runs an agent, which takes
141/// [`SecurityConfig::run_timeout`] instead of the request timeout.
142fn runs_an_agent(path: &str) -> bool {
143    matches!(path, "/api/run" | "/api/run_sse" | "/a2a" | "/a2a/stream" | "/a2a/v1")
144        || path.starts_with("/api/run/")
145        || path.starts_with("/a2a/v1/rest/message:")
146}
147
148/// Answers `408` when the response has not started within the route's timeout: the run
149/// timeout for a route that runs an agent, the request timeout for any other.
150async fn request_timeout(
151    State(security): State<Arc<SecurityConfig>>,
152    request: Request<Body>,
153    next: Next,
154) -> Response {
155    let limit = if runs_an_agent(request.uri().path()) {
156        security.run_timeout
157    } else {
158        security.request_timeout
159    };
160    match tokio::time::timeout(limit, next.run(request)).await {
161        Ok(response) => response,
162        Err(_) => StatusCode::REQUEST_TIMEOUT.into_response(),
163    }
164}
165
166async fn host_guard(
167    State(security): State<Arc<SecurityConfig>>,
168    request: Request<Body>,
169    next: Next,
170) -> Response {
171    if let Some(authority) = request_authority(&request)
172        && !security.allows_host(&authority)
173    {
174        tracing::warn!(http.host = %authority, "refused a request for a host not in allowed_hosts");
175        return forbidden(
176            "host not allowed",
177            "add the host to SecurityConfig::allowed_hosts to serve it",
178        );
179    }
180    next.run(request).await
181}
182
183/// Refuses a request whose `Origin` names another origin not in
184/// [`SecurityConfig::allowed_origins`].
185///
186/// CORS stops a browser from reading the response, but a simple cross-origin request still
187/// executes; this stops it before it reaches a handler.
188/// Whether `path` serves an A2A agent card, which any page may read.
189fn is_agent_card_path(path: &str) -> bool {
190    matches!(path, "/.well-known/agent-card.json" | "/.well-known/agent.json")
191}
192
193/// Serves the agent card to any origin, as a2a-go does: answers its CORS preflight
194/// (`GET`, `OPTIONS` with `Content-Type`, for a day) and lets the requesting page read the
195/// card (its `Origin` echoed with credentials, or `*`). The card is public metadata, and
196/// the host guard still refuses a rebinding `Host`.
197async fn agent_card_cors(request: Request<Body>, next: Next) -> Response {
198    if !is_agent_card_path(request.uri().path()) {
199        return next.run(request).await;
200    }
201    let origin = request.headers().get(header::ORIGIN).cloned();
202    let mut response = if request.method() == Method::OPTIONS {
203        let mut preflight = StatusCode::OK.into_response();
204        let headers = preflight.headers_mut();
205        headers
206            .insert(header::ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_static("GET, OPTIONS"));
207        headers
208            .insert(header::ACCESS_CONTROL_ALLOW_HEADERS, HeaderValue::from_static("Content-Type"));
209        headers.insert(header::ACCESS_CONTROL_MAX_AGE, HeaderValue::from_static("86400"));
210        preflight
211    } else {
212        next.run(request).await
213    };
214    let headers = response.headers_mut();
215    match origin {
216        Some(origin) => {
217            headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
218            headers
219                .insert(header::ACCESS_CONTROL_ALLOW_CREDENTIALS, HeaderValue::from_static("true"));
220            headers.append(header::VARY, HeaderValue::from_static("Origin"));
221        }
222        None => {
223            headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
224        }
225    }
226    response
227}
228
229async fn origin_guard(
230    State(security): State<Arc<SecurityConfig>>,
231    request: Request<Body>,
232    next: Next,
233) -> Response {
234    let reads_card = is_agent_card_path(request.uri().path())
235        && matches!(*request.method(), Method::GET | Method::HEAD | Method::OPTIONS);
236    if !reads_card && let Some(origin) = request.headers().get(header::ORIGIN) {
237        let origin = String::from_utf8_lossy(origin.as_bytes());
238        let same_origin = origin.split_once("://").is_some_and(|(_, authority)| {
239            request_authority(&request)
240                .is_some_and(|requested| requested.eq_ignore_ascii_case(authority))
241        });
242        if !same_origin && !security.allows_origin(&origin) {
243            tracing::warn!(http.origin = %origin, "refused a cross-origin request");
244            return forbidden(
245                "cross-origin request refused",
246                "add the origin to SecurityConfig::allowed_origins to allow it",
247            );
248        }
249    }
250    next.run(request).await
251}
252
253/// `security` with the hosts of the configured A2A base URL and backend URL added to
254/// its allowed hosts: the server advertises them, so peers and the web UI address it there.
255fn effective_security(security: &SecurityConfig, urls: [Option<&str>; 2]) -> Arc<SecurityConfig> {
256    let mut security = security.clone();
257    security.allowed_hosts.extend(
258        urls.into_iter()
259            .flatten()
260            .filter_map(|url| adk_core::Url::parse(url).ok())
261            .filter_map(|url| url.host_str().map(str::to_string)),
262    );
263    Arc::new(security)
264}
265
266fn validate_request_id(headers: &HeaderMap) -> Option<String> {
267    let value = headers.get(REQUEST_ID_HEADER)?;
268    let raw = value.to_str().ok()?;
269    if raw.len() > 128 {
270        return None;
271    }
272    uuid::Uuid::parse_str(raw).ok()?;
273    Some(raw.to_string())
274}
275
276async fn request_id_middleware(mut request: Request<Body>, next: Next) -> Response {
277    let request_id =
278        validate_request_id(request.headers()).unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
279
280    request.extensions_mut().insert(RequestId(request_id.clone()));
281
282    let mut response = next.run(request).await;
283    if let Ok(value) = HeaderValue::from_str(&request_id) {
284        response.headers_mut().insert(HeaderName::from_static(REQUEST_ID_HEADER), value);
285    }
286    response
287}
288
289async fn auth_middleware(
290    request: Request<Body>,
291    next: Next,
292    extractor: Option<Arc<dyn RequestContextExtractor>>,
293) -> Response {
294    let (mut parts, body) = request.into_parts();
295
296    let request_context = match extractor {
297        Some(extractor) => match extractor.extract(&parts).await {
298            Ok(context) => Some(context),
299            Err(RequestContextError::MissingAuth) => {
300                return (
301                    StatusCode::UNAUTHORIZED,
302                    Json(serde_json::json!({ "error": "missing authorization" })),
303                )
304                    .into_response();
305            }
306            Err(RequestContextError::InvalidToken(message)) => {
307                return (
308                    StatusCode::UNAUTHORIZED,
309                    Json(serde_json::json!({ "error": format!("invalid token: {message}") })),
310                )
311                    .into_response();
312            }
313            Err(RequestContextError::ExtractionFailed(message)) => {
314                return (
315                    StatusCode::INTERNAL_SERVER_ERROR,
316                    Json(serde_json::json!({
317                        "error": format!("auth extraction failed: {message}")
318                    })),
319                )
320                    .into_response();
321            }
322        },
323        None => None,
324    };
325
326    parts.extensions.insert::<Option<RequestContext>>(request_context);
327    next.run(Request::from_parts(parts, body)).await
328}
329
330/// `GET /api/version`: the server's version, as adk-python and adk-go serve it.
331async fn version() -> impl IntoResponse {
332    axum::Json(serde_json::json!({
333        "version": env!("CARGO_PKG_VERSION"),
334        "language": "rust",
335    }))
336}
337
338async fn health_check(State(controller): State<HealthController>) -> impl IntoResponse {
339    let session = match controller.session_service.health_check().await {
340        Ok(()) => ComponentHealth::healthy(),
341        Err(error) => ComponentHealth::unhealthy(error.to_string()),
342    };
343
344    let memory = match controller.memory_service.as_ref() {
345        Some(service) => match service.health_check().await {
346            Ok(()) => ComponentHealth::healthy(),
347            Err(error) => ComponentHealth::unhealthy(error.to_string()),
348        },
349        None => ComponentHealth::not_configured(),
350    };
351
352    let artifact = match controller.artifact_service.as_ref() {
353        Some(service) => match service.health_check().await {
354            Ok(()) => ComponentHealth::healthy(),
355            Err(error) => ComponentHealth::unhealthy(error.to_string()),
356        },
357        None => ComponentHealth::not_configured(),
358    };
359
360    let healthy = session.status == "healthy"
361        && memory.status != "unhealthy"
362        && artifact.status != "unhealthy";
363
364    (
365        if healthy { StatusCode::OK } else { StatusCode::SERVICE_UNAVAILABLE },
366        Json(HealthResponse {
367            status: if healthy { "healthy" } else { "unhealthy" },
368            components: HealthComponents { session, memory, artifact },
369        }),
370    )
371}
372
373/// Create the server application with optional A2A support
374pub fn create_app(config: ServerConfig) -> Router {
375    create_app_with_a2a(config, None)
376}
377
378/// Start hot reload watchers for configured YAML agent directories.
379///
380/// For each directory in `config.yaml_agent_dirs`, creates an
381/// [`AgentConfigLoader`](crate::yaml_agent::AgentConfigLoader) and
382/// [`HotReloadWatcher`](crate::yaml_agent::HotReloadWatcher), performs
383/// the initial load, and spawns a background watcher task.
384///
385/// Returns the list of active watchers so route handlers can look up
386/// YAML-defined agents.
387#[cfg(feature = "yaml-agent")]
388async fn start_yaml_agent_watchers(
389    dirs: &[std::path::PathBuf],
390) -> Vec<Arc<crate::yaml_agent::HotReloadWatcher>> {
391    use crate::yaml_agent::{AgentConfigLoader, HotReloadWatcher};
392
393    let mut watchers = Vec::new();
394
395    for dir in dirs {
396        // Create a minimal tool registry (no pre-registered tools) and a
397        // placeholder model factory. Real deployments should configure these
398        // via ServerConfig extensions; for now we use empty defaults so the
399        // watcher can start and load YAML definitions.
400        let registry: Arc<dyn adk_core::ToolRegistry> = Arc::new(EmptyToolRegistry);
401        let factory: Arc<dyn crate::yaml_agent::ModelFactory> = Arc::new(NoOpModelFactory);
402        let loader = Arc::new(AgentConfigLoader::new(registry, factory));
403        let watcher = Arc::new(HotReloadWatcher::new(loader));
404
405        match watcher.watch(dir).await {
406            Ok(handle) => {
407                tracing::info!("started YAML agent hot reload watcher for {}", dir.display());
408                // Detach the watcher task — it runs until the server shuts down.
409                drop(handle);
410                watchers.push(watcher);
411            }
412            Err(e) => {
413                tracing::warn!("failed to start YAML agent watcher for {}: {e}", dir.display());
414            }
415        }
416    }
417
418    watchers
419}
420
421/// Empty tool registry used as default when no tools are pre-registered.
422#[cfg(feature = "yaml-agent")]
423struct EmptyToolRegistry;
424
425#[cfg(feature = "yaml-agent")]
426impl adk_core::ToolRegistry for EmptyToolRegistry {
427    fn resolve(&self, _tool_name: &str) -> Option<Arc<dyn adk_core::Tool>> {
428        None
429    }
430
431    fn available_tools(&self) -> Vec<String> {
432        vec![]
433    }
434}
435
436/// Placeholder model factory that returns an error for any provider.
437///
438/// Real deployments should provide a proper `ModelFactory` via
439/// `ServerConfig` extensions. This exists so the watcher can start
440/// even when no model factory is explicitly configured.
441#[cfg(feature = "yaml-agent")]
442struct NoOpModelFactory;
443
444#[cfg(feature = "yaml-agent")]
445#[async_trait::async_trait]
446impl crate::yaml_agent::ModelFactory for NoOpModelFactory {
447    async fn create_model(
448        &self,
449        provider: &str,
450        model_id: &str,
451    ) -> adk_core::Result<Arc<dyn adk_core::Llm>> {
452        Err(adk_core::AdkError::config(format!(
453            "no model factory configured for YAML agent loading \
454             (requested provider='{provider}', model_id='{model_id}'). \
455             Configure a ModelFactory on the server to enable YAML agent model creation."
456        )))
457    }
458}
459
460/// The A2A 0.3 card path that predates `/.well-known/agent-card.json`.
461const A2A_LEGACY_CARD_PATH: &str = "/.well-known/agent.json";
462
463/// Where the A2A 0.3 card is served when it is the only A2A version: the well-known path
464/// since A2A 0.3.0, and the earlier path that existing peers use.
465#[cfg(not(feature = "a2a-v1"))]
466const A2A_CARD_PATHS: &[&str] = &["/.well-known/agent-card.json", A2A_LEGACY_CARD_PATH];
467
468/// Public routes serving the A2A 0.3 card at each of `paths`.
469fn a2a_card_routes(controller: A2aController, paths: &[&str]) -> Router {
470    paths
471        .iter()
472        .fold(Router::new(), |router, path| {
473            router.route(path, get(controllers::a2a::get_agent_card))
474        })
475        .with_state(controller)
476}
477
478/// Create the server application with A2A support at the specified base URL.
479///
480/// Builds the same router as [`ServerBuilder`] with only [`ServerBuilder::with_a2a`] set.
481pub fn create_app_with_a2a(config: ServerConfig, a2a_base_url: Option<&str>) -> Router {
482    let builder = ServerBuilder::new(config);
483    match a2a_base_url {
484        Some(base_url) => builder.with_a2a(base_url),
485        None => builder,
486    }
487    .build()
488}
489
490// ---------------------------------------------------------------------------
491// ServerBuilder — extensible server construction with custom routes
492// ---------------------------------------------------------------------------
493
494/// Builder for constructing an ADK server with custom routes.
495///
496/// `ServerBuilder` allows registering additional Axum routers alongside the
497/// built-in REST and A2A routes. Custom routes benefit from the same
498/// middleware stack (host and origin checks, auth, CORS, tracing, timeout,
499/// security headers) as the built-in routes.
500///
501/// The host and origin checks follow [`SecurityConfig`]: by
502/// default only loopback names and IP addresses are answered, and no other origin may
503/// call the server from a browser.
504///
505/// # Example
506///
507/// ```rust,ignore
508/// use adk_server::{ServerBuilder, ServerConfig};
509/// use axum::{Router, routing::get};
510///
511/// let config = ServerConfig::new(agent, session_service);
512///
513/// let app = ServerBuilder::new(config)
514///     .add_api_routes(
515///         Router::new()
516///             .route("/projects", get(list_projects))
517///             .route("/projects/{id}", get(get_project))
518///     )
519///     .add_api_routes(
520///         Router::new()
521///             .route("/automations", get(list_automations))
522///     )
523///     .with_a2a("http://localhost:8080")
524///     .build();
525///
526/// let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
527/// axum::serve(listener, app).await?;
528/// ```
529pub struct ServerBuilder {
530    config: ServerConfig,
531    a2a_base_url: Option<String>,
532    api_routes: Vec<Router>,
533    root_routes: Vec<Router>,
534    shutdown_endpoint: bool,
535    governance_endpoints: bool,
536    freeze_delegate: Option<Arc<dyn FreezeDelegate>>,
537    skill_index: Option<Arc<adk_skill::SkillIndex>>,
538    a2a_task_retention: Option<A2aTaskRetention>,
539    #[cfg(feature = "agent-engine")]
540    agent_engine: bool,
541    #[cfg(feature = "background")]
542    background_state: Option<crate::background::BackgroundState>,
543    #[cfg(feature = "background")]
544    cron_state: Option<crate::background::CronState>,
545    #[cfg(feature = "webhook-ingress")]
546    webhook_ingress: Option<crate::webhooks::WebhookIngress>,
547    #[cfg(feature = "google-triggers")]
548    google_push: Option<crate::google_triggers::GooglePushIngress>,
549    #[cfg(feature = "approvals")]
550    approval_service: Option<Arc<dyn adk_core::ApprovalService>>,
551    #[cfg(feature = "awp")]
552    awp_edge: bool,
553    /// What the host adds to protocol-native AG-UI runs (spec 3.3 §6.1 `genui`).
554    ag_ui_extension: Option<Arc<dyn controllers::AgUiExtension>>,
555}
556
557impl ServerBuilder {
558    /// Create a new server builder with the given configuration.
559    pub fn new(config: ServerConfig) -> Self {
560        Self {
561            config,
562            a2a_base_url: None,
563            api_routes: Vec::new(),
564            root_routes: Vec::new(),
565            shutdown_endpoint: false,
566            governance_endpoints: false,
567            freeze_delegate: None,
568            skill_index: None,
569            a2a_task_retention: None,
570            #[cfg(feature = "agent-engine")]
571            agent_engine: false,
572            #[cfg(feature = "background")]
573            background_state: None,
574            #[cfg(feature = "background")]
575            cron_state: None,
576            #[cfg(feature = "webhook-ingress")]
577            webhook_ingress: None,
578            #[cfg(feature = "google-triggers")]
579            google_push: None,
580            #[cfg(feature = "approvals")]
581            approval_service: None,
582            #[cfg(feature = "awp")]
583            awp_edge: false,
584            ag_ui_extension: None,
585        }
586    }
587
588    /// Adds `extension` to protocol-native AG-UI runs, and its features to `ag_ui` in
589    /// `GET /api/ui/capabilities` (spec 3.3 §6.1 `genui`; see
590    /// [`RuntimeController::with_ag_ui_extension`]).
591    ///
592    /// # Example
593    ///
594    /// ```rust,ignore
595    /// let app = ServerBuilder::new(config).with_ag_ui_extension(Arc::new(extension)).build();
596    /// ```
597    #[must_use]
598    pub fn with_ag_ui_extension(mut self, extension: Arc<dyn controllers::AgUiExtension>) -> Self {
599        self.ag_ui_extension = Some(extension);
600        self
601    }
602
603    /// Add custom routes nested under `/api`.
604    ///
605    /// These routes are merged into the API router and benefit from the auth
606    /// middleware layer. Multiple calls accumulate routes.
607    ///
608    /// # Example
609    ///
610    /// ```rust,ignore
611    /// builder.add_api_routes(
612    ///     Router::new()
613    ///         .route("/projects", get(list_projects))
614    ///         .route("/projects/{id}", get(get_project))
615    /// )
616    /// ```
617    pub fn add_api_routes(mut self, routes: Router) -> Self {
618        self.api_routes.push(routes);
619        self
620    }
621
622    /// Add custom routes at the root level (not nested under `/api`).
623    ///
624    /// These routes, such as the web home of `adk-surface`'s `web` feature, are merged at
625    /// the top level of the application, alongside the A2A routes. They receive the full
626    /// middleware stack (CORS, tracing, timeout, security headers, host and origin checks)
627    /// but NOT the auth middleware.
628    ///
629    /// Use this for routes that need their own auth handling or public endpoints.
630    pub fn add_root_routes(mut self, routes: Router) -> Self {
631        self.root_routes.push(routes);
632        self
633    }
634
635    /// Mounts the AWP 2.0 agent edge (spec 3.5 §7.9) through
636    /// [`add_root_routes`](Self::add_root_routes), so the host guard, CORS, timeouts and security
637    /// headers apply, and attaches the server's kill switch to it unless it carries its own.
638    ///
639    /// The edge serves `/.well-known/agent-card.json`; with an edge mounted,
640    /// [`with_a2a`](Self::with_a2a) keeps its JSON-RPC routes but not its card route.
641    ///
642    /// # Example
643    ///
644    /// ```rust,ignore
645    /// let app = ServerBuilder::new(config).awp(edge).build();
646    /// ```
647    #[cfg(feature = "awp")]
648    pub fn awp(mut self, edge: crate::awp::AwpEdge) -> Self {
649        edge.attach_governance(self.config.governance.clone());
650        self.awp_edge = true;
651        self.add_root_routes(edge.router())
652    }
653
654    /// Enable A2A protocol support at the specified base URL.
655    ///
656    /// The base URL is used to construct the agent card's endpoint URLs.
657    ///
658    /// With the `a2a-v1` feature, the root agent is served over A2A v1
659    /// (`a2a::v1::server::A2aV1Server`):
660    ///
661    /// - the JSON-RPC binding at `/a2a/v1`;
662    /// - the HTTP+JSON binding under `/a2a/v1/rest`;
663    /// - the v1 card at `/.well-known/agent-card.json`.
664    ///
665    /// The A2A 0.3 endpoint stays at `/a2a` (and `/a2a/stream`), with its card at
666    /// `/.well-known/agent.json`. The v1 card also lists it, as its last interface with
667    /// `protocolVersion` `0.3`; a v1 card has no top-level `url`, so a 0.3 peer reads the
668    /// 0.3 card.
669    ///
670    /// Without `a2a-v1`, only A2A 0.3 is served, and its card is at both paths.
671    pub fn with_a2a(mut self, base_url: impl Into<String>) -> Self {
672        self.a2a_base_url = Some(base_url.into());
673        self
674    }
675
676    /// Expose the skills in `skill_index` on the A2A agent card.
677    ///
678    /// When A2A is enabled via [`with_a2a`](Self::with_a2a), the served agent
679    /// card appends one `skills[]` entry per indexed
680    /// skill, mapped by [`agent_skills_from_index`](crate::a2a::agent_skills_from_index).
681    /// Has no effect without `with_a2a`.
682    ///
683    /// # Example
684    ///
685    /// ```rust,ignore
686    /// use adk_server::{ServerBuilder, ServerConfig};
687    /// use std::sync::Arc;
688    ///
689    /// let index = adk_skill::load_skill_index(".")?;
690    /// let app = ServerBuilder::new(config)
691    ///     .with_a2a("http://localhost:8080")
692    ///     .with_skill_index(Arc::new(index))
693    ///     .build();
694    /// ```
695    pub fn with_skill_index(mut self, skill_index: Arc<adk_skill::SkillIndex>) -> Self {
696        self.skill_index = Some(skill_index);
697        self
698    }
699
700    /// Bound how many finished A2A task records the server keeps, and for how long.
701    ///
702    /// Defaults to [`A2aTaskRetention::default`]: the newest 1,000 records, each for
703    /// at most one hour. Has no effect without [`with_a2a`](Self::with_a2a).
704    ///
705    /// # Example
706    ///
707    /// ```rust,ignore
708    /// use adk_server::{A2aTaskRetention, ServerBuilder};
709    /// use std::time::Duration;
710    ///
711    /// let app = ServerBuilder::new(config)
712    ///     .with_a2a("http://localhost:8080")
713    ///     .with_a2a_task_retention(A2aTaskRetention::default().with_ttl(Duration::from_secs(300)))
714    ///     .build();
715    /// ```
716    pub fn with_a2a_task_retention(mut self, retention: A2aTaskRetention) -> Self {
717        self.a2a_task_retention = Some(retention);
718        self
719    }
720
721    /// Mount the background run endpoints under `/api`, behind the auth middleware.
722    ///
723    /// Serves `POST /api/runs`, `GET /api/runs`, `GET /api/runs/{run_id}`, and
724    /// `DELETE /api/runs/{run_id}` from `state`, and starts its embedded worker when the
725    /// router is built inside a Tokio runtime. The state obeys
726    /// [`ServerConfig::governance`] unless it carries its own control. When a
727    /// `RequestContextExtractor` is configured, every request must authenticate, and an
728    /// authenticated run belongs to the caller's user id: the caller lists, reads, cancels,
729    /// and wakes only their own runs, another owner's run answers `404`, and the caller's
730    /// idempotency and concurrency keys are scoped to the caller. Without one the routes run
731    /// in [open mode](crate::background#open-mode), and [`build`](Self::build) logs a warning
732    /// that says so. Mounting
733    /// [`background_runs_router_with_state`](crate::background::background_runs_router_with_state)
734    /// yourself skips that layer.
735    ///
736    /// # Example
737    ///
738    /// ```rust,ignore
739    /// use adk_server::background::BackgroundState;
740    ///
741    /// let app = ServerBuilder::new(config)
742    ///     .with_background_runs(BackgroundState::new().with_executor(executor))
743    ///     .build();
744    /// ```
745    #[cfg(feature = "background")]
746    pub fn with_background_runs(mut self, state: crate::background::BackgroundState) -> Self {
747        self.background_state = Some(state);
748        self
749    }
750
751    /// Mount the cron job endpoints under `/api`, behind the auth middleware.
752    ///
753    /// Serves `POST /api/cron`, `GET /api/cron`, and `GET`/`PATCH`/`DELETE
754    /// /api/cron/{job_id}` from `state`. The scheduler is not started here — call
755    /// [`start_cron_scheduler`](crate::background::start_cron_scheduler) with a
756    /// clone of the same state on every replica; each fire time is enqueued once. Without a
757    /// `RequestContextExtractor` the routes run in
758    /// [open mode](crate::background#open-mode), and [`build`](Self::build) logs a warning
759    /// that says so.
760    ///
761    /// # Example
762    ///
763    /// ```rust,ignore
764    /// use adk_server::background::{BackgroundState, CronState, start_cron_scheduler};
765    ///
766    /// let cron_state = CronState::new(BackgroundState::new());
767    /// start_cron_scheduler(cron_state.clone());
768    /// let app = ServerBuilder::new(config).with_cron_jobs(cron_state).build();
769    /// ```
770    #[cfg(feature = "background")]
771    pub fn with_cron_jobs(mut self, state: crate::background::CronState) -> Self {
772        self.cron_state = Some(state);
773        self
774    }
775
776    /// Mount `POST /hooks/{name}`: each signed delivery enqueues a durable run.
777    ///
778    /// The route is served at the root, outside `/api` and without the auth middleware:
779    /// the Standard Webhooks signature is the authentication. When `ingress` has no kill
780    /// switch of its own, [`ServerConfig::governance`] is installed, so a freeze refuses
781    /// deliveries with `503`. Runs execute when a worker claims them from the ingress's
782    /// run store.
783    ///
784    /// # Example
785    ///
786    /// ```rust,ignore
787    /// use adk_server::webhooks::{WebhookHook, WebhookIngress};
788    ///
789    /// let ingress = WebhookIngress::new(run_store.clone())
790    ///     .with_hook(WebhookHook::new("billing", verifier, "billing", "invoice_agent"));
791    /// let app = ServerBuilder::new(config).with_webhook_ingress(ingress).build();
792    /// ```
793    #[cfg(feature = "webhook-ingress")]
794    pub fn with_webhook_ingress(mut self, ingress: crate::webhooks::WebhookIngress) -> Self {
795        self.webhook_ingress = Some(ingress);
796        self
797    }
798
799    /// Mount Google push triggers: `POST /triggers/pubsub/{name}` and
800    /// `POST /triggers/eventarc/{name}` at the root, outside `/api`, so Pub/Sub and Eventarc
801    /// reach them with their own OIDC tokens rather than the server's auth middleware
802    /// ([`google_triggers`](crate::google_triggers)).
803    ///
804    /// An ingress built without a kill switch takes
805    /// [`ServerConfig::governance`](crate::ServerConfig::governance), so a frozen server
806    /// answers `503` and the source redelivers. The routes are host-checked like every other:
807    /// add the service's hostname to `SecurityConfig::allowed_hosts`.
808    ///
809    /// ```rust,ignore
810    /// use adk_server::google_triggers::{GoogleOidcVerifier, GooglePushIngress, PushTrigger};
811    ///
812    /// let verifier = GoogleOidcVerifier::new(audience, ["push@my-project.iam.gserviceaccount.com"])?;
813    /// let ingress = GooglePushIngress::new(run_store.clone())
814    ///     .with_trigger(PushTrigger::pubsub("orders", verifier, "shop", "order_agent"));
815    /// let app = ServerBuilder::new(config).with_google_push(ingress).build();
816    /// ```
817    #[cfg(feature = "google-triggers")]
818    pub fn with_google_push(mut self, ingress: crate::google_triggers::GooglePushIngress) -> Self {
819        self.google_push = Some(ingress);
820        self
821    }
822
823    /// Mount the Agent Engine dispatch endpoints alongside the built-in routes.
824    ///
825    /// When enabled, `POST /api/reasoning_engine` and
826    /// `POST /api/stream_reasoning_engine` serve the Gemini Enterprise Agent
827    /// Platform runtime contract for the loader's root agent, using the
828    /// configured session and artifact services. The routes carry the shared
829    /// middleware stack but **not** the auth middleware or the host check — a
830    /// deployed engine is fronted by the platform, which authenticates callers
831    /// before they reach the container and chooses the `Host` it forwards. The memory class methods report `Unsupported`; use
832    /// [`serve_agent_engine`](crate::agent_engine::serve_agent_engine) with
833    /// [`AgentEngineOptions`](crate::agent_engine::AgentEngineOptions) to
834    /// configure a memory service.
835    ///
836    /// # Panics
837    ///
838    /// [`build`](Self::build) panics when the root agent's name is not a
839    /// valid app name, mirroring the builder's other misuse panics.
840    #[cfg(feature = "agent-engine")]
841    pub fn with_agent_engine(mut self, enabled: bool) -> Self {
842        self.agent_engine = enabled;
843        self
844    }
845
846    /// Enable the `POST /api/shutdown` endpoint for graceful shutdown.
847    ///
848    /// When enabled, the server exposes a shutdown endpoint that triggers
849    /// graceful shutdown: stops accepting new connections, completes in-flight
850    /// requests, and then exits. Use [`build_with_shutdown`](Self::build_with_shutdown)
851    /// to get the [`ShutdownHandle`] for wiring into `axum::serve().with_graceful_shutdown()`.
852    ///
853    /// The endpoint is protected by the auth middleware when a
854    /// `RequestContextExtractor` is configured.
855    pub fn enable_shutdown_endpoint(mut self) -> Self {
856        self.shutdown_endpoint = true;
857        self
858    }
859
860    /// Mount the governance admin endpoints under `/api/admin`, behind the auth middleware.
861    ///
862    /// | Route | Effect |
863    /// |-------|--------|
864    /// | `POST /api/admin/freeze` | Freezes [`ServerConfig::governance`], failing new runs and stopping running ones before their next model or tool call; background workers stop claiming and schedules stop firing; running durable runs are asked to cancel, or parked by the [`FreezeDelegate`] registered with [`with_freeze_delegate`](Self::with_freeze_delegate). A mirrored control writes the freeze to the shared store, so it reaches every replica. Body: `{"reason": "..."}`; answers the status with `parkedRuns` and `cancelledRuns` |
865    /// | `POST /api/admin/unfreeze` | Lifts the freeze; a delegate also resumes what the freeze parked |
866    /// | `GET /api/admin/governance` | Reports `{"frozen", "reason", "mirrored", "stale", "runningRuns"}`, where `runningRuns` is `park` under a delegate and `cancel` otherwise |
867    ///
868    /// The endpoints sit behind the auth middleware, and the freeze and the unfreeze admit
869    /// only an administrator: a caller whose
870    /// [`RequestContext::scopes`](adk_core::RequestContext::scopes) include
871    /// [`SecurityConfig::admin_scope`](crate::SecurityConfig::admin_scope) (`"admin"` by
872    /// default). An authenticated caller without it is refused with `403`
873    /// (`governance.forbidden`). Without a `RequestContextExtractor` no request has a caller,
874    /// so both are refused with `401` (`governance.unauthenticated`); the status stays
875    /// readable.
876    ///
877    /// # Example
878    ///
879    /// ```rust,ignore
880    /// let app = ServerBuilder::new(config).enable_governance_endpoints().build();
881    /// ```
882    pub fn enable_governance_endpoints(mut self) -> Self {
883        self.governance_endpoints = true;
884        self
885    }
886
887    /// Hands the governance endpoints' freezes and unfreezes to `delegate` (spec 3.2 §10
888    /// S4), so `POST /api/admin/freeze` parks the running runs the delegate supervises
889    /// instead of cancelling the background run stores' runs, and `POST /api/admin/unfreeze`
890    /// resumes them. A kernel registers itself here. Implies
891    /// [`enable_governance_endpoints`](Self::enable_governance_endpoints), so the delegate is
892    /// reached only by an administrator's request.
893    ///
894    /// # Example
895    ///
896    /// ```rust,ignore
897    /// let app = ServerBuilder::new(config).with_freeze_delegate(kernel).build();
898    /// ```
899    pub fn with_freeze_delegate(mut self, delegate: Arc<dyn FreezeDelegate>) -> Self {
900        self.freeze_delegate = Some(delegate);
901        self.governance_endpoints = true;
902        self
903    }
904
905    /// Mount the approval inbox endpoints for `service` under `/api/approvals`, behind
906    /// the auth middleware. See [`crate::approvals`] for the routes.
907    ///
908    /// Protocol-native AG-UI runs route the calls they hold to `service` as well: each ends
909    /// the run with an AG-UI interrupt naming its inbox entry, and a later AG-UI `resume`
910    /// decides the entry (spec 3.3 §10 S2,
911    /// [`RuntimeController::with_approval_service`]).
912    ///
913    /// The endpoints need an authenticated caller, so configure a
914    /// `RequestContextExtractor`; without one every route answers `401`. Run
915    /// [`spawn_approval_ticker`](crate::approvals::spawn_approval_ticker) as well so
916    /// requests expire and escalate.
917    ///
918    /// # Example
919    ///
920    /// ```rust,ignore
921    /// let app = ServerBuilder::new(config).with_approval_service(service).build();
922    /// ```
923    #[cfg(feature = "approvals")]
924    pub fn with_approval_service(mut self, service: Arc<dyn adk_core::ApprovalService>) -> Self {
925        self.approval_service = Some(service.clone());
926        self.add_api_routes(crate::approvals::approvals_router(
927            crate::approvals::ApprovalEndpoints::new(service),
928        ))
929    }
930
931    /// Serves `endpoints` as [`with_approval_service`](Self::with_approval_service) serves its
932    /// service: the endpoints keep what they were built with, such as a
933    /// [`DecideGuard`](crate::approvals::DecideGuard) that checks each decision (spec 3.3
934    /// §7.2).
935    ///
936    /// # Example
937    ///
938    /// ```rust,ignore
939    /// let endpoints = ApprovalEndpoints::new(service).with_decide_guard(guard);
940    /// let app = ServerBuilder::new(config).with_approval_endpoints(endpoints).build();
941    /// ```
942    #[cfg(feature = "approvals")]
943    pub fn with_approval_endpoints(
944        mut self,
945        endpoints: crate::approvals::ApprovalEndpoints,
946    ) -> Self {
947        self.approval_service = Some(endpoints.service().clone());
948        self.add_api_routes(crate::approvals::approvals_router(endpoints))
949    }
950
951    /// Build the final Axum router with all routes and middleware applied.
952    pub fn build(self) -> Router {
953        self.build_inner().0
954    }
955
956    /// Build the final Axum router and return a [`ShutdownHandle`].
957    ///
958    /// Use this when [`enable_shutdown_endpoint()`](Self::enable_shutdown_endpoint) is set.
959    /// Pass the handle's signal to `axum::serve().with_graceful_shutdown()`.
960    ///
961    /// # Example
962    ///
963    /// ```rust,ignore
964    /// let (app, shutdown_handle) = ServerBuilder::new(config)
965    ///     .enable_shutdown_endpoint()
966    ///     .build_with_shutdown();
967    ///
968    /// let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
969    /// axum::serve(listener, app)
970    ///     .with_graceful_shutdown(shutdown_handle.signal())
971    ///     .await?;
972    /// ```
973    pub fn build_with_shutdown(self) -> (Router, ShutdownHandle) {
974        let (router, handle) = self.build_inner();
975        (router, handle.expect("build_with_shutdown requires enable_shutdown_endpoint()"))
976    }
977
978    fn build_inner(self) -> (Router, Option<ShutdownHandle>) {
979        let config = &self.config;
980        let session_controller = SessionController::new(config.session_service.clone());
981        let history_controller = controllers::session_history::HistoryController::new(config);
982        let runtime_controller = RuntimeController::new(config.clone());
983        #[cfg(feature = "approvals")]
984        let runtime_controller = match &self.approval_service {
985            Some(service) => runtime_controller.with_approval_service(service.clone()),
986            None => runtime_controller,
987        };
988        let runtime_controller = match &self.ag_ui_extension {
989            Some(extension) => runtime_controller.with_ag_ui_extension(extension.clone()),
990            None => runtime_controller,
991        };
992        // An AG-UI resume decides inbox entries for an authenticated caller.
993        let resume_wired =
994            runtime_controller.answers_ag_ui_resume() && config.request_context_extractor.is_some();
995        let served_ui = controllers::ui::ServedUi {
996            resume: resume_wired,
997            ag_ui_features: runtime_controller.ag_ui_features(),
998        };
999        let apps_controller = AppsController::new(config.clone());
1000        let artifacts_controller = ArtifactsController::new(config.clone());
1001        let debug_controller = DebugController::new(config.clone());
1002        let health_controller = HealthController::new(config);
1003
1004        // Start YAML agent hot reload watchers if configured.
1005        #[cfg(feature = "yaml-agent")]
1006        {
1007            let dirs = config.yaml_agent_dirs.clone();
1008            if !dirs.is_empty() {
1009                tokio::spawn(async move {
1010                    let _watchers = start_yaml_agent_watchers(&dirs).await;
1011                    std::future::pending::<()>().await;
1012                });
1013            }
1014        }
1015
1016        let auth_layer = middleware::from_fn({
1017            let extractor = config.request_context_extractor.clone();
1018            move |request: Request<Body>, next: Next| {
1019                let extractor = extractor.clone();
1020                async move { auth_middleware(request, next, extractor).await }
1021            }
1022        });
1023
1024        let health_router = Router::new()
1025            .route("/health", get(health_check))
1026            .with_state(health_controller)
1027            .route("/version", get(version));
1028
1029        let ui_api_router = Router::new()
1030            .route("/apps", get(controllers::apps::list_apps))
1031            .route("/list-apps", get(controllers::apps::list_apps_compat))
1032            .route("/ui/agents/{name}", get(controllers::apps::get_agent_details))
1033            .with_state(apps_controller)
1034            .route(
1035                "/ui/capabilities",
1036                get(controllers::ui::served_ui_capabilities).with_state(served_ui),
1037            )
1038            .route("/ui/initialize", post(controllers::ui::ui_initialize))
1039            .route("/ui/message", post(controllers::ui::ui_message))
1040            .route("/ui/update-model-context", post(controllers::ui::ui_update_model_context))
1041            .route("/ui/notifications/poll", post(controllers::ui::ui_poll_notifications))
1042            .route(
1043                "/ui/notifications/resources-list-changed",
1044                post(controllers::ui::ui_notify_resources_list_changed),
1045            )
1046            .route(
1047                "/ui/notifications/tools-list-changed",
1048                post(controllers::ui::ui_notify_tools_list_changed),
1049            )
1050            .route("/ui/resources", get(controllers::ui::list_ui_resources))
1051            .route("/ui/resources/read", get(controllers::ui::read_ui_resource))
1052            .route("/ui/resources/register", post(controllers::ui::register_ui_resource))
1053            // These routes mutate and read shared bridge and resource state, so they
1054            // carry the same authentication as the session, artifact, and debug routers.
1055            .layer(auth_layer.clone());
1056
1057        let session_router = Router::new()
1058            .route("/sessions", post(controllers::session::create_session))
1059            .route(
1060                "/sessions/{app_name}/{user_id}/{session_id}",
1061                get(controllers::session::get_session).delete(controllers::session::delete_session),
1062            )
1063            .route(
1064                "/apps/{app_name}/users/{user_id}/sessions",
1065                get(controllers::session::list_sessions)
1066                    .post(controllers::session::create_session_from_path),
1067            )
1068            .route(
1069                "/apps/{app_name}/users/{user_id}/sessions/{session_id}",
1070                get(controllers::session::get_session_from_path)
1071                    .post(controllers::session::create_session_from_path)
1072                    .delete(controllers::session::delete_session_from_path),
1073            )
1074            .with_state(session_controller)
1075            .layer(auth_layer.clone());
1076
1077        // Fork, rewind, and edit carry the session routes' authentication.
1078        let history_router = Router::new()
1079            .route(
1080                "/apps/{app_name}/users/{user_id}/sessions/{session_id}/history",
1081                get(controllers::session_history::get_history),
1082            )
1083            .route(
1084                "/apps/{app_name}/users/{user_id}/sessions/{session_id}/history/edit",
1085                post(controllers::session_history::edit_history),
1086            )
1087            .route(
1088                "/apps/{app_name}/users/{user_id}/sessions/{session_id}/fork",
1089                post(controllers::session_history::fork_session),
1090            )
1091            .route(
1092                "/apps/{app_name}/users/{user_id}/sessions/{session_id}/rewind",
1093                post(controllers::session_history::rewind_session),
1094            )
1095            .with_state(history_controller)
1096            .layer(auth_layer.clone());
1097
1098        let runtime_router = Router::new()
1099            .route("/run", post(controllers::runtime::run_collect_for_request))
1100            .route(
1101                "/run/{app_name}/{user_id}/{session_id}",
1102                post(controllers::runtime::run_sse_for_request),
1103            )
1104            .route("/run_sse", post(controllers::runtime::run_sse_compat_for_request))
1105            .with_state(runtime_controller);
1106
1107        let artifacts_router = Router::new()
1108            .route(
1109                "/sessions/{app_name}/{user_id}/{session_id}/artifacts",
1110                get(controllers::artifacts::list_artifacts),
1111            )
1112            .route(
1113                "/sessions/{app_name}/{user_id}/{session_id}/artifacts/{artifact_name}",
1114                get(controllers::artifacts::get_artifact),
1115            )
1116            .with_state(artifacts_controller)
1117            .layer(auth_layer.clone());
1118
1119        let mut debug_router = Router::new()
1120            .route("/debug/trace/session/{session_id}", get(controllers::debug::get_session_traces))
1121            .route(
1122                "/debug/graph/{app_name}/{user_id}/{session_id}/{event_id}",
1123                get(controllers::debug::get_graph),
1124            )
1125            .route(
1126                "/apps/{app_name}/users/{user_id}/sessions/{session_id}/events/{event_id}/graph",
1127                get(controllers::debug::get_graph),
1128            )
1129            .route("/apps/{app_name}/eval_sets", get(controllers::debug::get_eval_sets))
1130            .route(
1131                "/apps/{app_name}/users/{user_id}/sessions/{session_id}/events/{event_id}",
1132                get(controllers::debug::get_event),
1133            );
1134
1135        if config.request_context_extractor.is_none() || config.security.expose_admin_debug {
1136            debug_router = debug_router
1137                .route("/debug/trace/{event_id}", get(controllers::debug::get_trace_by_event_id));
1138        }
1139
1140        let debug_router =
1141            debug_router.with_state(debug_controller.clone()).layer(auth_layer.clone());
1142
1143        // Assemble the API router with built-in + custom routes
1144        let mut api_router = Router::new()
1145            .merge(health_router)
1146            .merge(ui_api_router)
1147            .merge(session_router)
1148            .merge(history_router)
1149            .merge(runtime_router)
1150            .merge(artifacts_router)
1151            .merge(debug_router);
1152
1153        // Merge custom API routes — these get the same /api prefix and auth middleware
1154        for custom_routes in self.api_routes {
1155            api_router = api_router.merge(custom_routes.layer(auth_layer.clone()));
1156        }
1157
1158        // Background runs and cron schedules obey the server's kill switch unless they
1159        // carry their own, and a freeze asks their running runs to cancel.
1160        #[cfg(feature = "background")]
1161        let mut background_run_stores: Vec<Arc<dyn adk_core::DurableRunStore>> = Vec::new();
1162        #[cfg(feature = "background")]
1163        for state in self
1164            .background_state
1165            .iter()
1166            .chain(self.cron_state.iter().map(|cron| &cron.background_state))
1167        {
1168            state.governance_or(&config.governance);
1169            background_run_stores.push(Arc::clone(state.run_store()));
1170        }
1171
1172        if self.governance_endpoints {
1173            let controller = controllers::GovernanceController::new(config.governance.clone())
1174                .with_error_details(config.security.expose_error_details)
1175                .with_admin_scope(config.security.admin_scope.clone());
1176            #[cfg(feature = "background")]
1177            let controller = background_run_stores
1178                .iter()
1179                .fold(controller, |controller, store| controller.with_run_store(Arc::clone(store)));
1180            let controller = match self.freeze_delegate {
1181                Some(delegate) => controller.with_freeze_delegate(delegate),
1182                None => controller,
1183            };
1184            api_router = api_router.merge(
1185                Router::new()
1186                    .route("/admin/freeze", post(controllers::governance::freeze))
1187                    .route("/admin/unfreeze", post(controllers::governance::unfreeze))
1188                    .route("/admin/governance", get(controllers::governance::status))
1189                    .with_state(controller)
1190                    .layer(auth_layer.clone()),
1191            );
1192        }
1193
1194        // Background runs and cron jobs submit and schedule work, so they carry the
1195        // same authentication as every other mutation surface.
1196        // Without an extractor they run in open mode, announced here rather than per request.
1197        #[cfg(feature = "background")]
1198        if config.request_context_extractor.is_none() {
1199            let routes = match (&self.background_state, &self.cron_state) {
1200                (Some(_), Some(_)) => Some("/api/runs, /api/cron"),
1201                (Some(_), None) => Some("/api/runs"),
1202                (None, Some(_)) => Some("/api/cron"),
1203                (None, None) => None,
1204            };
1205            if let Some(routes) = routes {
1206                crate::background::warn_open_mode(routes);
1207            }
1208        }
1209        #[cfg(feature = "background")]
1210        if let Some(state) = self.background_state {
1211            api_router =
1212                api_router.merge(crate::background::runs_routes(state).layer(auth_layer.clone()));
1213        }
1214        #[cfg(feature = "background")]
1215        if let Some(state) = self.cron_state {
1216            api_router = api_router
1217                .merge(crate::background::cron::cron_routes(state).layer(auth_layer.clone()));
1218        }
1219
1220        // Add shutdown endpoint if enabled
1221        let shutdown_handle = if self.shutdown_endpoint {
1222            let handle = ShutdownHandle::new();
1223            let shutdown_router = Router::new()
1224                .route("/shutdown", post(handle_shutdown))
1225                .with_state(handle.token.clone())
1226                .layer(auth_layer.clone());
1227            api_router = api_router.merge(shutdown_router);
1228            Some(handle)
1229        } else {
1230            None
1231        };
1232
1233        let mut app = Router::new().nest("/api", api_router);
1234
1235        #[cfg(feature = "webhook-ingress")]
1236        if let Some(ingress) = self.webhook_ingress {
1237            let ingress = if ingress.has_governance() {
1238                ingress
1239            } else {
1240                ingress.with_governance(config.governance.clone())
1241            };
1242            app = app.merge(crate::webhooks::webhook_ingress_router(ingress));
1243        }
1244
1245        #[cfg(feature = "google-triggers")]
1246        if let Some(ingress) = self.google_push {
1247            let ingress = if ingress.has_governance() {
1248                ingress
1249            } else {
1250                ingress.with_governance(config.governance.clone())
1251            };
1252            app = app.merge(crate::google_triggers::google_push_router(ingress));
1253        }
1254
1255        // Merge custom root routes
1256        for custom_routes in self.root_routes {
1257            app = app.merge(custom_routes);
1258        }
1259
1260        if let Some(base_url) = &self.a2a_base_url {
1261            let a2a_controller = match &self.skill_index {
1262                Some(skill_index) => {
1263                    A2aController::with_skill_index(config.clone(), base_url, skill_index.clone())
1264                }
1265                None => A2aController::new(config.clone(), base_url),
1266            };
1267            let a2a_controller = match self.a2a_task_retention {
1268                Some(retention) => a2a_controller.with_task_retention(retention),
1269                None => a2a_controller,
1270            };
1271            // Same split as `create_app_with_a2a`: discovery is public, RPC is authenticated.
1272            // `route_layer`, as these routes are merged at the root: `layer` would also wrap
1273            // the app's fallback and answer every unknown path with `401`.
1274            let a2a_rpc = Router::new()
1275                .route("/a2a", post(controllers::a2a::handle_jsonrpc_for_caller))
1276                .route("/a2a/stream", post(controllers::a2a::handle_jsonrpc_stream_for_caller))
1277                .with_state(a2a_controller.clone())
1278                .route_layer(auth_layer.clone());
1279
1280            #[cfg(not(feature = "a2a-v1"))]
1281            let a2a_discovery = a2a_card_routes(a2a_controller, A2A_CARD_PATHS);
1282
1283            // A2A v1 is the protocol `/.well-known/agent-card.json` advertises. 0.3 keeps its
1284            // `/a2a` endpoint and `/.well-known/agent.json` card, and the v1 card lists the
1285            // 0.3 endpoint too, so peers on either version find theirs.
1286            #[cfg(feature = "a2a-v1")]
1287            let (a2a_discovery, a2a_rpc) = {
1288                let root_agent = config.agent_loader.root_agent();
1289                let runner_config =
1290                    controllers::a2a::runner_config_for(config, root_agent, None, None);
1291                let base = base_url.trim_end_matches('/');
1292                let mut v1 = crate::a2a::v1::server::A2aV1Server::builder(runner_config, base)
1293                    .legacy_jsonrpc_url(format!("{base}/a2a"));
1294                if let Some(skill_index) = &self.skill_index {
1295                    v1 = v1.skills(
1296                        crate::a2a::agent_skills_from_index(skill_index)
1297                            .into_iter()
1298                            .map(crate::a2a::v1::card::v1_skill),
1299                    );
1300                }
1301                let v1 = v1.build();
1302                (
1303                    a2a_card_routes(a2a_controller, &[A2A_LEGACY_CARD_PATH])
1304                        .merge(v1.card_router()),
1305                    a2a_rpc.merge(v1.rpc_router().route_layer(auth_layer.clone())),
1306                )
1307            };
1308
1309            // The AWP edge serves the site's signed card at the same path.
1310            #[cfg(feature = "awp")]
1311            let a2a_discovery = if self.awp_edge { Router::new() } else { a2a_discovery };
1312            app = app.merge(a2a_discovery).merge(a2a_rpc);
1313        }
1314
1315        let security = effective_security(
1316            &config.security,
1317            [self.a2a_base_url.as_deref(), config.backend_url.as_deref()],
1318        );
1319        app = app.layer(middleware::from_fn_with_state(Arc::clone(&security), host_guard));
1320
1321        // Agent Engine dispatch surface: root-level merge (its routes carry
1322        // their own /api/... paths) so the platform host reaches it without
1323        // the local auth middleware or the host check — the platform fronts the
1324        // container, authenticates callers, and chooses the Host it forwards.
1325        #[cfg(feature = "agent-engine")]
1326        if self.agent_engine {
1327            let root_agent = config.agent_loader.root_agent();
1328            let mut runner_builder = adk_runner::Runner::builder()
1329                .app_name(root_agent.name())
1330                .agent(root_agent.clone())
1331                .session_service(config.session_service.clone())
1332                .governance(config.governance.clone());
1333            if let Some(artifact_service) = &config.artifact_service {
1334                runner_builder = runner_builder.artifact_service(artifact_service.clone());
1335            }
1336            let runner = runner_builder
1337                .build()
1338                .expect("with_agent_engine requires the root agent's name to be a valid app name");
1339            let mut state = crate::agent_engine::AgentEngineState::new(Arc::new(runner));
1340            if let Some(artifact_service) = &config.artifact_service {
1341                state = state.with_artifact_service(artifact_service.clone());
1342            }
1343            app = app.merge(crate::agent_engine::agent_engine_router(state));
1344        }
1345
1346        let cors_layer = build_cors_layer(&security);
1347        let trace_layer = TraceLayer::new_for_http().make_span_with(|request: &Request<Body>| {
1348            let request_id =
1349                request.extensions().get::<RequestId>().map(RequestId::as_str).unwrap_or("");
1350            tracing::info_span!(
1351                "http.request",
1352                request.id = %request_id,
1353                http.method = %request.method(),
1354                http.path = %request.uri().path()
1355            )
1356        });
1357
1358        (
1359            app.layer(
1360                ServiceBuilder::new()
1361                    .layer(middleware::from_fn(request_id_middleware))
1362                    .layer(trace_layer)
1363                    .layer(middleware::from_fn_with_state(Arc::clone(&security), request_timeout))
1364                    .layer(DefaultBodyLimit::max(config.security.max_body_size))
1365                    .layer(middleware::from_fn(agent_card_cors))
1366                    .layer(cors_layer)
1367                    .layer(middleware::from_fn_with_state(Arc::clone(&security), origin_guard))
1368                    .layer(SetResponseHeaderLayer::if_not_present(
1369                        header::X_CONTENT_TYPE_OPTIONS,
1370                        HeaderValue::from_static("nosniff"),
1371                    ))
1372                    .layer(SetResponseHeaderLayer::if_not_present(
1373                        header::X_FRAME_OPTIONS,
1374                        HeaderValue::from_static("DENY"),
1375                    ))
1376                    .layer(SetResponseHeaderLayer::if_not_present(
1377                        header::X_XSS_PROTECTION,
1378                        HeaderValue::from_static("1; mode=block"),
1379                    )),
1380            ),
1381            shutdown_handle,
1382        )
1383    }
1384}
1385
1386/// Wait for a process shutdown signal.
1387pub async fn shutdown_signal() {
1388    let ctrl_c = async {
1389        let _ = tokio::signal::ctrl_c().await;
1390    };
1391
1392    #[cfg(unix)]
1393    let terminate = async {
1394        if let Ok(mut signal) =
1395            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
1396        {
1397            let _ = signal.recv().await;
1398        }
1399    };
1400
1401    #[cfg(not(unix))]
1402    let terminate = std::future::pending::<()>();
1403
1404    tokio::select! {
1405        _ = ctrl_c => {}
1406        _ = terminate => {}
1407    }
1408}
1409
1410// ---------------------------------------------------------------------------
1411// ShutdownHandle — programmatic graceful shutdown trigger
1412// ---------------------------------------------------------------------------
1413
1414/// Handle for triggering graceful server shutdown.
1415///
1416/// Returned by [`ServerBuilder::build_with_shutdown`]. Pass the future from
1417/// [`ShutdownHandle::signal()`] to `axum::serve(...).with_graceful_shutdown()`
1418/// to enable both OS signal-based and HTTP endpoint-based shutdown.
1419///
1420/// # Example
1421///
1422/// ```rust,ignore
1423/// use adk_server::{ServerBuilder, ServerConfig};
1424///
1425/// let (app, shutdown_handle) = ServerBuilder::new(config)
1426///     .enable_shutdown_endpoint()
1427///     .build_with_shutdown();
1428///
1429/// let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
1430/// axum::serve(listener, app)
1431///     .with_graceful_shutdown(shutdown_handle.signal())
1432///     .await?;
1433/// ```
1434#[derive(Clone)]
1435pub struct ShutdownHandle {
1436    token: CancellationToken,
1437}
1438
1439impl ShutdownHandle {
1440    /// Create a new shutdown handle.
1441    fn new() -> Self {
1442        Self { token: CancellationToken::new() }
1443    }
1444
1445    /// Trigger graceful shutdown programmatically.
1446    ///
1447    /// This has the same effect as calling `POST /api/shutdown` — the server
1448    /// stops accepting new connections and completes in-flight requests.
1449    pub fn shutdown(&self) {
1450        tracing::info!("graceful shutdown triggered programmatically");
1451        self.token.cancel();
1452    }
1453
1454    /// Returns a future that resolves when shutdown is triggered.
1455    ///
1456    /// Combines OS signals (Ctrl+C, SIGTERM) with the programmatic/HTTP trigger.
1457    /// Pass this to `axum::serve(...).with_graceful_shutdown()`.
1458    pub async fn signal(self) {
1459        let token = self.token.clone();
1460
1461        let ctrl_c = async {
1462            let _ = tokio::signal::ctrl_c().await;
1463        };
1464
1465        #[cfg(unix)]
1466        let terminate = async {
1467            if let Ok(mut signal) =
1468                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
1469            {
1470                let _ = signal.recv().await;
1471            }
1472        };
1473
1474        #[cfg(not(unix))]
1475        let terminate = std::future::pending::<()>();
1476
1477        tokio::select! {
1478            _ = ctrl_c => {
1479                tracing::info!("received Ctrl+C, initiating graceful shutdown");
1480            }
1481            _ = terminate => {
1482                tracing::info!("received SIGTERM, initiating graceful shutdown");
1483            }
1484            _ = token.cancelled() => {
1485                // Shutdown triggered via POST /api/shutdown or programmatic call
1486            }
1487        }
1488    }
1489
1490    /// Returns whether shutdown has been triggered.
1491    pub fn is_shutdown(&self) -> bool {
1492        self.token.is_cancelled()
1493    }
1494}
1495
1496/// Handler for `POST /api/shutdown`.
1497///
1498/// Triggers graceful shutdown: the server stops accepting new connections,
1499/// completes in-flight requests, and then exits.
1500async fn handle_shutdown(State(token): State<CancellationToken>) -> impl IntoResponse {
1501    tracing::info!("POST /api/shutdown received, initiating graceful shutdown");
1502    token.cancel();
1503    (StatusCode::OK, Json(serde_json::json!({ "status": "shutting_down" })))
1504}