Skip to main content

aether_cli/acp/
session_manager.rs

1use acp_utils::notifications::{AuthMethodsUpdatedParams, McpRequest};
2use acp_utils::server::AcpServerError;
3use aether_auth::OAuthCredentialStorage;
4use agent_client_protocol::schema::{
5    self as acp, AgentCapabilities, AuthMethod, AuthenticateRequest, AuthenticateResponse, AvailableCommandsUpdate,
6    ConfigOptionUpdate, Implementation, InitializeRequest, InitializeResponse, ListSessionsRequest,
7    ListSessionsResponse, LoadSessionRequest, LoadSessionResponse, McpCapabilities, NewSessionRequest,
8    NewSessionResponse, PromptCapabilities, PromptResponse, ProtocolVersion, SessionId, SessionNotification,
9    SessionUpdate, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse,
10};
11use agent_client_protocol::{Client, ConnectionTo};
12use llm::catalog::{LlmModel, get_local_models};
13use llm::types::IsoString;
14use llm::{ContentBlock, ReasoningEffort};
15use std::collections::HashSet;
16use std::path::Path;
17use std::sync::Arc;
18use tokio::spawn;
19use tokio::sync::oneshot;
20use tracing::{error, info, warn};
21
22use super::config_setting::ConfigSetting;
23use super::mappers::{map_acp_mcp_servers, replay_to_client};
24use super::model_config::{
25    ValidatedMode, build_config_options_from_modes, pick_default_model, supports_prompt_audio,
26    validated_modes_from_specs,
27};
28use super::relay::{SessionCommand, spawn_relay};
29use super::session::Session;
30use super::session_registry::{ConfigSnapshot, SessionRegistry};
31use super::session_store::{SessionMeta, SessionStore};
32use crate::settings_args::SettingsSourceArgs;
33use acp_utils::content::format_embedded_resource;
34use aether_core::agent_spec::AgentSpec;
35use aether_core::context::ext::ContextExt;
36use aether_project::{AetherSettings, AgentCatalog};
37use llm::Context;
38
39/// Initial session selection supplied when `aether acp` starts.
40#[derive(Clone, Debug, Default)]
41pub enum InitialSessionSelection {
42    #[default]
43    Default,
44    Agent(String),
45    Model {
46        model: String,
47        reasoning_effort: Option<ReasoningEffort>,
48    },
49}
50
51impl InitialSessionSelection {
52    pub fn agent(name: String) -> Self {
53        Self::Agent(name)
54    }
55
56    pub fn model(model: String, reasoning_effort: Option<ReasoningEffort>) -> Self {
57        Self::Model { model, reasoning_effort }
58    }
59}
60
61/// Manages ACP sessions, each session has its own agent and state
62pub struct SessionManager {
63    registry: Arc<SessionRegistry>,
64    session_store: Arc<SessionStore>,
65    oauth_credential_store: Arc<dyn OAuthCredentialStorage>,
66    initial_selection: InitialSessionSelection,
67    settings_source: SettingsSourceArgs,
68}
69
70pub(crate) struct SessionManagerConfig {
71    pub(crate) registry: Arc<SessionRegistry>,
72    pub(crate) session_store: Arc<SessionStore>,
73    pub(crate) oauth_credential_store: Arc<dyn OAuthCredentialStorage>,
74    pub(crate) initial_selection: InitialSessionSelection,
75    pub(crate) settings_source: SettingsSourceArgs,
76}
77
78struct SessionModeCatalog {
79    catalog: AgentCatalog,
80    modes: Vec<ValidatedMode>,
81    available: Vec<LlmModel>,
82}
83
84struct ResolvedInitialSession {
85    spec: AgentSpec,
86    selected_mode: Option<String>,
87}
88
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
90struct PromptModalities {
91    image: bool,
92    audio: bool,
93}
94
95impl PromptModalities {
96    fn from_content(content: &[ContentBlock]) -> Self {
97        Self {
98            image: content.iter().any(ContentBlock::is_image),
99            audio: content.iter().any(|block| matches!(block, ContentBlock::Audio { .. })),
100        }
101    }
102
103    fn is_empty(self) -> bool {
104        !self.image && !self.audio
105    }
106}
107
108impl SessionManager {
109    pub(crate) fn new(deps: SessionManagerConfig) -> Self {
110        Self {
111            registry: deps.registry,
112            session_store: deps.session_store,
113            oauth_credential_store: deps.oauth_credential_store,
114            initial_selection: deps.initial_selection,
115            settings_source: deps.settings_source,
116        }
117    }
118
119    fn resolve_initial_session(
120        &self,
121        mode_catalog: &SessionModeCatalog,
122        default_model: &LlmModel,
123    ) -> Result<ResolvedInitialSession, acp::Error> {
124        match &self.initial_selection {
125            InitialSessionSelection::Default => resolve_default_initial_session(mode_catalog, default_model),
126            InitialSessionSelection::Agent(agent) => {
127                if !mode_catalog.modes.iter().any(|mode| mode.name == *agent) {
128                    warn!("Unknown agent `{agent}` requested via --agent");
129                    return Err(acp::Error::invalid_params());
130                }
131                resolve_agent_spec(&mode_catalog.catalog, agent)
132                    .map(|spec| ResolvedInitialSession { spec, selected_mode: Some(agent.clone()) })
133            }
134            InitialSessionSelection::Model { model, reasoning_effort } => {
135                let model = parse_available_model(model, &mode_catalog.available)?;
136                Ok(ResolvedInitialSession {
137                    spec: AgentSpec::default_spec(&model, *reasoning_effort, Vec::new()),
138                    selected_mode: None,
139                })
140            }
141        }
142    }
143
144    async fn load_mode_catalog(&self, cwd: &Path) -> Result<SessionModeCatalog, acp::Error> {
145        let config = if let Some(source) = self.settings_source.source(cwd) {
146            AetherSettings::load(cwd, [source])
147        } else {
148            AetherSettings::load_default(cwd)
149        }
150        .map_err(|e| {
151            error!("Failed to load agent catalog: {e}");
152            acp::Error::invalid_params()
153        })?;
154        let catalog = if config.agents.is_empty() {
155            AgentCatalog::empty(cwd.to_path_buf())
156        } else {
157            AgentCatalog::from_settings(cwd, config).map_err(|e| {
158                error!("Failed to load agent catalog: {e}");
159                acp::Error::invalid_params()
160            })?
161        };
162
163        let available = get_local_models().await;
164        let specs: Vec<_> = catalog.user_invocable().cloned().collect();
165        let modes = validated_modes_from_specs(&specs, &available);
166
167        Ok(SessionModeCatalog { catalog, modes, available })
168    }
169
170    #[allow(clippy::too_many_arguments, clippy::similar_names)]
171    async fn register_session(
172        &self,
173        session: Session,
174        session_id: &str,
175        acp_session_id: &SessionId,
176        model: &str,
177        selected_mode: Option<String>,
178        reasoning_effort: Option<ReasoningEffort>,
179        modes: Vec<ValidatedMode>,
180        cx: &ConnectionTo<Client>,
181    ) -> Vec<acp::SessionConfigOption> {
182        let relay = spawn_relay(
183            session,
184            cx.clone(),
185            acp_session_id.clone(),
186            self.session_store.clone(),
187            Arc::clone(&self.oauth_credential_store),
188        );
189
190        self.registry
191            .insert(
192                session_id.to_string(),
193                relay,
194                model.to_string(),
195                selected_mode.clone(),
196                reasoning_effort,
197                modes.clone(),
198            )
199            .await;
200
201        let available = get_local_models().await;
202        let all_models = get_all_models(&available);
203        build_config_options_from_modes(
204            &modes,
205            &available,
206            selected_mode.as_deref(),
207            model,
208            reasoning_effort,
209            &all_models,
210            self.oauth_credential_store.as_ref(),
211        )
212    }
213
214    fn send_available_commands_notification(
215        available_commands: Vec<acp::AvailableCommand>,
216        acp_session_id: SessionId,
217        session_id: &str,
218        cx: &ConnectionTo<Client>,
219    ) {
220        if available_commands.is_empty() {
221            return;
222        }
223        let command_count = available_commands.len();
224        let notification = SessionNotification::new(
225            acp_session_id,
226            SessionUpdate::AvailableCommandsUpdate(AvailableCommandsUpdate::new(available_commands)),
227        );
228        if let Err(e) = cx.send_notification(notification).map_err(|e| AcpServerError::protocol("session/update", e)) {
229            error!("Failed to send available commands notification: {:?}", e);
230        } else {
231            info!("Sent available commands update for session {} ({} commands)", session_id, command_count);
232        }
233    }
234
235    /// Drain every session and stop its relay task. Blocks until every relay
236    /// has exited.
237    pub async fn shutdown_all_sessions(&self) {
238        self.registry.shutdown_all().await;
239    }
240}
241
242fn options_from_snapshot(
243    snapshot: &ConfigSnapshot,
244    available: &[LlmModel],
245    all_models: &[LlmModel],
246    credential_store: &dyn OAuthCredentialStorage,
247) -> Vec<acp::SessionConfigOption> {
248    build_config_options_from_modes(
249        &snapshot.modes,
250        available,
251        snapshot.selected_mode.as_deref(),
252        &snapshot.effective_model,
253        snapshot.reasoning_effort,
254        all_models,
255        credential_store,
256    )
257}
258
259/// Merge catalog `all()` with locally-discovered models for the `all_models`
260/// parameter of `build_model_config_option`.
261fn get_all_models(discovered: &[LlmModel]) -> Vec<LlmModel> {
262    let mut all = LlmModel::all().to_vec();
263    for m in discovered {
264        if !all.contains(m) {
265            all.push(m.clone());
266        }
267    }
268    all
269}
270
271fn build_auth_methods(store: &dyn OAuthCredentialStorage) -> Vec<AuthMethod> {
272    let mut seen = HashSet::new();
273    LlmModel::all()
274        .iter()
275        .filter_map(LlmModel::oauth_provider_id)
276        .filter(|id| seen.insert(*id))
277        .map(|id| {
278            let display = LlmModel::all()
279                .iter()
280                .find(|m| m.oauth_provider_id() == Some(id))
281                .map_or(id, |m| m.provider_display_name());
282            let mut method = acp::AuthMethodAgent::new(id, display);
283            if store.has_credential(id) {
284                method = method.description("authenticated");
285            }
286            AuthMethod::Agent(method)
287        })
288        .collect()
289}
290
291fn map_acp_to_content_blocks(blocks: Vec<acp::ContentBlock>) -> Vec<ContentBlock> {
292    blocks
293        .into_iter()
294        .map(|block| match block {
295            acp::ContentBlock::Text(t) => ContentBlock::text(t.text),
296            acp::ContentBlock::Image(img) => ContentBlock::Image { data: img.data, mime_type: img.mime_type },
297            acp::ContentBlock::Audio(aud) => ContentBlock::Audio { data: aud.data, mime_type: aud.mime_type },
298            acp::ContentBlock::Resource(r) => ContentBlock::text(format_embedded_resource(&r)),
299            acp::ContentBlock::ResourceLink(l) => ContentBlock::text(format!("[Resource: {}]", l.uri)),
300            _ => ContentBlock::text("[Unknown content]"),
301        })
302        .collect()
303}
304
305fn resolve_agent_spec(catalog: &AgentCatalog, mode_name: &str) -> Result<AgentSpec, acp::Error> {
306    catalog.resolve(mode_name).map_err(|e| {
307        error!("Failed to resolve runtime inputs for mode '{}': {e}", mode_name);
308        acp::Error::invalid_params()
309    })
310}
311
312fn resolve_default_initial_session(
313    mode_catalog: &SessionModeCatalog,
314    default_model: &LlmModel,
315) -> Result<ResolvedInitialSession, acp::Error> {
316    if let Some(mode) = mode_catalog.modes.first() {
317        return resolve_agent_spec(&mode_catalog.catalog, &mode.name)
318            .map(|spec| ResolvedInitialSession { spec, selected_mode: Some(mode.name.clone()) });
319    }
320
321    Ok(ResolvedInitialSession { spec: AgentSpec::default_spec(default_model, None, Vec::new()), selected_mode: None })
322}
323
324fn parse_available_model(model: &str, available: &[LlmModel]) -> Result<LlmModel, acp::Error> {
325    let parsed = model.parse().map_err(|e: String| {
326        warn!("Failed to parse --model `{model}`: {e}");
327        acp::Error::invalid_params()
328    })?;
329    if available.iter().any(|available| available == &parsed) {
330        Ok(parsed)
331    } else {
332        warn!("Requested model `{model}` is not available");
333        Err(acp::Error::invalid_params())
334    }
335}
336
337fn prompt_capabilities_for_models(models: &[LlmModel]) -> PromptCapabilities {
338    PromptCapabilities::new()
339        .embedded_context(true)
340        .image(models.iter().any(LlmModel::supports_image))
341        .audio(models.iter().any(supports_prompt_audio))
342}
343
344fn selected_models(model_value: &str) -> Result<Vec<LlmModel>, acp::Error> {
345    model_value
346        .split(',')
347        .map(str::trim)
348        .filter(|part| !part.is_empty())
349        .map(|part| part.parse::<LlmModel>().map_err(|_| acp::Error::invalid_params()))
350        .collect()
351}
352
353fn validate_prompt_support(model_value: &str, content: &[ContentBlock]) -> Result<(), acp::Error> {
354    let modalities = PromptModalities::from_content(content);
355    if modalities.is_empty() {
356        return Ok(());
357    }
358
359    let selected = selected_models(model_value)?;
360    if modalities.image && selected.iter().any(|model| !model.supports_image()) {
361        return Err(acp::Error::invalid_params());
362    }
363    if modalities.audio && selected.iter().any(|model| !supports_prompt_audio(model)) {
364        return Err(acp::Error::invalid_params());
365    }
366
367    Ok(())
368}
369
370#[cfg(test)]
371#[allow(clippy::items_after_test_module)]
372mod tests {
373    use super::*;
374    use agent_client_protocol::schema::{InitializeRequest, ProtocolVersion};
375
376    const SONNET: &str = "anthropic:claude-sonnet-4-5";
377    const DEEPSEEK: &str = "deepseek:deepseek-chat";
378
379    fn mock_oauth_store() -> Arc<dyn OAuthCredentialStorage> {
380        Arc::new(aether_auth::FakeOAuthCredentialStore::new())
381    }
382
383    #[tokio::test]
384    async fn initialize_always_advertises_load_session_support() {
385        let session_store =
386            SessionStore::new().map_or_else(|e| panic!("Failed to initialize session store: {e}"), Arc::new);
387        let manager = SessionManager::new(SessionManagerConfig {
388            registry: Arc::new(SessionRegistry::new()),
389            session_store,
390            oauth_credential_store: mock_oauth_store(),
391            initial_selection: InitialSessionSelection::default(),
392            settings_source: SettingsSourceArgs::default(),
393        });
394        let response =
395            manager.initialize(InitializeRequest::new(ProtocolVersion::LATEST)).await.expect("initialize succeeds");
396        let json = serde_json::to_string(&response).expect("response serializes");
397        assert!(json.contains("\"loadSession\":true"));
398    }
399
400    #[test]
401    fn prompt_capabilities_reflect_available_modalities() {
402        let image_only = prompt_capabilities_for_models(&["anthropic:claude-sonnet-4-5".parse().unwrap()]);
403        assert!(image_only.image);
404        assert!(!image_only.audio);
405
406        let audio_capable =
407            prompt_capabilities_for_models(&["gemini:gemini-live-2.5-flash-preview-native-audio".parse().unwrap()]);
408        assert!(!audio_capable.image);
409        assert!(audio_capable.audio);
410
411        let text_only = prompt_capabilities_for_models(&[DEEPSEEK.parse().unwrap()]);
412        assert!(!text_only.image);
413        assert!(!text_only.audio);
414    }
415
416    #[test]
417    fn validate_prompt_support_requires_all_selected_models_to_support_media() {
418        let image_content = vec![ContentBlock::Image { data: "aW1n".to_string(), mime_type: "image/png".to_string() }];
419        let audio_content =
420            vec![ContentBlock::Audio { data: "YXVkaW8=".to_string(), mime_type: "audio/wav".to_string() }];
421
422        assert!(validate_prompt_support(SONNET, &image_content).is_ok());
423        assert!(validate_prompt_support(DEEPSEEK, &image_content).is_err());
424        assert!(validate_prompt_support("gemini:gemini-live-2.5-flash-preview-native-audio", &audio_content,).is_ok());
425        assert!(validate_prompt_support(SONNET, &audio_content).is_err());
426        assert!(
427            validate_prompt_support("anthropic:claude-sonnet-4-5,deepseek:deepseek-chat", &image_content,).is_err()
428        );
429        assert!(
430            validate_prompt_support(
431                "gemini:gemini-live-2.5-flash-preview-native-audio,deepseek:deepseek-chat",
432                &audio_content,
433            )
434            .is_err()
435        );
436    }
437}
438
439impl SessionManager {
440    pub async fn initialize(&self, args: InitializeRequest) -> Result<InitializeResponse, acp::Error> {
441        info!("Received initialize request: {:?}", args);
442        let auth_methods = build_auth_methods(self.oauth_credential_store.as_ref());
443        let available = get_local_models().await;
444        Ok(InitializeResponse::new(ProtocolVersion::V1)
445            .agent_info(Implementation::new("Aether", "0.1.0"))
446            .agent_capabilities(
447                AgentCapabilities::new()
448                    .load_session(true)
449                    .mcp_capabilities(McpCapabilities::new().http(true).sse(true))
450                    .session_capabilities(acp::SessionCapabilities::new().list(acp::SessionListCapabilities::new()))
451                    .prompt_capabilities(prompt_capabilities_for_models(&available)),
452            )
453            .auth_methods(auth_methods))
454    }
455
456    pub async fn authenticate(
457        &self,
458        args: AuthenticateRequest,
459        cx: &ConnectionTo<Client>,
460    ) -> Result<AuthenticateResponse, acp::Error> {
461        info!("Received authenticate request: {:?}", args);
462        let method_id = args.method_id.0.as_ref();
463        match method_id {
464            "codex" => {
465                llm::perform_codex_oauth_flow(self.oauth_credential_store.as_ref()).await.map_err(|e| {
466                    error!("OAuth flow failed for {method_id}: {e}");
467                    acp::Error::internal_error()
468                })?;
469            }
470            _ => return Err(acp::Error::invalid_params()),
471        }
472        let auth_methods = build_auth_methods(self.oauth_credential_store.as_ref());
473        if let Err(e) = cx
474            .send_notification(AuthMethodsUpdatedParams { auth_methods })
475            .map_err(|e| AcpServerError::protocol("_aether/auth_methods_updated", e))
476        {
477            error!("Failed to send auth methods updated notification: {:?}", e);
478        }
479
480        let available = get_local_models().await;
481        let all_models = get_all_models(&available);
482        let snapshots = self.registry.snapshot_all_configs().await;
483
484        for (id, snap) in snapshots {
485            let options = options_from_snapshot(&snap, &available, &all_models, self.oauth_credential_store.as_ref());
486            let notification = SessionNotification::new(
487                SessionId::new(id),
488                SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(options)),
489            );
490            let _ = cx.send_notification(notification);
491        }
492
493        Ok(AuthenticateResponse::default())
494    }
495
496    pub async fn new_session(
497        &self,
498        mut args: NewSessionRequest,
499        cx: &ConnectionTo<Client>,
500    ) -> Result<NewSessionResponse, acp::Error> {
501        // Inside a sandbox container the client sends the *host* cwd, but the
502        // project is mounted at the container's working directory.
503        if std::env::var("AETHER_INSIDE_SANDBOX").is_ok() {
504            let container_cwd = std::env::current_dir().unwrap_or_else(|_| "/workspace".into());
505            info!("Sandbox: remapping cwd {:?} -> {:?}", args.cwd, container_cwd);
506            args.cwd = container_cwd;
507        }
508
509        info!("Creating new session with cwd: {:?}", args.cwd);
510        let session_id = uuid::Uuid::new_v4().to_string();
511        let acp_session_id = acp::SessionId::new(session_id.clone());
512
513        let mode_catalog = self.load_mode_catalog(&args.cwd).await?;
514        let default_model = pick_default_model(&mode_catalog.available).ok_or_else(|| {
515            error!("No models available — set an API key env var (e.g. ANTHROPIC_API_KEY)");
516            acp::Error::internal_error()
517        })?;
518
519        let ResolvedInitialSession { spec, selected_mode } =
520            self.resolve_initial_session(&mode_catalog, default_model)?;
521        let model_str = spec.model.clone();
522        let reasoning_effort = spec.reasoning_effort;
523
524        let session = Session::new(
525            spec,
526            args.cwd.clone(),
527            map_acp_mcp_servers(args.mcp_servers),
528            None,
529            Some(session_id.clone()),
530            Arc::clone(&self.oauth_credential_store),
531        )
532        .await
533        .map_err(|e| {
534            error!("Failed to create session: {}", e);
535            acp::Error::internal_error()
536        })?;
537
538        let available_commands = session.list_available_commands().await.map_err(|e| {
539            error!("Failed to list available commands: {}", e);
540            acp::Error::internal_error()
541        })?;
542
543        let meta = SessionMeta {
544            session_id: session_id.clone(),
545            cwd: args.cwd.clone(),
546            model: model_str.clone(),
547            selected_mode: selected_mode.clone(),
548            created_at: IsoString::now().0,
549        };
550        if let Err(e) = self.session_store.append_meta(&session_id, &meta) {
551            error!("Failed to write session meta: {e}");
552        }
553
554        let config_options = self
555            .register_session(
556                session,
557                &session_id,
558                &acp_session_id,
559                &model_str,
560                selected_mode,
561                reasoning_effort,
562                mode_catalog.modes,
563                cx,
564            )
565            .await;
566
567        info!("Session {} created successfully", session_id);
568
569        let response = NewSessionResponse::new(acp_session_id.clone()).config_options(config_options);
570
571        Self::send_available_commands_notification(available_commands, acp_session_id, &session_id, cx);
572
573        Ok(response)
574    }
575
576    pub fn list_sessions(&self, args: &ListSessionsRequest) -> Result<ListSessionsResponse, acp::Error> {
577        info!("Listing sessions, cwd filter: {:?}", args.cwd);
578        let mut summaries = self.session_store.list();
579
580        if let Some(cwd) = args.cwd.as_ref() {
581            summaries.retain(|s| s.meta.cwd == *cwd);
582        }
583
584        let sessions: Vec<acp::SessionInfo> = summaries
585            .into_iter()
586            .map(|s| acp::SessionInfo::new(s.meta.session_id, s.meta.cwd).updated_at(s.meta.created_at).title(s.title))
587            .collect();
588
589        info!("Found {} sessions", sessions.len());
590        Ok(ListSessionsResponse::new(sessions))
591    }
592
593    pub async fn load_session(
594        &self,
595        args: LoadSessionRequest,
596        cx: &ConnectionTo<Client>,
597    ) -> Result<LoadSessionResponse, acp::Error> {
598        let session_id = args.session_id.0.to_string();
599        info!("Loading session: {session_id}");
600
601        let (meta, events) = self.session_store.load(&session_id).ok_or_else(|| {
602            error!("Session not found: {session_id}");
603            acp::Error::invalid_params()
604        })?;
605
606        let context = Context::from_events(&events);
607        let mode_catalog = self.load_mode_catalog(&args.cwd).await?;
608
609        let spec = if let Some(mode_name) = meta.selected_mode.as_deref() {
610            resolve_agent_spec(&mode_catalog.catalog, mode_name)?
611        } else {
612            let parsed_model: LlmModel = meta.model.parse().map_err(|e: String| {
613                error!("Failed to parse restored model '{}': {e}", meta.model);
614                acp::Error::invalid_params()
615            })?;
616            AgentSpec::default_spec(&parsed_model, None, Vec::new())
617        };
618
619        let model = spec.model.clone();
620
621        let restored_messages: Vec<_> = context.messages().iter().filter(|m| !m.is_system()).cloned().collect();
622
623        let session = Session::new(
624            spec,
625            args.cwd.clone(),
626            map_acp_mcp_servers(args.mcp_servers),
627            Some(restored_messages),
628            Some(session_id.clone()),
629            Arc::clone(&self.oauth_credential_store),
630        )
631        .await
632        .map_err(|e| {
633            error!("Failed to create session for load: {e}");
634            acp::Error::internal_error()
635        })?;
636
637        let available_commands = session.list_available_commands().await.map_err(|e| {
638            error!("Failed to list available commands: {e}");
639            acp::Error::internal_error()
640        })?;
641
642        let acp_session_id = acp::SessionId::new(session_id.clone());
643
644        let config_options = self
645            .register_session(
646                session,
647                &session_id,
648                &acp_session_id,
649                &model,
650                meta.selected_mode,
651                None,
652                mode_catalog.modes,
653                cx,
654            )
655            .await;
656
657        info!("Session {session_id} loaded successfully");
658
659        let response = LoadSessionResponse::new().config_options(config_options);
660
661        let cx_clone = cx.clone();
662        let replay_session_id = acp_session_id.clone();
663        spawn(async move {
664            replay_to_client(&events, &cx_clone, &replay_session_id).await;
665        });
666
667        Self::send_available_commands_notification(available_commands, acp_session_id, &session_id, cx);
668
669        Ok(response)
670    }
671
672    pub async fn prompt(&self, args: acp::PromptRequest) -> Result<acp::PromptResponse, acp::Error> {
673        info!("Received prompt for session: {:?}", args.session_id);
674        let session_id_str = args.session_id.0.to_string();
675        let content = map_acp_to_content_blocks(args.prompt);
676
677        let model = self.registry.effective_model(&session_id_str).await.ok_or_else(|| {
678            error!("Session not found: {}", session_id_str);
679            acp::Error::invalid_params()
680        })?;
681        validate_prompt_support(&model, &content)?;
682
683        let dispatch = self.registry.begin_prompt(&session_id_str).await.ok_or_else(|| {
684            error!("Session not found: {}", session_id_str);
685            acp::Error::invalid_params()
686        })?;
687
688        let (result_tx, result_rx) = oneshot::channel();
689        dispatch
690            .relay_tx
691            .send(SessionCommand::Prompt {
692                content,
693                switch_model: dispatch.switch_model,
694                reasoning_effort: dispatch.reasoning_effort,
695                result_tx,
696            })
697            .await
698            .map_err(|_| {
699                error!("Relay channel closed for session {}", session_id_str);
700                acp::Error::internal_error()
701            })?;
702
703        let stop_reason = result_rx
704            .await
705            .map_err(|_| {
706                error!("Relay dropped result channel for session {}", session_id_str);
707                acp::Error::internal_error()
708            })?
709            .map_err(|e| {
710                error!("Relay error for session {}: {}", session_id_str, e);
711                acp::Error::internal_error()
712            })?;
713
714        info!("Prompt completed with stop reason: {:?}", stop_reason);
715        Ok(PromptResponse::new(stop_reason))
716    }
717
718    pub async fn cancel(&self, args: acp::CancelNotification) -> Result<(), acp::Error> {
719        info!("Received cancel for session: {:?}", args.session_id);
720        let session_id_str = args.session_id.0.to_string();
721        let relay = self.registry.relay(&session_id_str).await.ok_or_else(|| {
722            error!("Session not found for cancel: {}", session_id_str);
723            acp::Error::invalid_params()
724        })?;
725
726        relay.cmd.send(SessionCommand::Cancel).await.map_err(|_| {
727            error!("Relay channel closed for cancel: {}", session_id_str);
728            acp::Error::internal_error()
729        })?;
730
731        Ok(())
732    }
733
734    pub async fn set_session_config_option(
735        &self,
736        args: SetSessionConfigOptionRequest,
737    ) -> Result<SetSessionConfigOptionResponse, acp::Error> {
738        let session_id_str = args.session_id.0.to_string();
739        let config_id = args.config_id.0.to_string();
740        let value = args.value.0.to_string();
741
742        info!("set_session_config_option: session={}, config={}, value={}", session_id_str, config_id, value);
743
744        let setting = ConfigSetting::parse(&config_id, &value).map_err(|e| {
745            error!("{e}");
746            acp::Error::invalid_params()
747        })?;
748
749        let available = get_local_models().await;
750        let all_models = get_all_models(&available);
751
752        let snapshot =
753            self.registry.apply_config_change(&session_id_str, &setting, &available).await.ok_or_else(|| {
754                error!("Session not found: {}", session_id_str);
755                acp::Error::invalid_params()
756            })??;
757
758        let options = options_from_snapshot(&snapshot, &available, &all_models, self.oauth_credential_store.as_ref());
759        Ok(SetSessionConfigOptionResponse::new(options))
760    }
761
762    pub async fn on_mcp_request(&self, request: McpRequest) -> Result<(), acp::Error> {
763        info!("Received MCP ext request: {:?}", request);
764        match request {
765            McpRequest::Authenticate { session_id, server_name } => {
766                let relay = self.registry.relay(&session_id).await.ok_or_else(|| {
767                    error!("Session not found for authenticate_mcp_server: {}", session_id);
768                    acp::Error::invalid_params()
769                })?;
770
771                relay.mcp_request.send(McpRequest::Authenticate { session_id, server_name }).await.map_err(|_| {
772                    error!("MCP request channel closed for session");
773                    acp::Error::internal_error()
774                })?;
775            }
776        }
777
778        Ok(())
779    }
780}