Skip to main content

aether_cli/acp/
session_manager.rs

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