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::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    has_oauth_credential: fn(&str) -> bool,
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) has_oauth_credential: fn(&str) -> bool,
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            has_oauth_credential: deps.has_oauth_credential,
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            &OAuthCredentialStore::default(),
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: &OAuthCredentialStore,
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(has_credential: impl Fn(&str) -> bool) -> 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 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    #[tokio::test]
374    async fn initialize_always_advertises_load_session_support() {
375        let session_store =
376            SessionStore::new().map_or_else(|e| panic!("Failed to initialize session store: {e}"), Arc::new);
377        let manager = SessionManager::new(SessionManagerConfig {
378            registry: Arc::new(SessionRegistry::new()),
379            session_store,
380            has_oauth_credential: |_| false,
381            initial_selection: InitialSessionSelection::default(),
382            settings_source: SettingsSourceArgs::default(),
383        });
384        let response =
385            manager.initialize(InitializeRequest::new(ProtocolVersion::LATEST)).await.expect("initialize succeeds");
386        let json = serde_json::to_string(&response).expect("response serializes");
387        assert!(json.contains("\"loadSession\":true"));
388    }
389
390    #[test]
391    fn prompt_capabilities_reflect_available_modalities() {
392        let image_only = prompt_capabilities_for_models(&["anthropic:claude-sonnet-4-5".parse().unwrap()]);
393        assert!(image_only.image);
394        assert!(!image_only.audio);
395
396        let audio_capable =
397            prompt_capabilities_for_models(&["gemini:gemini-live-2.5-flash-preview-native-audio".parse().unwrap()]);
398        assert!(!audio_capable.image);
399        assert!(audio_capable.audio);
400
401        let text_only = prompt_capabilities_for_models(&[DEEPSEEK.parse().unwrap()]);
402        assert!(!text_only.image);
403        assert!(!text_only.audio);
404    }
405
406    #[test]
407    fn validate_prompt_support_requires_all_selected_models_to_support_media() {
408        let image_content = vec![ContentBlock::Image { data: "aW1n".to_string(), mime_type: "image/png".to_string() }];
409        let audio_content =
410            vec![ContentBlock::Audio { data: "YXVkaW8=".to_string(), mime_type: "audio/wav".to_string() }];
411
412        assert!(validate_prompt_support(SONNET, &image_content).is_ok());
413        assert!(validate_prompt_support(DEEPSEEK, &image_content).is_err());
414        assert!(validate_prompt_support("gemini:gemini-live-2.5-flash-preview-native-audio", &audio_content,).is_ok());
415        assert!(validate_prompt_support(SONNET, &audio_content).is_err());
416        assert!(
417            validate_prompt_support("anthropic:claude-sonnet-4-5,deepseek:deepseek-chat", &image_content,).is_err()
418        );
419        assert!(
420            validate_prompt_support(
421                "gemini:gemini-live-2.5-flash-preview-native-audio,deepseek:deepseek-chat",
422                &audio_content,
423            )
424            .is_err()
425        );
426    }
427}
428
429impl SessionManager {
430    pub async fn initialize(&self, args: InitializeRequest) -> Result<InitializeResponse, acp::Error> {
431        info!("Received initialize request: {:?}", args);
432        let auth_methods = build_auth_methods(self.has_oauth_credential);
433        let available = get_local_models().await;
434        Ok(InitializeResponse::new(ProtocolVersion::V1)
435            .agent_info(Implementation::new("Aether", "0.1.0"))
436            .agent_capabilities(
437                AgentCapabilities::new()
438                    .load_session(true)
439                    .mcp_capabilities(McpCapabilities::new().http(true).sse(true))
440                    .session_capabilities(acp::SessionCapabilities::new().list(acp::SessionListCapabilities::new()))
441                    .prompt_capabilities(prompt_capabilities_for_models(&available)),
442            )
443            .auth_methods(auth_methods))
444    }
445
446    pub async fn authenticate(
447        &self,
448        args: AuthenticateRequest,
449        cx: &ConnectionTo<Client>,
450    ) -> Result<AuthenticateResponse, acp::Error> {
451        info!("Received authenticate request: {:?}", args);
452        let method_id = args.method_id.0.as_ref();
453        match method_id {
454            "codex" => {
455                llm::perform_codex_oauth_flow().await.map_err(|e| {
456                    error!("OAuth flow failed for {method_id}: {e}");
457                    acp::Error::internal_error()
458                })?;
459            }
460            _ => return Err(acp::Error::invalid_params()),
461        }
462        let auth_methods = build_auth_methods(self.has_oauth_credential);
463        if let Err(e) = cx
464            .send_notification(AuthMethodsUpdatedParams { auth_methods })
465            .map_err(|e| AcpServerError::protocol("_aether/auth_methods_updated", e))
466        {
467            error!("Failed to send auth methods updated notification: {:?}", e);
468        }
469
470        let credential_store = OAuthCredentialStore::default();
471        let available = get_local_models().await;
472        let all_models = get_all_models(&available);
473        let snapshots = self.registry.snapshot_all_configs().await;
474
475        for (id, snap) in snapshots {
476            let options = options_from_snapshot(&snap, &available, &all_models, &credential_store);
477            let notification = SessionNotification::new(
478                SessionId::new(id),
479                SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(options)),
480            );
481            let _ = cx.send_notification(notification);
482        }
483
484        Ok(AuthenticateResponse::default())
485    }
486
487    pub async fn new_session(
488        &self,
489        mut args: NewSessionRequest,
490        cx: &ConnectionTo<Client>,
491    ) -> Result<NewSessionResponse, acp::Error> {
492        // Inside a sandbox container the client sends the *host* cwd, but the
493        // project is mounted at the container's working directory.
494        if std::env::var("AETHER_INSIDE_SANDBOX").is_ok() {
495            let container_cwd = std::env::current_dir().unwrap_or_else(|_| "/workspace".into());
496            info!("Sandbox: remapping cwd {:?} -> {:?}", args.cwd, container_cwd);
497            args.cwd = container_cwd;
498        }
499
500        info!("Creating new session with cwd: {:?}", args.cwd);
501        let session_id = uuid::Uuid::new_v4().to_string();
502        let acp_session_id = acp::SessionId::new(session_id.clone());
503
504        let mode_catalog = self.load_mode_catalog(&args.cwd).await?;
505        let default_model = pick_default_model(&mode_catalog.available).ok_or_else(|| {
506            error!("No models available — set an API key env var (e.g. ANTHROPIC_API_KEY)");
507            acp::Error::internal_error()
508        })?;
509
510        let ResolvedInitialSession { spec, selected_mode } =
511            self.resolve_initial_session(&mode_catalog, default_model)?;
512        let model_str = spec.model.clone();
513        let reasoning_effort = spec.reasoning_effort;
514
515        let session =
516            Session::new(spec, args.cwd.clone(), map_acp_mcp_servers(args.mcp_servers), None, Some(session_id.clone()))
517                .await
518                .map_err(|e| {
519                    error!("Failed to create session: {}", e);
520                    acp::Error::internal_error()
521                })?;
522
523        let available_commands = session.list_available_commands().await.map_err(|e| {
524            error!("Failed to list available commands: {}", e);
525            acp::Error::internal_error()
526        })?;
527
528        let meta = SessionMeta {
529            session_id: session_id.clone(),
530            cwd: args.cwd.clone(),
531            model: model_str.clone(),
532            selected_mode: selected_mode.clone(),
533            created_at: IsoString::now().0,
534        };
535        if let Err(e) = self.session_store.append_meta(&session_id, &meta) {
536            error!("Failed to write session meta: {e}");
537        }
538
539        let config_options = self
540            .register_session(
541                session,
542                &session_id,
543                &acp_session_id,
544                &model_str,
545                selected_mode,
546                reasoning_effort,
547                mode_catalog.modes,
548                cx,
549            )
550            .await;
551
552        info!("Session {} created successfully", session_id);
553
554        let response = NewSessionResponse::new(acp_session_id.clone()).config_options(config_options);
555
556        Self::send_available_commands_notification(available_commands, acp_session_id, &session_id, cx);
557
558        Ok(response)
559    }
560
561    pub fn list_sessions(&self, args: &ListSessionsRequest) -> Result<ListSessionsResponse, acp::Error> {
562        info!("Listing sessions, cwd filter: {:?}", args.cwd);
563        let mut summaries = self.session_store.list();
564
565        if let Some(cwd) = args.cwd.as_ref() {
566            summaries.retain(|s| s.meta.cwd == *cwd);
567        }
568
569        let sessions: Vec<acp::SessionInfo> = summaries
570            .into_iter()
571            .map(|s| acp::SessionInfo::new(s.meta.session_id, s.meta.cwd).updated_at(s.meta.created_at).title(s.title))
572            .collect();
573
574        info!("Found {} sessions", sessions.len());
575        Ok(ListSessionsResponse::new(sessions))
576    }
577
578    pub async fn load_session(
579        &self,
580        args: LoadSessionRequest,
581        cx: &ConnectionTo<Client>,
582    ) -> Result<LoadSessionResponse, acp::Error> {
583        let session_id = args.session_id.0.to_string();
584        info!("Loading session: {session_id}");
585
586        let (meta, events) = self.session_store.load(&session_id).ok_or_else(|| {
587            error!("Session not found: {session_id}");
588            acp::Error::invalid_params()
589        })?;
590
591        let context = Context::from_events(&events);
592        let mode_catalog = self.load_mode_catalog(&args.cwd).await?;
593
594        let spec = if let Some(mode_name) = meta.selected_mode.as_deref() {
595            resolve_agent_spec(&mode_catalog.catalog, mode_name)?
596        } else {
597            let parsed_model: LlmModel = meta.model.parse().map_err(|e: String| {
598                error!("Failed to parse restored model '{}': {e}", meta.model);
599                acp::Error::invalid_params()
600            })?;
601            AgentSpec::default_spec(&parsed_model, None, Vec::new())
602        };
603
604        let model = spec.model.clone();
605
606        let restored_messages: Vec<_> = context.messages().iter().filter(|m| !m.is_system()).cloned().collect();
607
608        let session = Session::new(
609            spec,
610            args.cwd.clone(),
611            map_acp_mcp_servers(args.mcp_servers),
612            Some(restored_messages),
613            Some(session_id.clone()),
614        )
615        .await
616        .map_err(|e| {
617            error!("Failed to create session for load: {e}");
618            acp::Error::internal_error()
619        })?;
620
621        let available_commands = session.list_available_commands().await.map_err(|e| {
622            error!("Failed to list available commands: {e}");
623            acp::Error::internal_error()
624        })?;
625
626        let acp_session_id = acp::SessionId::new(session_id.clone());
627
628        let config_options = self
629            .register_session(
630                session,
631                &session_id,
632                &acp_session_id,
633                &model,
634                meta.selected_mode,
635                None,
636                mode_catalog.modes,
637                cx,
638            )
639            .await;
640
641        info!("Session {session_id} loaded successfully");
642
643        let response = LoadSessionResponse::new().config_options(config_options);
644
645        let cx_clone = cx.clone();
646        let replay_session_id = acp_session_id.clone();
647        spawn(async move {
648            replay_to_client(&events, &cx_clone, &replay_session_id).await;
649        });
650
651        Self::send_available_commands_notification(available_commands, acp_session_id, &session_id, cx);
652
653        Ok(response)
654    }
655
656    pub async fn prompt(&self, args: acp::PromptRequest) -> Result<acp::PromptResponse, acp::Error> {
657        info!("Received prompt for session: {:?}", args.session_id);
658        let session_id_str = args.session_id.0.to_string();
659        let content = map_acp_to_content_blocks(args.prompt);
660
661        let model = self.registry.effective_model(&session_id_str).await.ok_or_else(|| {
662            error!("Session not found: {}", session_id_str);
663            acp::Error::invalid_params()
664        })?;
665        validate_prompt_support(&model, &content)?;
666
667        let dispatch = self.registry.begin_prompt(&session_id_str).await.ok_or_else(|| {
668            error!("Session not found: {}", session_id_str);
669            acp::Error::invalid_params()
670        })?;
671
672        let (result_tx, result_rx) = oneshot::channel();
673        dispatch
674            .relay_tx
675            .send(SessionCommand::Prompt {
676                content,
677                switch_model: dispatch.switch_model,
678                reasoning_effort: dispatch.reasoning_effort,
679                result_tx,
680            })
681            .await
682            .map_err(|_| {
683                error!("Relay channel closed for session {}", session_id_str);
684                acp::Error::internal_error()
685            })?;
686
687        let stop_reason = result_rx
688            .await
689            .map_err(|_| {
690                error!("Relay dropped result channel for session {}", session_id_str);
691                acp::Error::internal_error()
692            })?
693            .map_err(|e| {
694                error!("Relay error for session {}: {}", session_id_str, e);
695                acp::Error::internal_error()
696            })?;
697
698        info!("Prompt completed with stop reason: {:?}", stop_reason);
699        Ok(PromptResponse::new(stop_reason))
700    }
701
702    pub async fn cancel(&self, args: acp::CancelNotification) -> Result<(), acp::Error> {
703        info!("Received cancel for session: {:?}", args.session_id);
704        let session_id_str = args.session_id.0.to_string();
705        let relay = self.registry.relay(&session_id_str).await.ok_or_else(|| {
706            error!("Session not found for cancel: {}", session_id_str);
707            acp::Error::invalid_params()
708        })?;
709
710        relay.cmd.send(SessionCommand::Cancel).await.map_err(|_| {
711            error!("Relay channel closed for cancel: {}", session_id_str);
712            acp::Error::internal_error()
713        })?;
714
715        Ok(())
716    }
717
718    pub async fn set_session_config_option(
719        &self,
720        args: SetSessionConfigOptionRequest,
721    ) -> Result<SetSessionConfigOptionResponse, acp::Error> {
722        let session_id_str = args.session_id.0.to_string();
723        let config_id = args.config_id.0.to_string();
724        let value = args.value.0.to_string();
725
726        info!("set_session_config_option: session={}, config={}, value={}", session_id_str, config_id, value);
727
728        let setting = ConfigSetting::parse(&config_id, &value).map_err(|e| {
729            error!("{e}");
730            acp::Error::invalid_params()
731        })?;
732
733        let available = get_local_models().await;
734        let all_models = get_all_models(&available);
735
736        let snapshot =
737            self.registry.apply_config_change(&session_id_str, &setting, &available).await.ok_or_else(|| {
738                error!("Session not found: {}", session_id_str);
739                acp::Error::invalid_params()
740            })??;
741
742        let options = options_from_snapshot(&snapshot, &available, &all_models, &OAuthCredentialStore::default());
743        Ok(SetSessionConfigOptionResponse::new(options))
744    }
745
746    pub async fn on_mcp_request(&self, request: McpRequest) -> Result<(), acp::Error> {
747        info!("Received MCP ext request: {:?}", request);
748        match request {
749            McpRequest::Authenticate { session_id, server_name } => {
750                let relay = self.registry.relay(&session_id).await.ok_or_else(|| {
751                    error!("Session not found for authenticate_mcp_server: {}", session_id);
752                    acp::Error::invalid_params()
753                })?;
754
755                relay.mcp_request.send(McpRequest::Authenticate { session_id, server_name }).await.map_err(|_| {
756                    error!("MCP request channel closed for session");
757                    acp::Error::internal_error()
758                })?;
759            }
760        }
761
762        Ok(())
763    }
764}