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
98fn 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
121fn 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
136fn 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
148async 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
183fn is_agent_card_path(path: &str) -> bool {
190 matches!(path, "/.well-known/agent-card.json" | "/.well-known/agent.json")
191}
192
193async 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
253fn 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
330async 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
373pub fn create_app(config: ServerConfig) -> Router {
375 create_app_with_a2a(config, None)
376}
377
378#[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 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 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#[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#[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
460const A2A_LEGACY_CARD_PATH: &str = "/.well-known/agent.json";
462
463#[cfg(not(feature = "a2a-v1"))]
466const A2A_CARD_PATHS: &[&str] = &["/.well-known/agent-card.json", A2A_LEGACY_CARD_PATH];
467
468fn 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
478pub 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
490pub 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 ag_ui_extension: Option<Arc<dyn controllers::AgUiExtension>>,
555}
556
557impl ServerBuilder {
558 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 #[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 pub fn add_api_routes(mut self, routes: Router) -> Self {
618 self.api_routes.push(routes);
619 self
620 }
621
622 pub fn add_root_routes(mut self, routes: Router) -> Self {
631 self.root_routes.push(routes);
632 self
633 }
634
635 #[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 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 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 pub fn with_a2a_task_retention(mut self, retention: A2aTaskRetention) -> Self {
717 self.a2a_task_retention = Some(retention);
718 self
719 }
720
721 #[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 #[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 #[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 #[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 #[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 pub fn enable_shutdown_endpoint(mut self) -> Self {
856 self.shutdown_endpoint = true;
857 self
858 }
859
860 pub fn enable_governance_endpoints(mut self) -> Self {
883 self.governance_endpoints = true;
884 self
885 }
886
887 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 #[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 #[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 pub fn build(self) -> Router {
953 self.build_inner().0
954 }
955
956 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 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 #[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 .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 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 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 for custom_routes in self.api_routes {
1155 api_router = api_router.merge(custom_routes.layer(auth_layer.clone()));
1156 }
1157
1158 #[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 #[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 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 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 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 #[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 #[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 #[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
1386pub 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#[derive(Clone)]
1435pub struct ShutdownHandle {
1436 token: CancellationToken,
1437}
1438
1439impl ShutdownHandle {
1440 fn new() -> Self {
1442 Self { token: CancellationToken::new() }
1443 }
1444
1445 pub fn shutdown(&self) {
1450 tracing::info!("graceful shutdown triggered programmatically");
1451 self.token.cancel();
1452 }
1453
1454 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 }
1487 }
1488 }
1489
1490 pub fn is_shutdown(&self) -> bool {
1492 self.token.is_cancelled()
1493 }
1494}
1495
1496async 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}