Skip to main content

adk_server/rest/controllers/
runtime.rs

1use super::ag_ui_decisions::{
2    AgUiCaller, AgUiDecisions, HeldCall, INTERRUPTS_OPEN, INVALID_RESUME, RESUME_IN_PROGRESS,
3    ResumeOutcome, ResumesInProgress, commit_resume, decision_event, open_interrupt_ids,
4    plan_resume,
5};
6use super::ag_ui_extension::{AgUiAction, AgUiExtension};
7use super::error_details;
8use crate::ServerConfig;
9use crate::auth_bridge::{RequestContextError, RequestContextExtractor};
10use crate::rest::controllers::ui::{
11    McpUiInitializeParams, McpUiMessageParams, McpUiUpdateModelContextParams,
12    initialize_mcp_ui_bridge, mark_mcp_ui_initialized, message_mcp_ui_bridge,
13    update_mcp_ui_bridge_model_context,
14};
15use crate::ui_protocol::{
16    SUPPORTED_UI_PROTOCOLS, UI_PROTOCOL_CAPABILITIES, normalize_runtime_ui_protocol,
17};
18use adk_core::{RequestContext, SessionId, UserId};
19use axum::{
20    Json,
21    extract::{Path, State},
22    http::{HeaderMap, StatusCode, request::Parts},
23    response::sse::{Event, KeepAlive, Sse},
24};
25use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
26use futures::{StreamExt, stream::Stream};
27use serde::{Deserialize, Serialize};
28use serde_json::{Map, Value, json};
29use std::collections::HashMap;
30use std::convert::Infallible;
31use std::sync::Arc;
32use tracing::{Instrument, info, warn};
33use uuid::Uuid;
34
35fn default_streaming_true() -> bool {
36    true
37}
38
39const UI_PROTOCOL_HEADER: &str = "x-adk-ui-protocol";
40const UI_TRANSPORT_HEADER: &str = "x-adk-ui-transport";
41
42#[derive(Clone)]
43pub struct RuntimeController {
44    config: ServerConfig,
45    approval_service: Option<Arc<dyn adk_core::ApprovalService>>,
46    resumes: ResumesInProgress,
47    /// What the host adds to protocol-native AG-UI runs (spec 3.3 §6.1 `genui`).
48    ag_ui_extension: Option<Arc<dyn AgUiExtension>>,
49}
50
51impl RuntimeController {
52    pub fn new(config: ServerConfig) -> Self {
53        Self {
54            config,
55            approval_service: None,
56            resumes: ResumesInProgress::default(),
57            ag_ui_extension: None,
58        }
59    }
60
61    /// Adds `extension` to protocol-native AG-UI runs (spec 3.3 §6.1 `genui`, §10 S2): its
62    /// events after each event's own, its say on which `activity` messages a client sends back
63    /// are kept, and the call a run's `forwardedProps` action asks for, which the run's agent
64    /// holds so the run ends with a `tool_call` interrupt. Only an authenticated run may carry
65    /// such an action. See [`AgUiExtension`].
66    ///
67    /// # Example
68    ///
69    /// ```rust,ignore
70    /// let controller = RuntimeController::new(config).with_ag_ui_extension(Arc::new(extension));
71    /// ```
72    #[must_use]
73    pub fn with_ag_ui_extension(mut self, extension: Arc<dyn AgUiExtension>) -> Self {
74        self.ag_ui_extension = Some(extension);
75        self
76    }
77
78    /// The features the AG-UI extension adds to `ag_ui`, none without one.
79    pub(crate) fn ag_ui_features(&self) -> Vec<&'static str> {
80        self.ag_ui_extension.as_ref().map(|extension| extension.features()).unwrap_or_default()
81    }
82
83    /// Routes the calls that protocol-native AG-UI runs hold for approval to `service`,
84    /// and answers AG-UI resumes through it (spec 3.3 §10 S2).
85    ///
86    /// A held call ends the run with an AG-UI interrupt whose `id` is the call's inbox
87    /// entry, and a later run's `resume` entry becomes [`ApprovalService::decide`] on that
88    /// entry. A call the service routes to no inbox entry — no router, or a service without an
89    /// [`approval_store`](adk_core::ApprovalService::approval_store) — ends the run with an
90    /// interrupt carrying the call ID, `metadata.answerable: false` and no `responseSchema`.
91    /// `ServerBuilder::with_approval_service` (feature `approvals`) sets it.
92    ///
93    /// [`ApprovalService::decide`]: adk_core::ApprovalService::decide
94    ///
95    /// # Example
96    ///
97    /// ```rust,ignore
98    /// use adk_core::{ApprovalPolicy, ApproverSelector, InMemoryApprovalStore, StoreApprovalService};
99    ///
100    /// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
101    ///     .with_router(ApprovalPolicy::new([ApproverSelector::human("alice")]).allow_self_approval());
102    /// let controller = RuntimeController::new(config).with_approval_service(Arc::new(service));
103    /// ```
104    #[must_use]
105    pub fn with_approval_service(mut self, service: Arc<dyn adk_core::ApprovalService>) -> Self {
106        self.approval_service = Some(service);
107        self
108    }
109
110    /// Whether AG-UI resumes can be decided: the controller has an approval service.
111    pub(crate) fn answers_ag_ui_resume(&self) -> bool {
112        self.approval_service.is_some()
113    }
114}
115
116/// Attachment structure for the legacy /run endpoint
117#[derive(Serialize, Deserialize, Debug)]
118pub struct Attachment {
119    pub name: String,
120    #[serde(rename = "type")]
121    pub mime_type: String,
122    pub base64: String,
123}
124
125#[derive(Serialize, Deserialize)]
126pub struct RunRequest {
127    pub new_message: String,
128    #[serde(default, alias = "uiProtocol")]
129    pub ui_protocol: Option<String>,
130    #[serde(default)]
131    pub protocol: Option<String>,
132    #[serde(default, alias = "ui_transport")]
133    pub ui_transport: Option<String>,
134    #[serde(default)]
135    pub attachments: Vec<Attachment>,
136}
137
138/// Request format for /run_sse (adk-go compatible)
139#[derive(Serialize, Deserialize, Debug)]
140#[serde(rename_all = "camelCase")]
141pub struct RunSseRequest {
142    pub app_name: String,
143    pub user_id: String,
144    pub session_id: String,
145    #[serde(default)]
146    pub new_message: Option<NewMessage>,
147    #[serde(default = "default_streaming_true")]
148    pub streaming: bool,
149    #[serde(default)]
150    pub state_delta: Option<Value>,
151    #[serde(default, alias = "ui_protocol")]
152    pub ui_protocol: Option<String>,
153    #[serde(default)]
154    pub protocol: Option<String>,
155    #[serde(default, alias = "ui_transport")]
156    pub ui_transport: Option<String>,
157    #[serde(default)]
158    pub input: Option<AgUiRunInput>,
159    #[serde(default)]
160    pub ag_ui_input: Option<AgUiRunInput>,
161    #[serde(default)]
162    pub ag_ui_compatibility_event: Option<Value>,
163    #[serde(default)]
164    pub protocol_envelope: Option<Value>,
165    #[serde(default)]
166    pub mcp_apps_request: Option<McpAppsRuntimeEnvelope>,
167    #[serde(default)]
168    pub mcp_apps_initialize: Option<McpAppsRuntimeEnvelope>,
169    #[serde(default)]
170    pub mcp_apps_initialized: Option<Value>,
171    #[serde(default)]
172    pub method: Option<String>,
173    #[serde(default)]
174    pub params: Option<Value>,
175}
176
177#[derive(Serialize, Deserialize, Debug, Clone, Default)]
178#[serde(rename_all = "camelCase")]
179pub struct AgUiInputMessage {
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub id: Option<String>,
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub role: Option<String>,
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub name: Option<String>,
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub activity_type: Option<String>,
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub content: Option<Value>,
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub replace: Option<bool>,
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub patch: Option<Vec<Value>>,
194}
195
196#[derive(Serialize, Deserialize, Debug, Clone, Default)]
197#[serde(rename_all = "camelCase")]
198pub struct AgUiRunInput {
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub thread_id: Option<String>,
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub run_id: Option<String>,
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub parent_run_id: Option<String>,
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub state: Option<Value>,
207    #[serde(default)]
208    pub messages: Vec<AgUiInputMessage>,
209    #[serde(default, skip_serializing_if = "Vec::is_empty")]
210    pub tools: Vec<Value>,
211    #[serde(default, skip_serializing_if = "Vec::is_empty")]
212    pub context: Vec<Value>,
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub forwarded_props: Option<Value>,
215    /// The AG-UI protocol version the client speaks, such as `1.0`. A client that names 1.0
216    /// gets AG-UI 1.0's run shape: a success outcome, snapshots before an interrupt, the
217    /// server-execution marker on tool calls, strict event fields, and a resume that must
218    /// answer every open interrupt (spec 3.3 §10 S2).
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub protocol_version: Option<String>,
221    /// Answers to the interrupts the previous run on the thread ended with (spec 3.3 §10
222    /// S2). A run that carries them starts no new user turn unless `newMessage` is set.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub resume: Option<AgUiResume>,
225}
226
227/// The `resume` of an AG-UI run input (spec 3.3 §10 S2): the AG-UI 1.0 list of
228/// [`AgUiResumeEntry`], or the single entry of the earlier interrupt draft.
229///
230/// # Example
231///
232/// ```rust
233/// use adk_server::rest::controllers::runtime::{AgUiResume, AgUiResumeStatus};
234/// use serde_json::json;
235///
236/// let resume: AgUiResume = serde_json::from_value(json!([
237///     { "interruptId": "apr_1", "status": "resolved", "payload": { "approved": true } }
238/// ]))
239/// .unwrap();
240/// assert_eq!(resume.entries()[0].status, AgUiResumeStatus::Resolved);
241/// ```
242#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
243#[serde(untagged)]
244pub enum AgUiResume {
245    /// One entry per interrupt, as AG-UI 1.0 sends them.
246    Entries(Vec<AgUiResumeEntry>),
247    /// One entry, as the earlier draft sends it.
248    Entry(AgUiResumeEntry),
249}
250
251impl AgUiResume {
252    /// The entries, in order.
253    pub fn entries(&self) -> &[AgUiResumeEntry] {
254        match self {
255            Self::Entries(entries) => entries,
256            Self::Entry(entry) => std::slice::from_ref(entry),
257        }
258    }
259}
260
261/// One answer to an AG-UI interrupt (spec 3.3 §10 S2; AG-UI `ResumeEntry`).
262///
263/// A `resolved` answer's `payload` is `{"approved": true}` (allow once),
264/// `{"approved": true, "editedArgs": {...}}` (edit), or
265/// `{"approved": false, "reason": "..."}` (deny). `metadata.version`, when the client echoes
266/// the version its interrupt carried, is the inbox entry version the decision is made at.
267///
268/// # Example
269///
270/// ```rust
271/// use adk_server::rest::controllers::runtime::{AgUiResumeEntry, AgUiResumeStatus};
272/// use serde_json::json;
273///
274/// let entry: AgUiResumeEntry = serde_json::from_value(json!({
275///     "interruptId": "apr_1",
276///     "payload": { "approved": false, "reason": "wrong client" }
277/// }))
278/// .unwrap();
279/// assert_eq!(entry.status, AgUiResumeStatus::Resolved);
280/// ```
281#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
282#[serde(rename_all = "camelCase")]
283pub struct AgUiResumeEntry {
284    /// The interrupt answered, as the interrupt's `id` named it.
285    pub interrupt_id: String,
286    /// Whether the person answered or abandoned the interrupt; `resolved` when absent.
287    #[serde(default)]
288    pub status: AgUiResumeStatus,
289    /// The answer.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub payload: Option<Value>,
292    /// Envelope information, not part of the answer.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub metadata: Option<Value>,
295}
296
297/// How an AG-UI client ended an interrupt (spec 3.3 §10 S2).
298///
299/// # Example
300///
301/// ```rust
302/// use adk_server::rest::controllers::runtime::AgUiResumeStatus;
303///
304/// assert_eq!(serde_json::to_value(AgUiResumeStatus::Cancelled).unwrap(), "cancelled");
305/// ```
306#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)]
307#[serde(rename_all = "camelCase")]
308pub enum AgUiResumeStatus {
309    /// The person answered; the payload is the answer.
310    #[default]
311    Resolved,
312    /// The person abandoned the interrupt; the decision keeps waiting in the inbox.
313    Cancelled,
314}
315
316#[derive(Serialize, Deserialize, Debug, Clone)]
317#[serde(rename_all = "camelCase")]
318pub struct McpAppsRuntimeEnvelope {
319    pub method: String,
320    #[serde(default)]
321    pub params: Option<Value>,
322}
323
324#[derive(Serialize, Deserialize, Debug, Clone)]
325pub struct NewMessage {
326    pub role: String,
327    pub parts: Vec<MessagePart>,
328}
329
330#[derive(Serialize, Deserialize, Debug, Clone, Default)]
331pub struct MessagePart {
332    #[serde(default)]
333    pub text: Option<String>,
334    #[serde(default, rename = "inlineData")]
335    pub inline_data: Option<InlineData>,
336    /// A function call, in Gemini's shape.
337    #[serde(default, rename = "functionCall", skip_serializing_if = "Option::is_none")]
338    pub function_call: Option<FunctionCallPart>,
339    /// A function's result, in Gemini's shape. Sent with the call's `id`, it answers a
340    /// long-running call, as adk-python and adk-go accept.
341    #[serde(default, rename = "functionResponse", skip_serializing_if = "Option::is_none")]
342    pub function_response: Option<FunctionResponsePart>,
343}
344
345/// A function call in a message part: `{id, name, args}`.
346#[derive(Serialize, Deserialize, Debug, Clone)]
347pub struct FunctionCallPart {
348    /// The call id.
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub id: Option<String>,
351    /// The function's name.
352    pub name: String,
353    /// The call's arguments.
354    #[serde(default)]
355    pub args: serde_json::Value,
356}
357
358/// A function's result in a message part: `{id, name, response}`.
359#[derive(Serialize, Deserialize, Debug, Clone)]
360pub struct FunctionResponsePart {
361    /// The id of the call this answers.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub id: Option<String>,
364    /// The function's name.
365    pub name: String,
366    /// The result.
367    #[serde(default)]
368    pub response: serde_json::Value,
369}
370
371#[derive(Serialize, Deserialize, Debug, Clone)]
372#[serde(rename_all = "camelCase")]
373pub struct InlineData {
374    pub display_name: Option<String>,
375    pub data: String,
376    pub mime_type: String,
377}
378
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380enum UiProfile {
381    AdkUi,
382    A2ui,
383    AgUi,
384    McpApps,
385}
386
387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
388enum UiTransportMode {
389    LegacyWrapper,
390    ProtocolNative,
391}
392
393impl UiProfile {
394    fn as_str(self) -> &'static str {
395        match self {
396            Self::AdkUi => "adk_ui",
397            Self::A2ui => "a2ui",
398            Self::AgUi => "ag_ui",
399            Self::McpApps => "mcp_apps",
400        }
401    }
402}
403
404type RuntimeError = (StatusCode, String);
405
406/// Convert an `AdkError` into a `RuntimeError` using the structured error envelope.
407///
408/// Uses `AdkError::http_status_code()` for the HTTP status and the error's Problem JSON for
409/// the response body, its message withheld unless `expose_details` is set or the server wrote
410/// it (see [`SecurityConfig::expose_error_details`](crate::SecurityConfig::expose_error_details)).
411fn adk_err_to_runtime(err: adk_core::AdkError, expose_details: bool) -> RuntimeError {
412    let status =
413        StatusCode::from_u16(err.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
414    let body = error_details::problem_json(&err, expose_details).to_string();
415    (status, body)
416}
417
418fn parse_ui_profile(raw: &str) -> Option<UiProfile> {
419    match normalize_runtime_ui_protocol(raw)? {
420        "adk_ui" => Some(UiProfile::AdkUi),
421        "a2ui" => Some(UiProfile::A2ui),
422        "ag_ui" => Some(UiProfile::AgUi),
423        "mcp_apps" => Some(UiProfile::McpApps),
424        _ => None,
425    }
426}
427
428fn resolve_ui_profile(
429    headers: &HeaderMap,
430    body_ui_protocol: Option<&str>,
431) -> Result<UiProfile, RuntimeError> {
432    let header_value = headers.get(UI_PROTOCOL_HEADER).and_then(|v| v.to_str().ok());
433    let candidate = header_value.or(body_ui_protocol);
434
435    let Some(raw) = candidate else {
436        return Ok(UiProfile::AdkUi);
437    };
438
439    parse_ui_profile(raw).ok_or_else(|| {
440        let supported = SUPPORTED_UI_PROTOCOLS.join(", ");
441        warn!(
442            requested = %raw,
443            header = %UI_PROTOCOL_HEADER,
444            "unsupported ui protocol requested"
445        );
446        (
447            StatusCode::BAD_REQUEST,
448            format!("Unsupported ui protocol '{}'. Supported profiles: {}", raw, supported),
449        )
450    })
451}
452
453fn parse_ui_transport(raw: &str) -> Option<UiTransportMode> {
454    match raw.trim().to_ascii_lowercase().as_str() {
455        "legacy" | "legacy_wrapper" => Some(UiTransportMode::LegacyWrapper),
456        "native" | "protocol_native" => Some(UiTransportMode::ProtocolNative),
457        _ => None,
458    }
459}
460
461fn resolve_ui_transport(
462    headers: &HeaderMap,
463    body_ui_transport: Option<&str>,
464) -> Result<UiTransportMode, RuntimeError> {
465    let header_value = headers.get(UI_TRANSPORT_HEADER).and_then(|v| v.to_str().ok());
466    let candidate = header_value.or(body_ui_transport);
467
468    let Some(raw) = candidate else {
469        return Ok(UiTransportMode::LegacyWrapper);
470    };
471
472    parse_ui_transport(raw).ok_or_else(|| {
473        warn!(
474            requested = %raw,
475            header = %UI_TRANSPORT_HEADER,
476            "unsupported ui transport requested"
477        );
478        (
479            StatusCode::BAD_REQUEST,
480            format!(
481                "Unsupported ui transport '{}'. Supported values: legacy_wrapper, protocol_native",
482                raw
483            ),
484        )
485    })
486}
487
488fn validate_transport_support(
489    profile: UiProfile,
490    transport: UiTransportMode,
491) -> Result<(), RuntimeError> {
492    if transport == UiTransportMode::ProtocolNative && profile != UiProfile::AgUi {
493        return Err((
494            StatusCode::BAD_REQUEST,
495            "protocol_native transport is currently available only for ag_ui; use the MCP Apps bridge endpoints for mcp_apps".to_string(),
496        ));
497    }
498    Ok(())
499}
500
501fn protocol_from_envelope(envelope: &Value) -> Option<&str> {
502    envelope.as_object().and_then(|object| object.get("protocol")).and_then(|value| value.as_str())
503}
504
505fn serialize_runtime_event(event: &adk_core::Event, profile: UiProfile) -> Option<String> {
506    if profile == UiProfile::AdkUi {
507        return serde_json::to_string(event).ok();
508    }
509
510    serde_json::to_string(&json!({
511        "ui_protocol": profile.as_str(),
512        "event": event
513    }))
514    .ok()
515}
516
517fn serialize_runtime_error(
518    error: &adk_core::AdkError,
519    profile: UiProfile,
520    expose_details: bool,
521) -> Option<String> {
522    let mut event = adk_core::Event::new(String::new());
523    event.llm_response.error_code = Some(error.code.to_string());
524    event.llm_response.error_message = Some(error_details::display(error, expose_details));
525    serialize_runtime_event(&event, profile)
526}
527
528fn infer_sse_request_protocol(req: &RunSseRequest) -> Option<&str> {
529    req.ui_protocol
530        .as_deref()
531        .or(req.protocol.as_deref())
532        .or_else(|| req.protocol_envelope.as_ref().and_then(protocol_from_envelope))
533        .or_else(|| req.ag_ui_input.as_ref().map(|_| "ag_ui"))
534        .or_else(|| req.input.as_ref().map(|_| "ag_ui"))
535        .or_else(|| req.mcp_apps_request.as_ref().map(|_| "mcp_apps"))
536        .or_else(|| req.mcp_apps_initialize.as_ref().map(|_| "mcp_apps"))
537}
538
539fn infer_run_request_protocol(req: &RunRequest) -> Option<&str> {
540    req.ui_protocol.as_deref().or(req.protocol.as_deref())
541}
542
543fn ag_ui_input_from_request(req: &RunSseRequest) -> Option<AgUiRunInput> {
544    req.ag_ui_input.clone().or_else(|| req.input.clone()).or_else(|| {
545        let envelope = req.protocol_envelope.as_ref()?;
546        if protocol_from_envelope(envelope)? != "ag_ui" {
547            return None;
548        }
549        envelope
550            .as_object()
551            .and_then(|object| object.get("input"))
552            .and_then(|value| serde_json::from_value(value.clone()).ok())
553    })
554}
555
556fn mcp_apps_request_from_request(req: &RunSseRequest) -> Option<McpAppsRuntimeEnvelope> {
557    req.mcp_apps_request.clone().or_else(|| {
558        if let Some(method) = req.method.clone() {
559            return Some(McpAppsRuntimeEnvelope { method, params: req.params.clone() });
560        }
561        let envelope = req.protocol_envelope.as_ref()?;
562        if protocol_from_envelope(envelope)? != "mcp_apps" {
563            return None;
564        }
565        let object = envelope.as_object()?;
566        let method = object.get("method")?.as_str()?.to_string();
567        let params = object.get("params").cloned();
568        Some(McpAppsRuntimeEnvelope { method, params })
569    })
570}
571
572fn mcp_apps_initialize_from_request(req: &RunSseRequest) -> Option<McpAppsRuntimeEnvelope> {
573    req.mcp_apps_initialize.clone()
574}
575
576fn extract_text_segments(value: &Value) -> Vec<String> {
577    match value {
578        Value::String(text) => {
579            let trimmed = text.trim();
580            if trimmed.is_empty() { vec![] } else { vec![trimmed.to_string()] }
581        }
582        Value::Array(items) => items
583            .iter()
584            .flat_map(|item| {
585                if let Some(text) = item
586                    .as_object()
587                    .and_then(|object| object.get("text"))
588                    .and_then(|text| text.as_str())
589                {
590                    let trimmed = text.trim();
591                    if !trimmed.is_empty() {
592                        return vec![trimmed.to_string()];
593                    }
594                }
595                vec![]
596            })
597            .collect(),
598        Value::Object(object) => object
599            .get("text")
600            .and_then(|text| text.as_str())
601            .map(|text| text.trim().to_string())
602            .filter(|text| !text.is_empty())
603            .into_iter()
604            .collect(),
605        _ => vec![],
606    }
607}
608
609fn new_message_from_ag_ui_input(input: &AgUiRunInput) -> Option<NewMessage> {
610    let selected = input
611        .messages
612        .iter()
613        .rev()
614        .find(|message| message.role.as_deref().unwrap_or("user") == "user")
615        .or_else(|| input.messages.last())?;
616
617    let content = selected.content.as_ref()?;
618    let parts: Vec<MessagePart> = extract_text_segments(content)
619        .into_iter()
620        .map(|text| MessagePart { text: Some(text), ..MessagePart::default() })
621        .collect();
622    if parts.is_empty() {
623        return None;
624    }
625
626    Some(NewMessage { role: selected.role.clone().unwrap_or_else(|| "user".to_string()), parts })
627}
628
629fn activity_content_snapshot(value: Option<&Value>) -> Value {
630    match value.cloned() {
631        Some(Value::Object(object)) => Value::Object(object),
632        Some(other) => json!({ "value": other }),
633        None => json!({}),
634    }
635}
636
637fn activity_message_id(message: &AgUiInputMessage) -> String {
638    message.id.clone().unwrap_or_else(|| format!("activity-{}", Uuid::new_v4()))
639}
640
641fn activity_message_type(message: &AgUiInputMessage) -> String {
642    message
643        .activity_type
644        .clone()
645        .or_else(|| message.name.clone())
646        .unwrap_or_else(|| "CUSTOM".to_string())
647}
648
649fn activity_events_from_ag_ui_input(input: &AgUiRunInput) -> Vec<Value> {
650    input
651        .messages
652        .iter()
653        .filter(|message| message.role.as_deref() == Some("activity"))
654        .map(|message| {
655            let timestamp = chrono::Utc::now().timestamp_millis().max(0) as u64;
656            let message_id = activity_message_id(message);
657            let activity_type = activity_message_type(message);
658            if let Some(patch) = &message.patch {
659                json!({
660                    "type": "ACTIVITY_DELTA",
661                    "messageId": message_id,
662                    "activityType": activity_type,
663                    "patch": patch,
664                    "timestamp": timestamp,
665                })
666            } else {
667                let mut event = json!({
668                    "type": "ACTIVITY_SNAPSHOT",
669                    "messageId": message_id,
670                    "activityType": activity_type,
671                    "content": activity_content_snapshot(message.content.as_ref()),
672                    "timestamp": timestamp,
673                });
674                if let Some(replace) = message.replace
675                    && let Some(object) = event.as_object_mut()
676                {
677                    object.insert("replace".to_string(), Value::Bool(replace));
678                }
679                event
680            }
681        })
682        .collect()
683}
684
685fn messages_snapshot_from_ag_ui_input(input: &AgUiRunInput) -> Option<Value> {
686    if input.messages.is_empty() {
687        return None;
688    }
689
690    let filtered: Vec<AgUiInputMessage> = input
691        .messages
692        .iter()
693        .filter(|message| !(message.role.as_deref() == Some("activity") && message.patch.is_some()))
694        .cloned()
695        .collect();
696    if filtered.is_empty() {
697        return None;
698    }
699
700    serde_json::to_value(filtered).ok()
701}
702
703fn object_entries_to_state_delta(object: &Map<String, Value>) -> HashMap<String, Value> {
704    object.iter().map(|(key, value)| (key.clone(), value.clone())).collect()
705}
706
707fn ag_ui_state_delta(input: &AgUiRunInput) -> HashMap<String, Value> {
708    let mut delta = HashMap::new();
709
710    if let Some(state) = input.state.clone() {
711        match state {
712            Value::Object(object) => {
713                delta.extend(object_entries_to_state_delta(&object));
714            }
715            value => {
716                delta.insert("temp:ag_ui_state".to_string(), value);
717            }
718        }
719    }
720
721    if !input.messages.is_empty()
722        && let Ok(value) = serde_json::to_value(&input.messages)
723    {
724        delta.insert("temp:ag_ui_messages".to_string(), value);
725    }
726    if !input.tools.is_empty() {
727        delta.insert("temp:ag_ui_tools".to_string(), Value::Array(input.tools.clone()));
728    }
729    if !input.context.is_empty() {
730        delta.insert("temp:ag_ui_context".to_string(), Value::Array(input.context.clone()));
731    }
732    if let Some(forwarded_props) = input.forwarded_props.clone() {
733        delta.insert("temp:ag_ui_forwarded_props".to_string(), forwarded_props);
734    }
735
736    delta
737}
738
739fn body_state_delta(value: Option<&Value>) -> Result<HashMap<String, Value>, RuntimeError> {
740    let Some(value) = value else {
741        return Ok(HashMap::new());
742    };
743    let object = value.as_object().ok_or_else(|| {
744        (StatusCode::BAD_REQUEST, "stateDelta must be a JSON object when provided".to_string())
745    })?;
746    Ok(object_entries_to_state_delta(object))
747}
748
749fn log_profile_deprecation(profile: UiProfile) {
750    if profile != UiProfile::AdkUi {
751        return;
752    }
753    let Some(spec) = UI_PROTOCOL_CAPABILITIES
754        .iter()
755        .find(|capability| capability.protocol == profile.as_str())
756        .and_then(|capability| capability.deprecation)
757    else {
758        return;
759    };
760
761    warn!(
762        protocol = %profile.as_str(),
763        stage = %spec.stage,
764        announced_on = %spec.announced_on,
765        sunset_target_on = ?spec.sunset_target_on,
766        replacements = ?spec.replacement_protocols,
767        "legacy ui protocol profile selected"
768    );
769}
770
771/// Build Content from message text and attachments
772fn build_content_with_attachments(
773    text: &str,
774    attachments: &[Attachment],
775) -> Result<adk_core::Content, RuntimeError> {
776    let mut content = adk_core::Content::new("user");
777
778    // Add the text part
779    content.parts.push(adk_core::Part::Text { text: text.to_string() });
780
781    // Add attachment parts
782    for attachment in attachments {
783        match BASE64_STANDARD.decode(&attachment.base64) {
784            Ok(data) => {
785                if data.len() > adk_core::MAX_INLINE_DATA_SIZE {
786                    return Err((
787                        StatusCode::PAYLOAD_TOO_LARGE,
788                        format!(
789                            "Attachment '{}' exceeds max inline size of {} bytes",
790                            attachment.name,
791                            adk_core::MAX_INLINE_DATA_SIZE
792                        ),
793                    ));
794                }
795                content.parts.push(adk_core::Part::InlineData {
796                    mime_type: attachment.mime_type.clone(),
797                    data,
798                    uri: None,
799                    annotations: None,
800                });
801            }
802            Err(e) => {
803                return Err((
804                    StatusCode::BAD_REQUEST,
805                    format!("Invalid base64 data for attachment '{}': {}", attachment.name, e),
806                ));
807            }
808        }
809    }
810
811    Ok(content)
812}
813
814/// Build Content from message parts (for /run_sse endpoint)
815fn build_content_from_parts(parts: &[MessagePart]) -> Result<adk_core::Content, RuntimeError> {
816    let mut content = adk_core::Content::new("user");
817
818    for part in parts {
819        // Add text part if present
820        if let Some(text) = &part.text {
821            content.parts.push(adk_core::Part::Text { text: text.clone() });
822        }
823
824        // Add inline data part if present
825        if let Some(inline_data) = &part.inline_data {
826            match BASE64_STANDARD.decode(&inline_data.data) {
827                Ok(data) => {
828                    if data.len() > adk_core::MAX_INLINE_DATA_SIZE {
829                        return Err((
830                            StatusCode::PAYLOAD_TOO_LARGE,
831                            format!(
832                                "inline_data exceeds max inline size of {} bytes",
833                                adk_core::MAX_INLINE_DATA_SIZE
834                            ),
835                        ));
836                    }
837                    content.parts.push(adk_core::Part::InlineData {
838                        mime_type: inline_data.mime_type.clone(),
839                        data,
840                        uri: None,
841                        annotations: None,
842                    });
843                }
844                Err(e) => {
845                    return Err((
846                        StatusCode::BAD_REQUEST,
847                        format!("Invalid base64 data in inline_data: {}", e),
848                    ));
849                }
850            }
851        }
852
853        if let Some(call) = &part.function_call {
854            content.parts.push(adk_core::Part::FunctionCall {
855                name: call.name.clone(),
856                args: call.args.clone(),
857                id: call.id.clone(),
858                thought_signature: None,
859            });
860        }
861
862        if let Some(response) = &part.function_response {
863            content.parts.push(adk_core::Part::FunctionResponse {
864                function_response: adk_core::FunctionResponseData::new(
865                    response.name.clone(),
866                    response.response.clone(),
867                ),
868                id: response.id.clone(),
869                annotations: None,
870            });
871        }
872    }
873
874    Ok(content)
875}
876
877async fn apply_state_delta_to_session(
878    session_service: &std::sync::Arc<dyn adk_session::SessionService>,
879    app_name: &str,
880    user_id: &str,
881    session_id: &str,
882    state_delta: HashMap<String, Value>,
883    expose_details: bool,
884) -> Result<(), RuntimeError> {
885    if state_delta.is_empty() {
886        return Ok(());
887    }
888
889    let identity = adk_core::AdkIdentity::new(
890        adk_core::AppName::try_from(app_name).map_err(|error| {
891            (
892                StatusCode::BAD_REQUEST,
893                format!("invalid app_name for state delta application: {}", error),
894            )
895        })?,
896        adk_core::UserId::try_from(user_id).map_err(|error| {
897            (
898                StatusCode::BAD_REQUEST,
899                format!("invalid user_id for state delta application: {}", error),
900            )
901        })?,
902        adk_core::SessionId::try_from(session_id).map_err(|error| {
903            (
904                StatusCode::BAD_REQUEST,
905                format!("invalid session_id for state delta application: {}", error),
906            )
907        })?,
908    );
909
910    let mut event = adk_core::Event::new(format!("ui-input-{}", Uuid::new_v4()));
911    event.author = "ui_protocol_bridge".to_string();
912    event.actions.state_delta = state_delta;
913    session_service
914        .append_event_for_identity(adk_session::AppendEventRequest { identity, event })
915        .await
916        .map_err(|error| adk_err_to_runtime(error, expose_details))
917}
918
919/// Whether a run creates the session it names when that session does not exist.
920#[derive(Debug, Clone, Copy, PartialEq, Eq)]
921enum MissingSession {
922    /// The run is refused with 404, as adk-python and adk-go refuse it: an ADK client
923    /// creates its session first (`POST /apps/{app}/users/{user}/sessions`).
924    Refuse,
925    /// The session is created. A UI protocol's host (AG-UI, A2UI, MCP Apps) names its
926    /// thread and expects the run to start it.
927    Create,
928}
929
930/// The [`MissingSession`] rule for a `/run_sse` request in `profile`.
931fn missing_session_rule(profile: UiProfile) -> MissingSession {
932    match profile {
933        UiProfile::AdkUi => MissingSession::Refuse,
934        UiProfile::A2ui | UiProfile::AgUi | UiProfile::McpApps => MissingSession::Create,
935    }
936}
937
938/// Applies `state_delta` to the session when it exists. When it does not, `missing` decides:
939/// the run is refused with 404, or the session is created with `state_delta` as its initial
940/// state.
941///
942/// Only a `session.not_found` read counts as missing. Any other read failure is returned, so
943/// a transient backend error never replaces a stored session. A create that loses a race to
944/// a concurrent request finds the session that request created and applies `state_delta`
945/// to it.
946async fn ensure_session(
947    session_service: &std::sync::Arc<dyn adk_session::SessionService>,
948    app_name: &str,
949    user_id: &str,
950    session_id: &str,
951    state_delta: HashMap<String, Value>,
952    expose_details: bool,
953    missing: MissingSession,
954) -> Result<(), RuntimeError> {
955    let existing = session_service
956        .get(adk_session::GetRequest {
957            app_name: app_name.to_string(),
958            user_id: user_id.to_string(),
959            session_id: session_id.to_string(),
960            num_recent_events: None,
961            after: None,
962        })
963        .await;
964    match existing {
965        Ok(_) => {
966            apply_state_delta_to_session(
967                session_service,
968                app_name,
969                user_id,
970                session_id,
971                state_delta,
972                expose_details,
973            )
974            .await
975        }
976        // 404 with code `session.not_found`, as the path-style run answers.
977        Err(error) if error.is_not_found() && missing == MissingSession::Refuse => {
978            Err(adk_err_to_runtime(error, expose_details))
979        }
980        Err(error) if error.is_not_found() => {
981            let created = session_service
982                .create(adk_session::CreateRequest {
983                    app_name: app_name.to_string(),
984                    user_id: user_id.to_string(),
985                    session_id: Some(session_id.to_string()),
986                    state: state_delta.clone(),
987                })
988                .await;
989            match created {
990                Ok(_) => Ok(()),
991                Err(error) if error.is_conflict() => {
992                    apply_state_delta_to_session(
993                        session_service,
994                        app_name,
995                        user_id,
996                        session_id,
997                        state_delta,
998                        expose_details,
999                    )
1000                    .await
1001                }
1002                Err(error) => Err(adk_err_to_runtime(error, expose_details)),
1003            }
1004        }
1005        Err(error) => Err(adk_err_to_runtime(error, expose_details)),
1006    }
1007}
1008
1009fn merge_runtime_state_delta(
1010    body_delta: HashMap<String, Value>,
1011    ag_ui_delta: HashMap<String, Value>,
1012) -> HashMap<String, Value> {
1013    let mut merged = body_delta;
1014    merged.extend(ag_ui_delta);
1015    merged
1016}
1017
1018fn json_pointer_escape(segment: &str) -> String {
1019    segment.replace('~', "~0").replace('/', "~1")
1020}
1021
1022fn state_delta_to_json_patch(delta: &HashMap<String, Value>) -> Vec<Value> {
1023    delta
1024        .iter()
1025        .map(|(key, value)| {
1026            json!({
1027                "op": "add",
1028                "path": format!("/{}", json_pointer_escape(key)),
1029                "value": value
1030            })
1031        })
1032        .collect()
1033}
1034
1035fn timestamp_millis(event: &adk_core::Event) -> u64 {
1036    event.timestamp.timestamp_millis().max(0) as u64
1037}
1038
1039fn serialize_ag_ui_tool_call_delta(args: &Value, allow_raw_string_delta: bool) -> String {
1040    if allow_raw_string_delta && let Value::String(delta) = args {
1041        return delta.clone();
1042    }
1043
1044    serde_json::to_string(args).unwrap_or_else(|_| args.to_string())
1045}
1046
1047fn translate_ag_ui_event(
1048    event: &adk_core::Event,
1049    thread_id: &str,
1050    run_id: &str,
1051    open: &AgUiMessages,
1052) -> Vec<Value> {
1053    let mut translated = Vec::new();
1054    let timestamp = timestamp_millis(event);
1055    let is_partial = event.llm_response.partial;
1056    // Every action is named, so a new kind is a compile error here rather than dropped.
1057    let adk_core::EventActions {
1058        state_delta,
1059        // AG-UI 1.0 has no event for these; they stay in the session.
1060        artifact_delta: _,
1061        skip_summarization: _,
1062        transfer_to_agent: _,
1063        escalate: _,
1064        compaction: _,
1065        route: _,
1066        input_screened: _,
1067        workflow_positions: _,
1068        // A held call ends the run with an interrupt (spec 3.3 §10 S2), built when the
1069        // run finishes; a decision is reported by the result of the call it decided.
1070        tool_confirmation,
1071        tool_confirmation_decision: _,
1072        steering,
1073        // AG-UI 1.0 has no event for retrieved sources; they stay in the session.
1074        grounding_sources: _,
1075    } = &event.actions;
1076    // A steering message is the person's own input, which, like the run's message, this
1077    // translation does not echo; it stays in the session.
1078    if steering.is_some() {
1079        return translated;
1080    }
1081
1082    if !state_delta.is_empty() {
1083        translated.push(json!({
1084            "type": "STATE_DELTA",
1085            "delta": state_delta_to_json_patch(state_delta),
1086            "timestamp": timestamp,
1087        }));
1088    }
1089
1090    if let Some(message) = event.llm_response.error_message.clone() {
1091        translated.push(json!({
1092            "type": "RUN_ERROR",
1093            "threadId": thread_id,
1094            "runId": run_id,
1095            "message": message,
1096            "code": event.llm_response.error_code,
1097            "timestamp": timestamp,
1098        }));
1099    }
1100
1101    // The text of the event that holds a call is the agent's placeholder; the interrupt
1102    // describes the decision instead, drawn from the inbox entry (spec 3.3 §7.1).
1103    if tool_confirmation.is_some() {
1104        return translated;
1105    }
1106    let Some(content) = &event.llm_response.content else {
1107        return translated;
1108    };
1109
1110    let mut text_seen = false;
1111    let mut thinking_seen = false;
1112    for (index, part) in content.parts.iter().enumerate() {
1113        match part {
1114            // Every text part of the event is one message, sent at the first.
1115            adk_core::Part::Text { .. } => {
1116                if text_seen {
1117                    continue;
1118                }
1119                text_seen = true;
1120                let text: String = content
1121                    .parts
1122                    .iter()
1123                    .filter_map(|part| match part {
1124                        adk_core::Part::Text { text } => Some(text.as_str()),
1125                        _ => None,
1126                    })
1127                    .collect();
1128                if text.is_empty() && (is_partial || open.text.is_none()) {
1129                    continue;
1130                }
1131                let message_id =
1132                    open.text.clone().unwrap_or_else(|| format!("{}-text-{}", event.id, index));
1133                if is_partial {
1134                    translated.push(json!({
1135                        "type": "TEXT_MESSAGE_CHUNK",
1136                        "messageId": message_id,
1137                        "role": "assistant",
1138                        "delta": text,
1139                        "timestamp": timestamp,
1140                    }));
1141                } else {
1142                    if open.text.is_none() {
1143                        translated.push(json!({
1144                        "type": "TEXT_MESSAGE_START",
1145                        "messageId": message_id,
1146                        "role": "assistant",
1147                        "timestamp": timestamp,
1148                        }));
1149                    }
1150                    if !text.is_empty() {
1151                        translated.push(json!({
1152                        "type": "TEXT_MESSAGE_CONTENT",
1153                        "messageId": message_id,
1154                        "delta": text,
1155                        "timestamp": timestamp,
1156                        }));
1157                    }
1158                    translated.push(json!({
1159                        "type": "TEXT_MESSAGE_END",
1160                        "messageId": message_id,
1161                        "timestamp": timestamp,
1162                    }));
1163                }
1164            }
1165            adk_core::Part::Thinking { .. } => {
1166                if thinking_seen {
1167                    continue;
1168                }
1169                thinking_seen = true;
1170                let thinking: String = content
1171                    .parts
1172                    .iter()
1173                    .filter_map(|part| match part {
1174                        adk_core::Part::Thinking { thinking, .. } => Some(thinking.as_str()),
1175                        _ => None,
1176                    })
1177                    .collect();
1178                if thinking.is_empty() && (is_partial || open.reasoning.is_none()) {
1179                    continue;
1180                }
1181                let message_id = open
1182                    .reasoning
1183                    .clone()
1184                    .unwrap_or_else(|| format!("{}-reasoning-{}", event.id, index));
1185                if is_partial {
1186                    translated.push(json!({
1187                        "type": "REASONING_MESSAGE_CHUNK",
1188                        "messageId": message_id,
1189                        "delta": thinking,
1190                        "timestamp": timestamp,
1191                    }));
1192                } else {
1193                    let reasoning_id = format!("{}-reasoning-phase-{}", event.id, index);
1194                    if open.reasoning.is_none() {
1195                        translated.push(json!({
1196                            "type": "REASONING_START",
1197                            "messageId": reasoning_id,
1198                            "timestamp": timestamp,
1199                        }));
1200                        translated.push(json!({
1201                        "type": "REASONING_MESSAGE_START",
1202                        "messageId": message_id,
1203                        "role": "assistant",
1204                        "timestamp": timestamp,
1205                        }));
1206                    }
1207                    if !thinking.is_empty() {
1208                        translated.push(json!({
1209                        "type": "REASONING_MESSAGE_CONTENT",
1210                        "messageId": message_id,
1211                        "delta": thinking,
1212                        "timestamp": timestamp,
1213                        }));
1214                    }
1215                    translated.push(json!({
1216                        "type": "REASONING_MESSAGE_END",
1217                        "messageId": message_id,
1218                        "timestamp": timestamp,
1219                    }));
1220                    translated.push(json!({
1221                        "type": "REASONING_END",
1222                        "messageId": reasoning_id,
1223                        "timestamp": timestamp,
1224                    }));
1225                }
1226            }
1227            adk_core::Part::FunctionCall { name, args, id, .. } => {
1228                let tool_call_id =
1229                    id.clone().unwrap_or_else(|| format!("{}-tool-call-{}", event.id, index));
1230                let raw_chunk_supported = is_partial && matches!(args, Value::String(_));
1231                let args_delta = serialize_ag_ui_tool_call_delta(args, raw_chunk_supported);
1232                if raw_chunk_supported {
1233                    translated.push(json!({
1234                        "type": "TOOL_CALL_CHUNK",
1235                        "toolCallId": tool_call_id,
1236                        "toolCallName": name,
1237                        "delta": args_delta,
1238                        "timestamp": timestamp,
1239                    }));
1240                } else {
1241                    translated.push(json!({
1242                        "type": "TOOL_CALL_START",
1243                        "toolCallId": tool_call_id,
1244                        "toolCallName": name,
1245                        "timestamp": timestamp,
1246                    }));
1247                    translated.push(json!({
1248                        "type": "TOOL_CALL_ARGS",
1249                        "toolCallId": id.clone().unwrap_or_else(|| format!("{}-tool-call-{}", event.id, index)),
1250                        "delta": args_delta,
1251                        "timestamp": timestamp,
1252                    }));
1253                    translated.push(json!({
1254                        "type": "TOOL_CALL_END",
1255                        "toolCallId": id.clone().unwrap_or_else(|| format!("{}-tool-call-{}", event.id, index)),
1256                        "timestamp": timestamp,
1257                    }));
1258                }
1259            }
1260            adk_core::Part::FunctionResponse { function_response, id, .. } => {
1261                // A held call has no result yet: it arrives against the same tool call ID
1262                // in the run that resumes it.
1263                if adk_core::is_confirmation_pending(&function_response.response) {
1264                    continue;
1265                }
1266                let tool_call_id =
1267                    id.clone().unwrap_or_else(|| format!("{}-tool-result-{}", event.id, index));
1268                let response_content = serde_json::to_string(&function_response.response)
1269                    .unwrap_or_else(|_| function_response.response.to_string());
1270                translated.push(json!({
1271                    "type": "TOOL_CALL_RESULT",
1272                    "messageId": format!("msg-{}", tool_call_id),
1273                    "toolCallId": tool_call_id,
1274                    "toolCallName": function_response.name,
1275                    "content": response_content,
1276                    "role": "tool",
1277                    "timestamp": timestamp,
1278                }));
1279            }
1280            // AG-UI 1.0 has no event for inline or file data, provider-executed tools, or
1281            // embedded resources.
1282            adk_core::Part::InlineData { .. }
1283            | adk_core::Part::FileData { .. }
1284            | adk_core::Part::ServerToolCall { .. }
1285            | adk_core::Part::ServerToolResponse { .. }
1286            | adk_core::Part::EmbeddedResource { .. } => {}
1287        }
1288    }
1289
1290    translated
1291}
1292
1293/// Minimal request [`Parts`] carrying only `headers`, for a handler called without the
1294/// request it serves. Such parts have no extensions, so an extractor that reads the peer
1295/// address (`ConnectInfo`) cannot see it.
1296fn parts_from_headers(headers: &HeaderMap) -> Result<Parts, RuntimeError> {
1297    let mut builder = axum::http::Request::builder();
1298    for (name, value) in headers {
1299        builder = builder.header(name, value);
1300    }
1301    Ok(builder
1302        .body(())
1303        .map_err(|e| {
1304            (StatusCode::INTERNAL_SERVER_ERROR, format!("failed to build request parts: {e}"))
1305        })?
1306        .into_parts()
1307        .0)
1308}
1309
1310/// Extract [`RequestContext`] from the configured extractor, if present.
1311///
1312/// The extractor sees the request's own parts — its headers and its extensions, such as the
1313/// peer address a server records with `ConnectInfo` — as the auth middleware does on every
1314/// other route. Returns `None` when no extractor is configured (fall-through to existing
1315/// behavior).
1316async fn extract_request_context(
1317    extractor: Option<&dyn RequestContextExtractor>,
1318    parts: &Parts,
1319) -> Result<Option<RequestContext>, RuntimeError> {
1320    let Some(extractor) = extractor else {
1321        return Ok(None);
1322    };
1323
1324    match extractor.extract(parts).await {
1325        Ok(ctx) => Ok(Some(ctx)),
1326        Err(RequestContextError::MissingAuth) => {
1327            Err((StatusCode::UNAUTHORIZED, "missing authorization".to_string()))
1328        }
1329        Err(RequestContextError::InvalidToken(msg)) => {
1330            Err((StatusCode::UNAUTHORIZED, format!("invalid token: {msg}")))
1331        }
1332        Err(RequestContextError::ExtractionFailed(msg)) => {
1333            Err((StatusCode::INTERNAL_SERVER_ERROR, format!("auth extraction failed: {msg}")))
1334        }
1335    }
1336}
1337
1338fn bridge_params_with_identity(
1339    app_name: &str,
1340    user_id: &str,
1341    session_id: &str,
1342    params: Option<Value>,
1343) -> Value {
1344    let mut object = params.and_then(|value| value.as_object().cloned()).unwrap_or_default();
1345    object.insert("appName".to_string(), Value::String(app_name.to_string()));
1346    object.insert("userId".to_string(), Value::String(user_id.to_string()));
1347    object.insert("sessionId".to_string(), Value::String(session_id.to_string()));
1348    Value::Object(object)
1349}
1350
1351fn deserialize_bridge_params<T: for<'de> Deserialize<'de>>(
1352    app_name: &str,
1353    user_id: &str,
1354    session_id: &str,
1355    params: Option<Value>,
1356) -> Result<T, RuntimeError> {
1357    serde_json::from_value(bridge_params_with_identity(app_name, user_id, session_id, params))
1358        .map_err(|error| {
1359            (StatusCode::BAD_REQUEST, format!("invalid protocol-native bridge payload: {}", error))
1360        })
1361}
1362
1363fn maybe_mark_mcp_ui_initialized(
1364    app_name: &str,
1365    user_id: &str,
1366    session_id: &str,
1367    initialized_notification: Option<&Value>,
1368) -> Result<(), RuntimeError> {
1369    let Some(value) = initialized_notification else {
1370        return Ok(());
1371    };
1372    let method = value
1373        .as_object()
1374        .and_then(|object| object.get("method"))
1375        .and_then(|value| value.as_str())
1376        .unwrap_or_default();
1377    if method == "ui/notifications/initialized" {
1378        mark_mcp_ui_initialized(app_name, user_id, session_id)?;
1379    }
1380    Ok(())
1381}
1382
1383fn apply_mcp_apps_runtime_envelope(
1384    app_name: &str,
1385    user_id: &str,
1386    session_id: &str,
1387    envelope: McpAppsRuntimeEnvelope,
1388) -> Result<(), RuntimeError> {
1389    match envelope.method.as_str() {
1390        "ui/initialize" => {
1391            let params = deserialize_bridge_params::<McpUiInitializeParams>(
1392                app_name,
1393                user_id,
1394                session_id,
1395                envelope.params,
1396            )?;
1397            initialize_mcp_ui_bridge(params)?;
1398            Ok(())
1399        }
1400        "ui/message" => {
1401            let params = deserialize_bridge_params::<McpUiMessageParams>(
1402                app_name,
1403                user_id,
1404                session_id,
1405                envelope.params,
1406            )?;
1407            message_mcp_ui_bridge(params)?;
1408            Ok(())
1409        }
1410        "ui/update-model-context" => {
1411            let params = deserialize_bridge_params::<McpUiUpdateModelContextParams>(
1412                app_name,
1413                user_id,
1414                session_id,
1415                envelope.params,
1416            )?;
1417            update_mcp_ui_bridge_model_context(params)?;
1418            Ok(())
1419        }
1420        "ui/notifications/initialized" => {
1421            mark_mcp_ui_initialized(app_name, user_id, session_id)?;
1422            Ok(())
1423        }
1424        method => Err((
1425            StatusCode::BAD_REQUEST,
1426            format!("unsupported MCP Apps runtime bridge method '{}'", method),
1427        )),
1428    }
1429}
1430
1431#[derive(Default)]
1432struct AgUiMessages {
1433    text: Option<String>,
1434    reasoning: Option<String>,
1435}
1436
1437#[derive(Default)]
1438struct AgUiStream {
1439    deltas: adk_core::EventTextDeltas,
1440    messages: HashMap<(String, String), AgUiMessages>,
1441    /// Calls the run held for approval, one per fingerprint, in the order held.
1442    held: Vec<HeldCall>,
1443    /// What the host adds after each event (spec 3.3 §6.1 `genui`).
1444    extension: Option<Arc<dyn AgUiExtension>>,
1445    /// The client named AG-UI 1.0.
1446    v1: bool,
1447    /// The thread's state as the run left it: the input's, with every delta applied.
1448    state: Map<String, Value>,
1449    /// The thread's messages as the run left them: the input's, then what the run said and
1450    /// the calls it made, for the snapshot an interrupting `RUN_FINISHED` follows.
1451    transcript: Vec<Value>,
1452    /// A `RUN_ERROR` was sent: under 1.0 nothing follows it.
1453    errored: bool,
1454}
1455
1456/// Whether a client's `protocolVersion` names AG-UI 1.0 or later.
1457fn speaks_ag_ui_1(input: Option<&AgUiRunInput>) -> bool {
1458    input
1459        .and_then(|input| input.protocol_version.as_deref())
1460        .and_then(|version| version.trim().trim_start_matches('v').split('.').next())
1461        .and_then(|major| major.parse::<u32>().ok())
1462        .is_some_and(|major| major >= 1)
1463}
1464
1465/// `payload` in AG-UI 1.0's strict shape: no `null` fields, a run error without the thread
1466/// and run (its stream names them), a tool result without the tool's name, reasoning in the
1467/// `reasoning` role, and every tool call marked as executed on the server.
1468fn conform_ag_ui_1(payload: &mut Value) {
1469    let Some(object) = payload.as_object_mut() else {
1470        return;
1471    };
1472    object.retain(|_, value| !value.is_null());
1473    match object.get("type").and_then(Value::as_str).unwrap_or_default() {
1474        "RUN_ERROR" => {
1475            object.remove("threadId");
1476            object.remove("runId");
1477        }
1478        "TOOL_CALL_RESULT" => {
1479            object.remove("toolCallName");
1480        }
1481        "REASONING_MESSAGE_START" | "REASONING_MESSAGE_CHUNK" => {
1482            object.insert("role".into(), Value::String("reasoning".into()));
1483        }
1484        "TOOL_CALL_START" => {
1485            let metadata = object.entry("metadata").or_insert_with(|| json!({}));
1486            if let Some(metadata) = metadata.as_object_mut() {
1487                metadata.insert("ag-ui:tool-execution".into(), Value::String("server".into()));
1488            }
1489        }
1490        _ => {}
1491    }
1492}
1493
1494impl AgUiStream {
1495    /// Keeps what the snapshots need from one event the stream sends.
1496    fn observe(&mut self, payload: &Value) {
1497        let text =
1498            |key: &str| payload.get(key).and_then(Value::as_str).unwrap_or_default().to_string();
1499        match payload.get("type").and_then(Value::as_str).unwrap_or_default() {
1500            "TEXT_MESSAGE_START" | "TEXT_MESSAGE_CONTENT" | "TEXT_MESSAGE_CHUNK" => {
1501                let id = text("messageId");
1502                if id.is_empty() {
1503                    return;
1504                }
1505                let index =
1506                    match self.transcript.iter().position(|message| message["id"] == id.as_str()) {
1507                        Some(index) => index,
1508                        None => {
1509                            let role =
1510                                payload.get("role").and_then(Value::as_str).unwrap_or("assistant");
1511                            self.transcript.push(json!({ "id": id, "role": role, "content": "" }));
1512                            self.transcript.len() - 1
1513                        }
1514                    };
1515                if let Some(delta) = payload.get("delta").and_then(Value::as_str) {
1516                    let content =
1517                        self.transcript[index]["content"].as_str().unwrap_or_default().to_string();
1518                    self.transcript[index]["content"] = Value::String(content + delta);
1519                }
1520            }
1521            "TOOL_CALL_START" | "TOOL_CALL_ARGS" | "TOOL_CALL_CHUNK" => {
1522                let id = text("toolCallId");
1523                if id.is_empty() {
1524                    return;
1525                }
1526                let found = self.transcript.iter().enumerate().find_map(|(m, message)| {
1527                    message["toolCalls"]
1528                        .as_array()?
1529                        .iter()
1530                        .position(|call| call["id"] == id.as_str())
1531                        .map(|c| (m, c))
1532                });
1533                let (m, c) = match found {
1534                    Some(found) => found,
1535                    None => {
1536                        let parent = payload
1537                            .get("parentMessageId")
1538                            .and_then(Value::as_str)
1539                            .map(str::to_string)
1540                            .unwrap_or_else(|| format!("msg-{id}"));
1541                        let m = match self
1542                            .transcript
1543                            .iter()
1544                            .position(|message| message["id"] == parent.as_str())
1545                        {
1546                            Some(m) => m,
1547                            None => {
1548                                self.transcript.push(json!({ "id": parent, "role": "assistant" }));
1549                                self.transcript.len() - 1
1550                            }
1551                        };
1552                        let calls = self.transcript[m]
1553                            .as_object_mut()
1554                            .map(|message| message.entry("toolCalls").or_insert_with(|| json!([])));
1555                        let Some(Value::Array(calls)) = calls else { return };
1556                        calls.push(json!({
1557                            "id": id,
1558                            "type": "function",
1559                            "function": { "name": text("toolCallName"), "arguments": "" },
1560                        }));
1561                        (m, calls.len() - 1)
1562                    }
1563                };
1564                if let Some(delta) = payload.get("delta").and_then(Value::as_str) {
1565                    let call = &mut self.transcript[m]["toolCalls"][c]["function"];
1566                    let arguments = call["arguments"].as_str().unwrap_or_default().to_string();
1567                    call["arguments"] = Value::String(arguments + delta);
1568                }
1569            }
1570            "TOOL_CALL_RESULT" => {
1571                self.transcript.push(json!({
1572                    "id": text("messageId"),
1573                    "role": "tool",
1574                    "toolCallId": text("toolCallId"),
1575                    "content": payload.get("content").cloned().unwrap_or(Value::String(String::new())),
1576                }));
1577            }
1578            "STATE_DELTA" => {
1579                for op in payload.get("delta").and_then(Value::as_array).into_iter().flatten() {
1580                    let path = op.get("path").and_then(Value::as_str).unwrap_or_default();
1581                    let key = path.trim_start_matches('/').replace("~1", "/").replace("~0", "~");
1582                    if key.is_empty() || key.contains('/') {
1583                        continue;
1584                    }
1585                    match op.get("op").and_then(Value::as_str) {
1586                        Some("remove") => {
1587                            self.state.remove(&key);
1588                        }
1589                        Some(_) => {
1590                            self.state.insert(key, op.get("value").cloned().unwrap_or(Value::Null));
1591                        }
1592                        None => {}
1593                    }
1594                }
1595            }
1596            "RUN_ERROR" => self.errored = true,
1597            _ => {}
1598        }
1599    }
1600
1601    /// The events of one translated event, kept for the snapshots and, under 1.0, in its
1602    /// strict shape.
1603    fn finish(&mut self, payloads: Vec<Value>) -> Vec<Value> {
1604        payloads
1605            .into_iter()
1606            .map(|mut payload| {
1607                self.observe(&payload);
1608                if self.v1 {
1609                    conform_ag_ui_1(&mut payload);
1610                }
1611                payload
1612            })
1613            .collect()
1614    }
1615}
1616
1617impl AgUiStream {
1618    fn translate(&mut self, event: &adk_core::Event, thread_id: &str, run_id: &str) -> Vec<Value> {
1619        if let Some(request) = &event.actions.tool_confirmation {
1620            let fingerprint = request.fingerprint();
1621            self.held.retain(|held| held.request.fingerprint() != fingerprint);
1622            self.held.push(HeldCall { request: request.clone(), agent: event.author.clone() });
1623        }
1624        let key = (event.invocation_id.clone(), event.id.clone());
1625        let mut open = self.messages.remove(&key).unwrap_or_default();
1626        let mut delta = self.deltas.push(event);
1627        if !event.llm_response.partial {
1628            let parts = delta.content().map(|content| content.parts.as_slice()).unwrap_or(&[]);
1629            let mut endings = Vec::new();
1630            if open.text.is_some()
1631                && !parts.iter().any(|part| matches!(part, adk_core::Part::Text { .. }))
1632            {
1633                endings.push(adk_core::Part::Text { text: String::new() });
1634            }
1635            if open.reasoning.is_some()
1636                && !parts.iter().any(|part| matches!(part, adk_core::Part::Thinking { .. }))
1637            {
1638                endings.push(adk_core::Part::Thinking { thinking: String::new(), signature: None });
1639            }
1640            if !endings.is_empty() {
1641                delta
1642                    .to_mut()
1643                    .llm_response
1644                    .content
1645                    .get_or_insert_with(|| adk_core::Content::new("model"))
1646                    .parts
1647                    .extend(endings);
1648            }
1649        }
1650        let mut translated = translate_ag_ui_event(&delta, thread_id, run_id, &open);
1651        if let Some(extension) = &self.extension
1652            && !event.llm_response.partial
1653        {
1654            translated.extend(extension.events_for(event));
1655        }
1656        if event.llm_response.partial {
1657            for item in &translated {
1658                let id = item.get("messageId").and_then(Value::as_str).map(str::to_owned);
1659                match item.get("type").and_then(Value::as_str) {
1660                    Some("TEXT_MESSAGE_CHUNK") => open.text = id,
1661                    Some("REASONING_MESSAGE_CHUNK") => open.reasoning = id,
1662                    _ => {}
1663                }
1664            }
1665            if open.text.is_some() || open.reasoning.is_some() {
1666                self.messages.insert(key, open);
1667            }
1668        }
1669        translated
1670    }
1671}
1672
1673fn build_runtime_sse_stream<S>(
1674    mut event_stream: S,
1675    profile: UiProfile,
1676    transport: UiTransportMode,
1677    session_id: String,
1678    ag_ui_input: Option<AgUiRunInput>,
1679    decisions: AgUiDecisions,
1680    controller: &RuntimeController,
1681) -> std::pin::Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>>
1682where
1683    S: Stream<Item = adk_core::Result<adk_core::Event>> + Send + 'static + Unpin,
1684{
1685    let extension = controller.ag_ui_extension.clone();
1686    let expose_details = controller.config.security.expose_error_details;
1687    let decision_updates: Vec<Value> =
1688        decisions.updates.iter().cloned().map(decision_event).collect();
1689    let selected_thread_id =
1690        ag_ui_input.as_ref().and_then(|input| input.thread_id.clone()).unwrap_or(session_id);
1691    let selected_run_input = ag_ui_input.clone();
1692    let selected_parent_run_id = ag_ui_input.as_ref().and_then(|input| input.parent_run_id.clone());
1693    let selected_initial_state = ag_ui_input.as_ref().and_then(|input| input.state.clone());
1694    let selected_messages_snapshot =
1695        ag_ui_input.as_ref().and_then(messages_snapshot_from_ag_ui_input);
1696    let selected_activity_events =
1697        ag_ui_input.as_ref().map(activity_events_from_ag_ui_input).unwrap_or_default();
1698
1699    Box::pin(async_stream::stream! {
1700        let native_ag_ui = profile == UiProfile::AgUi && transport == UiTransportMode::ProtocolNative;
1701        let mut started = false;
1702        let v1 = speaks_ag_ui_1(ag_ui_input.as_ref());
1703        let mut ag_ui_stream = AgUiStream {
1704            extension,
1705            v1,
1706            state: selected_initial_state
1707                .as_ref()
1708                .and_then(Value::as_object)
1709                .cloned()
1710                .unwrap_or_default(),
1711            transcript: selected_messages_snapshot
1712                .as_ref()
1713                .and_then(Value::as_array)
1714                .cloned()
1715                .unwrap_or_default(),
1716            ..AgUiStream::default()
1717        };
1718        let mut active_run_id = ag_ui_input.as_ref().and_then(|input| input.run_id.clone());
1719
1720        while let Some(item) = event_stream.next().await {
1721            match item {
1722                Ok(event) => {
1723                    if native_ag_ui {
1724                        let run_id = active_run_id
1725                            .get_or_insert_with(|| event.invocation_id.clone())
1726                            .clone();
1727                        if !started {
1728                            let mut started_event = json!({
1729                                "type": "RUN_STARTED",
1730                                "threadId": selected_thread_id,
1731                                "runId": run_id,
1732                            });
1733                            if let Some(parent_run_id) = selected_parent_run_id.clone()
1734                                && let Some(object) = started_event.as_object_mut()
1735                            {
1736                                object.insert("parentRunId".to_string(), Value::String(parent_run_id));
1737                            }
1738                            if let Some(run_input) = selected_run_input.clone()
1739                                && let Ok(value) = serde_json::to_value(run_input)
1740                                && let Some(object) = started_event.as_object_mut()
1741                            {
1742                                object.insert("input".to_string(), value);
1743                            }
1744                            // A 1.0 client hears back the version this run speaks.
1745                            if v1 {
1746                                started_event["protocolVersion"] = json!("1.0");
1747                            }
1748                            yield Ok(Event::default().data(started_event.to_string()));
1749
1750                            if let Some(snapshot) = selected_initial_state.clone() {
1751                                yield Ok(Event::default().data(json!({
1752                                    "type": "STATE_SNAPSHOT",
1753                                    "snapshot": snapshot,
1754                                }).to_string()));
1755                            }
1756                            if let Some(messages) = selected_messages_snapshot.clone() {
1757                                yield Ok(Event::default().data(json!({
1758                                    "type": "MESSAGES_SNAPSHOT",
1759                                    "messages": messages,
1760                                }).to_string()));
1761                            }
1762                            for activity_event in selected_activity_events.clone() {
1763                                yield Ok(Event::default().data(activity_event.to_string()));
1764                            }
1765                            for update in &decision_updates {
1766                                yield Ok(Event::default().data(update.to_string()));
1767                            }
1768                            started = true;
1769                        }
1770
1771                        let translated = ag_ui_stream.translate(&event, &selected_thread_id, &run_id);
1772                        for payload in ag_ui_stream.finish(translated) {
1773                            yield Ok(Event::default().data(payload.to_string()));
1774                        }
1775                        // Under 1.0 a run error ends the run: no RUN_FINISHED follows it.
1776                        if ag_ui_stream.v1 && ag_ui_stream.errored {
1777                            return;
1778                        }
1779                    } else if let Some(payload) = serialize_runtime_event(&event, profile) {
1780                        yield Ok(Event::default().data(payload));
1781                    }
1782                }
1783                Err(error) => {
1784                    if native_ag_ui {
1785                        let run_id =
1786                            active_run_id.unwrap_or_else(|| format!("run-{}", Uuid::new_v4()));
1787                        if !started {
1788                            yield Ok(Event::default().data(json!({
1789                                "type": "RUN_STARTED",
1790                                "threadId": selected_thread_id,
1791                                "runId": run_id,
1792                            }).to_string()));
1793                            for update in &decision_updates {
1794                                yield Ok(Event::default().data(update.to_string()));
1795                            }
1796                        }
1797                        let mut failed = json!({
1798                            "type": "RUN_ERROR",
1799                            "threadId": selected_thread_id,
1800                            "runId": run_id,
1801                            "message": error_details::display(&error, expose_details),
1802                            "code": error.code,
1803                        });
1804                        if ag_ui_stream.v1 {
1805                            conform_ag_ui_1(&mut failed);
1806                        }
1807                        yield Ok(Event::default().data(failed.to_string()));
1808                    } else if let Some(payload) =
1809                        serialize_runtime_error(&error, profile, expose_details)
1810                    {
1811                        yield Ok(Event::default().data(payload));
1812                    }
1813                    return;
1814                }
1815            }
1816        }
1817
1818        if native_ag_ui {
1819            let run_id = active_run_id.unwrap_or_else(|| format!("run-{}", Uuid::new_v4()));
1820            if !started {
1821                yield Ok(Event::default().data(json!({
1822                    "type": "RUN_STARTED",
1823                    "threadId": selected_thread_id,
1824                    "runId": run_id,
1825                }).to_string()));
1826                for update in &decision_updates {
1827                    yield Ok(Event::default().data(update.to_string()));
1828                }
1829            }
1830            let mut finished = json!({
1831                "type": "RUN_FINISHED",
1832                "threadId": selected_thread_id,
1833                "runId": run_id,
1834            });
1835            // A run that stopped on held calls is not a success (spec 3.3 §10 S2).
1836            if !ag_ui_stream.held.is_empty() {
1837                match decisions.interrupts(&ag_ui_stream.held).await {
1838                    Ok(mut interrupts) => {
1839                        if ag_ui_stream.v1 {
1840                            // AG-UI 1.0: the thread as it stands, then the interrupts; every
1841                            // held call runs on the server once answered.
1842                            yield Ok(Event::default().data(json!({
1843                                "type": "STATE_SNAPSHOT",
1844                                "snapshot": Value::Object(ag_ui_stream.state.clone()),
1845                            }).to_string()));
1846                            yield Ok(Event::default().data(json!({
1847                                "type": "MESSAGES_SNAPSHOT",
1848                                "messages": ag_ui_stream.transcript.clone(),
1849                            }).to_string()));
1850                            for interrupt in &mut interrupts {
1851                                if let Some(object) = interrupt.as_object_mut() {
1852                                    let metadata = object.entry("metadata").or_insert_with(|| json!({}));
1853                                    if let Some(metadata) = metadata.as_object_mut() {
1854                                        metadata.insert("ag-ui:tool-execution".into(), json!("server"));
1855                                    }
1856                                }
1857                            }
1858                        }
1859                        finished["outcome"] = json!({ "type": "interrupt", "interrupts": interrupts });
1860                    }
1861                    // An interrupt without its inbox entry would say the call cannot be
1862                    // decided here, so the failure is reported instead.
1863                    Err(error) => {
1864                        let mut failed = json!({
1865                            "type": "RUN_ERROR",
1866                            "threadId": selected_thread_id,
1867                            "runId": run_id,
1868                            "message": "This run is waiting for a decision that could not be \
1869                                        loaded; answer it in your decisions inbox",
1870                            "code": error.code,
1871                        });
1872                        if ag_ui_stream.v1 {
1873                            conform_ag_ui_1(&mut failed);
1874                        }
1875                        yield Ok(Event::default().data(failed.to_string()));
1876                        return;
1877                    }
1878                }
1879            } else if ag_ui_stream.v1 {
1880                finished["outcome"] = json!({ "type": "success" });
1881            }
1882            yield Ok(Event::default().data(finished.to_string()));
1883        }
1884    })
1885}
1886
1887/// The stream of an AG-UI resume refused before its run started: `RUN_STARTED`, the
1888/// decision updates, and a `RUN_ERROR` naming the refusal (spec 3.3 §10 S2, S-I2).
1889fn refused_resume_stream(
1890    thread_id: String,
1891    run_id: String,
1892    updates: Vec<Value>,
1893    code: &'static str,
1894    message: String,
1895    v1: bool,
1896) -> std::pin::Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>> {
1897    let mut started = json!({ "type": "RUN_STARTED", "threadId": thread_id, "runId": run_id });
1898    if v1 {
1899        started["protocolVersion"] = json!("1.0");
1900    }
1901    let mut events = vec![started];
1902    events.extend(updates.into_iter().map(decision_event));
1903    let mut failed = json!({
1904        "type": "RUN_ERROR",
1905        "threadId": thread_id,
1906        "runId": run_id,
1907        "message": message,
1908        "code": code,
1909    });
1910    if v1 {
1911        conform_ag_ui_1(&mut failed);
1912    }
1913    events.push(failed);
1914    Box::pin(futures::stream::iter(
1915        events.into_iter().map(|event| Ok(Event::default().data(event.to_string()))),
1916    ))
1917}
1918
1919/// What a request's AG-UI stream needs for decisions: the approval service only for
1920/// protocol-native AG-UI runs, whose held calls become interrupts (spec 3.3 §10 S2).
1921fn ag_ui_decisions(
1922    controller: &RuntimeController,
1923    profile: UiProfile,
1924    transport: UiTransportMode,
1925    scope: adk_core::ApprovalScope,
1926    caller: Option<&RequestContext>,
1927) -> AgUiDecisions {
1928    if profile != UiProfile::AgUi || transport != UiTransportMode::ProtocolNative {
1929        return AgUiDecisions::default();
1930    }
1931    AgUiDecisions {
1932        service: controller.approval_service.clone(),
1933        // The caller the extractor authenticated is the session's owner: the session was
1934        // looked up under its user ID.
1935        caller: caller.map(|caller| AgUiCaller {
1936            approver: adk_core::principal::SubjectRef::human(scope.user_id.clone()),
1937            groups: caller.scopes.clone(),
1938        }),
1939        scope: Some(scope),
1940        updates: Vec::new(),
1941        audit: controller.config.governance.audit(),
1942    }
1943}
1944
1945pub async fn run_sse(
1946    State(controller): State<RuntimeController>,
1947    path: Path<(String, String, String)>,
1948    headers: HeaderMap,
1949    Json(req): Json<RunRequest>,
1950) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, RuntimeError> {
1951    run_sse_for_request(State(controller), path, parts_from_headers(&headers)?, Json(req)).await
1952}
1953
1954/// `POST /run/{app_name}/{user_id}/{session_id}` as the server routes it: the request
1955/// context extractor sees the whole request, including its peer address, rather than only
1956/// its headers.
1957pub(crate) async fn run_sse_for_request(
1958    State(controller): State<RuntimeController>,
1959    Path((app_name, user_id, session_id)): Path<(String, String, String)>,
1960    parts: Parts,
1961    Json(req): Json<RunRequest>,
1962) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, RuntimeError> {
1963    let expose_details = controller.config.security.expose_error_details;
1964    let problem = move |error: adk_core::AdkError| adk_err_to_runtime(error, expose_details);
1965    let headers = parts.headers.clone();
1966    let ui_profile = resolve_ui_profile(&headers, infer_run_request_protocol(&req))?;
1967    let transport = resolve_ui_transport(&headers, req.ui_transport.as_deref())?;
1968    validate_transport_support(ui_profile, transport)?;
1969    let span = tracing::info_span!("run_sse", session_id = %session_id, app_name = %app_name, user_id = %user_id);
1970
1971    async move {
1972        log_profile_deprecation(ui_profile);
1973        info!(
1974            ui_protocol = %ui_profile.as_str(),
1975            ui_transport = ?transport,
1976            "resolved ui protocol profile for runtime request"
1977        );
1978
1979        // Extract request context from auth middleware bridge if configured.
1980        // This returns Err (401/500) when the extractor is present but auth
1981        // fails, ensuring authorization checks are never bypassed.
1982        let request_context =
1983            extract_request_context(controller.config.request_context_extractor.as_deref(), &parts)
1984                .await?;
1985
1986        // Explicit authenticated user override: when an auth extractor is
1987        // configured and succeeds, the authenticated user_id takes precedence
1988        // over the path parameter. This prevents callers from impersonating
1989        // other users via the URL while keeping the path param as a fallback
1990        // for unauthenticated deployments (no extractor configured).
1991        let effective_user_id = request_context.as_ref().map_or(user_id, |rc| rc.user_id.clone());
1992        let decisions = ag_ui_decisions(
1993            &controller,
1994            ui_profile,
1995            transport,
1996            adk_core::ApprovalScope::new(&app_name, &effective_user_id, &session_id),
1997            request_context.as_ref(),
1998        );
1999
2000        // Validate session exists
2001        controller
2002            .config
2003            .session_service
2004            .get(adk_session::GetRequest {
2005                app_name: app_name.clone(),
2006                user_id: effective_user_id.clone(),
2007                session_id: session_id.clone(),
2008                num_recent_events: None,
2009                after: None,
2010            })
2011            .await
2012            .map_err(problem)?;
2013
2014        // Load agent
2015        let agent = controller.config.agent_loader.load_agent(&app_name).await.map_err(problem)?;
2016
2017        // Create runner
2018        let mut runner_builder = adk_runner::Runner::builder()
2019            .app_name(app_name.clone())
2020            .agent(agent)
2021            .session_service(controller.config.session_service.clone())
2022            .governance(controller.config.governance.clone())
2023            .session_activity(controller.config.session_activity.clone());
2024        if let Some(ref artifact_service) = controller.config.artifact_service {
2025            runner_builder = runner_builder.artifact_service(artifact_service.clone());
2026        }
2027        if let Some(ref memory_service) = controller.config.memory_service {
2028            runner_builder = runner_builder.memory_service(memory_service.clone());
2029        }
2030        if let Some(ref compaction_config) = controller.config.compaction_config {
2031            runner_builder = runner_builder.compaction_config(compaction_config.clone());
2032        }
2033        if let Some(ref context_cache_config) = controller.config.context_cache_config {
2034            runner_builder = runner_builder.context_cache_config(context_cache_config.clone());
2035        }
2036        if let Some(ref cache_capable) = controller.config.cache_capable {
2037            runner_builder = runner_builder.cache_capable(cache_capable.clone());
2038        }
2039        if let Some(request_context) = request_context {
2040            runner_builder = runner_builder.request_context(request_context);
2041        }
2042        if let Some(service) = decisions.service.clone() {
2043            runner_builder = runner_builder
2044                .run_config(adk_core::RunConfig::builder().approval_service(service).build());
2045        }
2046        let runner = runner_builder.build().map_err(problem)?;
2047
2048        // Build content with attachments
2049        let content = build_content_with_attachments(&req.new_message, &req.attachments)?;
2050
2051        // Log attachment info
2052        if !req.attachments.is_empty() {
2053            info!(attachment_count = req.attachments.len(), "processing request with attachments");
2054        }
2055
2056        // Run agent
2057        let typed_user_id = UserId::new(effective_user_id).map_err(|err| problem(err.into()))?;
2058        let typed_session_id =
2059            SessionId::new(session_id.clone()).map_err(|err| problem(err.into()))?;
2060        let event_stream =
2061            runner.run(typed_user_id, typed_session_id, content).await.map_err(problem)?;
2062
2063        // Convert to SSE stream
2064        let sse_stream = build_runtime_sse_stream(
2065            event_stream,
2066            ui_profile,
2067            transport,
2068            session_id.clone(),
2069            None,
2070            decisions,
2071            &controller,
2072        );
2073
2074        Ok(Sse::new(sse_stream).keep_alive(KeepAlive::default()))
2075    }
2076    .instrument(span)
2077    .await
2078}
2079
2080/// POST /run_sse - adk-go compatible endpoint
2081/// Accepts JSON body with appName, userId, sessionId, newMessage
2082pub async fn run_sse_compat(
2083    State(controller): State<RuntimeController>,
2084    headers: HeaderMap,
2085    Json(req): Json<RunSseRequest>,
2086) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, RuntimeError> {
2087    run_sse_compat_for_request(State(controller), parts_from_headers(&headers)?, Json(req)).await
2088}
2089
2090/// `POST /run_sse` as the server routes it: the request context extractor sees the whole
2091/// request, including its peer address, rather than only its headers.
2092pub(crate) async fn run_sse_compat_for_request(
2093    State(controller): State<RuntimeController>,
2094    parts: Parts,
2095    Json(req): Json<RunSseRequest>,
2096) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, RuntimeError> {
2097    let expose_details = controller.config.security.expose_error_details;
2098    let problem = move |error: adk_core::AdkError| adk_err_to_runtime(error, expose_details);
2099    let headers = parts.headers.clone();
2100    let ui_profile = resolve_ui_profile(&headers, infer_sse_request_protocol(&req))?;
2101    let transport = resolve_ui_transport(&headers, req.ui_transport.as_deref())?;
2102    validate_transport_support(ui_profile, transport)?;
2103    let app_name = req.app_name.clone();
2104    let user_id = req.user_id.clone();
2105    let session_id = req.session_id.clone();
2106    let mut ag_ui_input = ag_ui_input_from_request(&req);
2107    // The host's extension decides which activities a client sent back are kept: a dropped
2108    // one reaches neither the stream nor the session (spec 3.3 §6.1 `genui`).
2109    let extension = controller.ag_ui_extension.clone();
2110    if let (Some(extension), Some(input)) = (&extension, ag_ui_input.as_mut()) {
2111        input.messages.retain(|message| {
2112            message.role.as_deref() != Some("activity") || extension.keeps_activity(message)
2113        });
2114    }
2115    let mcp_apps_request = mcp_apps_request_from_request(&req);
2116    let mcp_apps_initialize = mcp_apps_initialize_from_request(&req);
2117
2118    info!(
2119        app_name = %app_name,
2120        user_id = %user_id,
2121        session_id = %session_id,
2122        ui_protocol = %ui_profile.as_str(),
2123        ui_transport = ?transport,
2124        "POST /run_sse request received"
2125    );
2126    log_profile_deprecation(ui_profile);
2127
2128    // Extract request context from auth middleware bridge if configured.
2129    // This returns Err (401/500) when the extractor is present but auth
2130    // fails, ensuring authorization checks are never bypassed.
2131    let request_context =
2132        extract_request_context(controller.config.request_context_extractor.as_deref(), &parts)
2133            .await?;
2134
2135    // Explicit authenticated user override: when an auth extractor is
2136    // configured and succeeds, the authenticated user_id takes precedence
2137    // over the request body value. This prevents callers from impersonating
2138    // other users via the JSON payload while keeping the body param as a
2139    // fallback for unauthenticated deployments (no extractor configured).
2140    let effective_user_id = request_context.as_ref().map_or(user_id, |rc| rc.user_id.clone());
2141    let mut decisions = ag_ui_decisions(
2142        &controller,
2143        ui_profile,
2144        transport,
2145        adk_core::ApprovalScope::new(&app_name, &effective_user_id, &session_id),
2146        request_context.as_ref(),
2147    );
2148
2149    // Answers to the previous run's interrupts are checked now and recorded only once the run
2150    // is about to start, so a request that fails decides nothing and the run resumes the calls
2151    // they allow (spec 3.3 §10 S2).
2152    let resume = ag_ui_input.as_ref().and_then(|input| input.resume.as_ref());
2153    let resuming = resume.is_some_and(|resume| !resume.entries().is_empty());
2154    let mut resume_plan = None;
2155    let mut resume_in_progress = None;
2156    if let Some(resume) = resume.filter(|_| resuming) {
2157        let Some(service) = decisions.service.clone() else {
2158            return Err((
2159                StatusCode::BAD_REQUEST,
2160                "an AG-UI resume needs the ag_ui profile with the protocol_native transport and \
2161                 a server with an approval service (ServerBuilder::with_approval_service)"
2162                    .to_string(),
2163            ));
2164        };
2165        let Some(caller) = request_context.as_ref() else {
2166            return Err((
2167                StatusCode::UNAUTHORIZED,
2168                "an AG-UI resume decides approvals, which need an authenticated caller; \
2169                 configure a RequestContextExtractor"
2170                    .to_string(),
2171            ));
2172        };
2173        let scope = adk_core::ApprovalScope::new(&app_name, &effective_user_id, &session_id);
2174        let refused = |updates, code, message| {
2175            let input = ag_ui_input.as_ref();
2176            let thread_id = input
2177                .and_then(|input| input.thread_id.clone())
2178                .unwrap_or_else(|| session_id.clone());
2179            let run_id = input
2180                .and_then(|input| input.run_id.clone())
2181                .unwrap_or_else(|| format!("run-{}", Uuid::new_v4()));
2182            let stream = refused_resume_stream(
2183                thread_id,
2184                run_id,
2185                updates,
2186                code,
2187                message,
2188                speaks_ag_ui_1(input),
2189            );
2190            Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
2191        };
2192        // One resume of a session at a time, until its run ends: a second one would start a
2193        // second run resuming the same held calls (spec 3.3 S-I2).
2194        let Some(in_progress) = controller.resumes.begin(&scope) else {
2195            return refused(
2196                Vec::new(),
2197                RESUME_IN_PROGRESS,
2198                "An earlier answer on this thread is still being applied; try again when its \
2199                 run finishes"
2200                    .to_string(),
2201            );
2202        };
2203        resume_in_progress = Some(in_progress);
2204        // AG-UI 1.0: a resume answers every interrupt still open on the thread, and names no
2205        // other.
2206        if speaks_ag_ui_1(ag_ui_input.as_ref()) {
2207            let open = match open_interrupt_ids(service.as_ref(), &scope).await {
2208                Ok(open) => open,
2209                Err(error) => return Err((StatusCode::INTERNAL_SERVER_ERROR, error.to_string())),
2210            };
2211            let answered: std::collections::BTreeSet<&str> =
2212                resume.entries().iter().map(|entry| entry.interrupt_id.as_str()).collect();
2213            let open_set: std::collections::BTreeSet<&str> =
2214                open.iter().map(String::as_str).collect();
2215            if answered != open_set {
2216                return refused(
2217                    Vec::new(),
2218                    INVALID_RESUME,
2219                    format!(
2220                        "A resume answers every open interrupt on this thread at once: {} open, {} answered",
2221                        open_set.len(),
2222                        answered.len()
2223                    ),
2224                );
2225            }
2226        }
2227        // The session's owner decides: the extractor authenticated the user it runs for.
2228        let approver = adk_core::principal::SubjectRef::human(effective_user_id.clone());
2229        match plan_resume(
2230            service.as_ref(),
2231            &scope,
2232            &approver,
2233            &caller.scopes,
2234            resume.entries(),
2235            decisions.audit.as_ref(),
2236        )
2237        .await
2238        .map_err(|reason| (StatusCode::BAD_REQUEST, reason))?
2239        {
2240            ResumeOutcome::Run(plan) => resume_plan = Some((service, plan)),
2241            ResumeOutcome::Refused { updates, code, message } => {
2242                return refused(updates, code, message);
2243            }
2244        }
2245    }
2246
2247    // AG-UI 1.0: new input waits until the thread's open interrupts are answered.
2248    if resume_plan.is_none()
2249        && speaks_ag_ui_1(ag_ui_input.as_ref())
2250        && let Some(service) = decisions.service.clone()
2251    {
2252        let scope = adk_core::ApprovalScope::new(&app_name, &effective_user_id, &session_id);
2253        let open = open_interrupt_ids(service.as_ref(), &scope)
2254            .await
2255            .map_err(|error| (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()))?;
2256        if !open.is_empty() {
2257            let input = ag_ui_input.as_ref();
2258            let thread_id = input
2259                .and_then(|input| input.thread_id.clone())
2260                .unwrap_or_else(|| session_id.clone());
2261            let run_id = input
2262                .and_then(|input| input.run_id.clone())
2263                .unwrap_or_else(|| format!("run-{}", Uuid::new_v4()));
2264            let stream = refused_resume_stream(
2265                thread_id,
2266                run_id,
2267                Vec::new(),
2268                INTERRUPTS_OPEN,
2269                format!(
2270                    "This thread waits for {} decision(s); resume with an answer for each first",
2271                    open.len()
2272                ),
2273                true,
2274            );
2275            return Ok(Sse::new(stream).keep_alive(KeepAlive::default()));
2276        }
2277    }
2278
2279    // An action in `forwardedProps` asks for a call a person decides (spec 3.3 §7.4 rule 5):
2280    // the host's extension checks it against the session, and the run's agent holds it.
2281    let native_ag_ui =
2282        ui_profile == UiProfile::AgUi && transport == UiTransportMode::ProtocolNative;
2283    let mut requested_call = None;
2284    // The agent that holds the call, loaded once for the run.
2285    let mut action_agent = None;
2286    if native_ag_ui
2287        && let Some(extension) = &extension
2288        && let Some(props) = ag_ui_input.as_ref().and_then(|input| input.forwarded_props.as_ref())
2289        && extension.action_in(props)
2290    {
2291        let Some(caller) = request_context.as_ref() else {
2292            return Err((
2293                StatusCode::UNAUTHORIZED,
2294                "an AG-UI action asks for a call a person decides, which needs an authenticated \
2295                 caller; configure a RequestContextExtractor"
2296                    .to_string(),
2297            ));
2298        };
2299        if resuming {
2300            return Err((
2301                StatusCode::BAD_REQUEST,
2302                "an AG-UI run carries either a resume or an action in forwardedProps, not both"
2303                    .to_string(),
2304            ));
2305        }
2306        let session = controller
2307            .config
2308            .session_service
2309            .get(adk_session::GetRequest {
2310                app_name: app_name.clone(),
2311                user_id: effective_user_id.clone(),
2312                session_id: session_id.clone(),
2313                num_recent_events: None,
2314                after: None,
2315            })
2316            .await
2317            .map_err(problem)?;
2318        let events = session.events().all();
2319        let requested_by = adk_core::principal::SubjectRef::human(caller.user_id.clone());
2320        let agent = controller.config.agent_loader.load_agent(&app_name).await.map_err(problem)?;
2321        requested_call = extension
2322            .requested_call(AgUiAction {
2323                app_name: &app_name,
2324                agent_name: agent.name(),
2325                user_id: &effective_user_id,
2326                session_id: &session_id,
2327                requested_by: &requested_by,
2328                forwarded_props: props,
2329                events: &events,
2330            })
2331            .await
2332            .map_err(problem)?;
2333        action_agent = Some(agent);
2334    }
2335    let submitting = requested_call.is_some();
2336
2337    // A resume carries the client's whole history, whose last user message this session
2338    // already answered, so it starts no new user turn unless one is sent as `newMessage`. An
2339    // action is not a new turn either: the person pressed a button.
2340    let content = match req.new_message.clone().or_else(|| {
2341        if resuming || submitting {
2342            None
2343        } else {
2344            ag_ui_input.as_ref().and_then(new_message_from_ag_ui_input)
2345        }
2346    }) {
2347        Some(resolved_new_message) => {
2348            // Log part info
2349            let text_parts: Vec<_> =
2350                resolved_new_message.parts.iter().filter(|p| p.text.is_some()).collect();
2351            let data_parts: Vec<_> =
2352                resolved_new_message.parts.iter().filter(|p| p.inline_data.is_some()).collect();
2353            if !data_parts.is_empty() {
2354                info!(
2355                    text_parts = text_parts.len(),
2356                    inline_data_parts = data_parts.len(),
2357                    "processing request with inline data"
2358                );
2359            }
2360            // Build content from message parts (includes both text and inline_data)
2361            build_content_from_parts(&resolved_new_message.parts)?
2362        }
2363        // A blank turn resumes the held calls that now have a decision, or holds the call a
2364        // person asked for.
2365        None if resuming || submitting => adk_core::Content::new("user").with_text(""),
2366        None => {
2367            return Err((
2368                StatusCode::BAD_REQUEST,
2369                "newMessage is required unless protocol-native ag_ui input supplies a user message"
2370                    .to_string(),
2371            ));
2372        }
2373    };
2374
2375    let merged_state_delta = merge_runtime_state_delta(
2376        body_state_delta(req.state_delta.as_ref())?,
2377        ag_ui_input.as_ref().map(ag_ui_state_delta).unwrap_or_default(),
2378    );
2379
2380    // The agent loads first, so an unknown app reports itself rather than a missing session.
2381    let agent = match action_agent {
2382        Some(agent) => agent,
2383        None => controller.config.agent_loader.load_agent(&app_name).await.map_err(problem)?,
2384    };
2385
2386    ensure_session(
2387        &controller.config.session_service,
2388        &app_name,
2389        &effective_user_id,
2390        &session_id,
2391        merged_state_delta.clone(),
2392        expose_details,
2393        missing_session_rule(ui_profile),
2394    )
2395    .await?;
2396
2397    if ui_profile == UiProfile::McpApps {
2398        if let Some(initialize) = mcp_apps_initialize {
2399            apply_mcp_apps_runtime_envelope(
2400                &app_name,
2401                &effective_user_id,
2402                &session_id,
2403                initialize,
2404            )?;
2405        }
2406        if let Some(request) = mcp_apps_request {
2407            apply_mcp_apps_runtime_envelope(&app_name, &effective_user_id, &session_id, request)?;
2408        }
2409        maybe_mark_mcp_ui_initialized(
2410            &app_name,
2411            &effective_user_id,
2412            &session_id,
2413            req.mcp_apps_initialized.as_ref(),
2414        )?;
2415    }
2416
2417    // Create runner with streaming config from request
2418    let streaming_mode =
2419        if req.streaming { adk_core::StreamingMode::SSE } else { adk_core::StreamingMode::None };
2420
2421    let mut run_config = adk_core::RunConfig::builder().streaming_mode(streaming_mode);
2422    if let Some(service) = decisions.service.clone() {
2423        run_config = run_config.approval_service(service);
2424    }
2425    if let Some(call) = requested_call {
2426        run_config = run_config.requested_call(call);
2427    }
2428    let mut runner_builder = adk_runner::Runner::builder()
2429        .app_name(app_name)
2430        .agent(agent)
2431        .session_service(controller.config.session_service.clone())
2432        .governance(controller.config.governance.clone())
2433        .session_activity(controller.config.session_activity.clone())
2434        .run_config(run_config.build());
2435    if let Some(ref artifact_service) = controller.config.artifact_service {
2436        runner_builder = runner_builder.artifact_service(artifact_service.clone());
2437    }
2438    if let Some(ref memory_service) = controller.config.memory_service {
2439        runner_builder = runner_builder.memory_service(memory_service.clone());
2440    }
2441    if let Some(ref compaction_config) = controller.config.compaction_config {
2442        runner_builder = runner_builder.compaction_config(compaction_config.clone());
2443    }
2444    if let Some(ref context_cache_config) = controller.config.context_cache_config {
2445        runner_builder = runner_builder.context_cache_config(context_cache_config.clone());
2446    }
2447    if let Some(ref cache_capable) = controller.config.cache_capable {
2448        runner_builder = runner_builder.cache_capable(cache_capable.clone());
2449    }
2450    if let Some(request_context) = request_context {
2451        runner_builder = runner_builder.request_context(request_context);
2452    }
2453    let runner = runner_builder.build().map_err(problem)?;
2454    // A frozen server records no answer: the run would not start.
2455    if resume_plan.is_some() {
2456        controller.config.governance.check().map_err(problem)?;
2457    }
2458
2459    // Run agent with full content (text + inline data)
2460    let typed_user_id = UserId::new(effective_user_id).map_err(|err| problem(err.into()))?;
2461    let typed_session_id = SessionId::new(session_id.clone()).map_err(|err| problem(err.into()))?;
2462    // `run` refuses a request context of another user before returning; the agent runs only
2463    // once the stream is read, after the answers are recorded below.
2464    let event_stream =
2465        runner.run(typed_user_id, typed_session_id, content).await.map_err(problem)?;
2466    if let Some((service, plan)) = resume_plan {
2467        decisions.updates = commit_resume(service.as_ref(), plan, decisions.audit.as_ref()).await;
2468    }
2469
2470    // Convert to SSE stream
2471    let sse_stream = build_runtime_sse_stream(
2472        event_stream,
2473        ui_profile,
2474        transport,
2475        session_id.clone(),
2476        ag_ui_input,
2477        decisions,
2478        &controller,
2479    );
2480    // The resume stays in progress until its run's stream ends or is dropped.
2481    let sse_stream: std::pin::Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>> =
2482        Box::pin(sse_stream.map(move |event| {
2483            let _resume = &resume_in_progress;
2484            event
2485        }));
2486
2487    Ok(Sse::new(sse_stream).keep_alive(KeepAlive::default()))
2488}
2489
2490/// POST /run - plain-JSON, non-streaming endpoint (Google ADK api_server parity)
2491///
2492/// Accepts the same JSON body as `POST /run_sse`, runs the agent to
2493/// completion, and returns every produced event as a JSON array instead of
2494/// an SSE stream. The `streaming` body field is ignored — the run always
2495/// uses `StreamingMode::None`.
2496pub async fn run_collect(
2497    State(controller): State<RuntimeController>,
2498    headers: HeaderMap,
2499    Json(req): Json<RunSseRequest>,
2500) -> Result<Json<Vec<adk_core::Event>>, RuntimeError> {
2501    run_collect_for_request(State(controller), parts_from_headers(&headers)?, Json(req)).await
2502}
2503
2504/// `POST /run` as the server routes it: the request context extractor sees the whole
2505/// request, including its peer address, rather than only its headers.
2506pub(crate) async fn run_collect_for_request(
2507    State(controller): State<RuntimeController>,
2508    parts: Parts,
2509    Json(req): Json<RunSseRequest>,
2510) -> Result<Json<Vec<adk_core::Event>>, RuntimeError> {
2511    let expose_details = controller.config.security.expose_error_details;
2512    let problem = move |error: adk_core::AdkError| adk_err_to_runtime(error, expose_details);
2513    let app_name = req.app_name.clone();
2514    let user_id = req.user_id.clone();
2515    let session_id = req.session_id.clone();
2516
2517    info!(
2518        app_name = %app_name,
2519        user_id = %user_id,
2520        session_id = %session_id,
2521        "POST /run request received"
2522    );
2523
2524    // Extract request context from auth middleware bridge if configured.
2525    // This returns Err (401/500) when the extractor is present but auth
2526    // fails, ensuring authorization checks are never bypassed.
2527    let request_context =
2528        extract_request_context(controller.config.request_context_extractor.as_deref(), &parts)
2529            .await?;
2530
2531    // Explicit authenticated user override: when an auth extractor is
2532    // configured and succeeds, the authenticated user_id takes precedence
2533    // over the request body value. This prevents callers from impersonating
2534    // other users via the JSON payload while keeping the body param as a
2535    // fallback for unauthenticated deployments (no extractor configured).
2536    let effective_user_id = request_context.as_ref().map_or(user_id, |rc| rc.user_id.clone());
2537
2538    let new_message = req
2539        .new_message
2540        .as_ref()
2541        .ok_or_else(|| (StatusCode::BAD_REQUEST, "newMessage is required".to_string()))?;
2542
2543    // Build content from message parts (includes both text and inline_data)
2544    let content = build_content_from_parts(&new_message.parts)?;
2545
2546    let state_delta = body_state_delta(req.state_delta.as_ref())?;
2547
2548    // The agent loads first, so an unknown app reports itself rather than a missing session.
2549    let agent = controller.config.agent_loader.load_agent(&app_name).await.map_err(problem)?;
2550
2551    // An ADK run, as /run_sse without a UI protocol: the session must exist.
2552    ensure_session(
2553        &controller.config.session_service,
2554        &app_name,
2555        &effective_user_id,
2556        &session_id,
2557        state_delta,
2558        expose_details,
2559        MissingSession::Refuse,
2560    )
2561    .await?;
2562
2563    // Create runner — always non-streaming for the plain-JSON endpoint
2564    let mut runner_builder = adk_runner::Runner::builder()
2565        .app_name(app_name)
2566        .agent(agent)
2567        .session_service(controller.config.session_service.clone())
2568        .governance(controller.config.governance.clone())
2569        .session_activity(controller.config.session_activity.clone())
2570        .run_config(
2571            adk_core::RunConfig::builder().streaming_mode(adk_core::StreamingMode::None).build(),
2572        );
2573    if let Some(ref artifact_service) = controller.config.artifact_service {
2574        runner_builder = runner_builder.artifact_service(artifact_service.clone());
2575    }
2576    if let Some(ref memory_service) = controller.config.memory_service {
2577        runner_builder = runner_builder.memory_service(memory_service.clone());
2578    }
2579    if let Some(ref compaction_config) = controller.config.compaction_config {
2580        runner_builder = runner_builder.compaction_config(compaction_config.clone());
2581    }
2582    if let Some(ref context_cache_config) = controller.config.context_cache_config {
2583        runner_builder = runner_builder.context_cache_config(context_cache_config.clone());
2584    }
2585    if let Some(ref cache_capable) = controller.config.cache_capable {
2586        runner_builder = runner_builder.cache_capable(cache_capable.clone());
2587    }
2588    if let Some(request_context) = request_context {
2589        runner_builder = runner_builder.request_context(request_context);
2590    }
2591    let runner = runner_builder.build().map_err(problem)?;
2592
2593    // Run agent to completion, collecting every event
2594    let typed_user_id = UserId::new(effective_user_id).map_err(|err| problem(err.into()))?;
2595    let typed_session_id = SessionId::new(session_id).map_err(|err| problem(err.into()))?;
2596    let mut event_stream =
2597        runner.run(typed_user_id, typed_session_id, content).await.map_err(problem)?;
2598
2599    let mut events = Vec::new();
2600    while let Some(event) = event_stream.next().await {
2601        events.push(event.map_err(problem)?);
2602    }
2603
2604    info!(event_count = events.len(), "POST /run completed");
2605
2606    Ok(Json(events))
2607}
2608
2609#[cfg(test)]
2610#[path = "runtime_stream_tests.rs"]
2611mod stream_tests;
2612
2613#[cfg(test)]
2614mod error_status_tests {
2615    use super::*;
2616    use adk_core::{AdkError, ErrorCategory, ErrorComponent};
2617
2618    #[test]
2619    fn conflict_errors_map_to_409_with_their_code() {
2620        let error = AdkError::new(
2621            ErrorComponent::Agent,
2622            ErrorCategory::Conflict,
2623            "run_store.stale_epoch",
2624            "run is no longer held",
2625        );
2626        let (status, body) = adk_err_to_runtime(error, false);
2627        assert_eq!(status, StatusCode::CONFLICT);
2628        let body: serde_json::Value = serde_json::from_str(&body).unwrap();
2629        assert_eq!(body["error"]["category"], "conflict");
2630        assert_eq!(body["error"]["code"], "run_store.stale_epoch");
2631    }
2632}
2633
2634#[cfg(test)]
2635mod message_part_tests {
2636    use super::*;
2637
2638    #[test]
2639    fn a_function_response_part_answers_its_call_by_id() {
2640        // The shape adk-python and adk-go clients send to resume a long-running call.
2641        let message: NewMessage = serde_json::from_value(serde_json::json!({
2642            "role": "user",
2643            "parts": [{"functionResponse": {
2644                "id": "call-approve",
2645                "name": "request_approval",
2646                "response": {"status": "approved"}
2647            }}]
2648        }))
2649        .unwrap();
2650        let content = build_content_from_parts(&message.parts).unwrap();
2651        match content.parts.as_slice() {
2652            [adk_core::Part::FunctionResponse { function_response, id, .. }] => {
2653                assert_eq!(id.as_deref(), Some("call-approve"));
2654                assert_eq!(function_response.name, "request_approval");
2655                assert_eq!(function_response.response, serde_json::json!({"status": "approved"}));
2656            }
2657            other => panic!("expected one function response, got {other:?}"),
2658        }
2659    }
2660}