acp.rs

   1use acp_thread::AgentConnection;
   2use acp_tools::AcpConnectionRegistry;
   3use action_log::ActionLog;
   4use agent_client_protocol::{self as acp, Agent as _, ErrorCode};
   5use anyhow::anyhow;
   6use collections::HashMap;
   7use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};
   8use futures::AsyncBufReadExt as _;
   9use futures::io::BufReader;
  10use project::Project;
  11use project::agent_server_store::AgentServerCommand;
  12use serde::Deserialize;
  13use settings::Settings as _;
  14use task::ShellBuilder;
  15use util::ResultExt as _;
  16use util::process::Child;
  17
  18use std::path::PathBuf;
  19use std::process::Stdio;
  20use std::{any::Any, cell::RefCell};
  21use std::{path::Path, rc::Rc};
  22use thiserror::Error;
  23
  24use anyhow::{Context as _, Result};
  25use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Task, WeakEntity};
  26
  27use acp_thread::{AcpThread, AuthRequired, LoadError, TerminalProviderEvent};
  28use terminal::TerminalBuilder;
  29use terminal::terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
  30
  31#[derive(Debug, Error)]
  32#[error("Unsupported version")]
  33pub struct UnsupportedVersion;
  34
  35pub struct AcpConnection {
  36    server_name: SharedString,
  37    telemetry_id: SharedString,
  38    connection: Rc<acp::ClientSideConnection>,
  39    sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
  40    auth_methods: Vec<acp::AuthMethod>,
  41    agent_capabilities: acp::AgentCapabilities,
  42    default_mode: Option<acp::SessionModeId>,
  43    default_model: Option<acp::ModelId>,
  44    default_config_options: HashMap<String, String>,
  45    root_dir: PathBuf,
  46    child: Child,
  47    _io_task: Task<Result<(), acp::Error>>,
  48    _wait_task: Task<Result<()>>,
  49    _stderr_task: Task<Result<()>>,
  50}
  51
  52struct ConfigOptions {
  53    config_options: Rc<RefCell<Vec<acp::SessionConfigOption>>>,
  54    tx: Rc<RefCell<watch::Sender<()>>>,
  55    rx: watch::Receiver<()>,
  56}
  57
  58impl ConfigOptions {
  59    fn new(config_options: Rc<RefCell<Vec<acp::SessionConfigOption>>>) -> Self {
  60        let (tx, rx) = watch::channel(());
  61        Self {
  62            config_options,
  63            tx: Rc::new(RefCell::new(tx)),
  64            rx,
  65        }
  66    }
  67}
  68
  69pub struct AcpSession {
  70    thread: WeakEntity<AcpThread>,
  71    suppress_abort_err: bool,
  72    models: Option<Rc<RefCell<acp::SessionModelState>>>,
  73    session_modes: Option<Rc<RefCell<acp::SessionModeState>>>,
  74    config_options: Option<ConfigOptions>,
  75}
  76
  77pub async fn connect(
  78    server_name: SharedString,
  79    command: AgentServerCommand,
  80    root_dir: &Path,
  81    default_mode: Option<acp::SessionModeId>,
  82    default_model: Option<acp::ModelId>,
  83    default_config_options: HashMap<String, String>,
  84    is_remote: bool,
  85    cx: &mut AsyncApp,
  86) -> Result<Rc<dyn AgentConnection>> {
  87    let conn = AcpConnection::stdio(
  88        server_name,
  89        command.clone(),
  90        root_dir,
  91        default_mode,
  92        default_model,
  93        default_config_options,
  94        is_remote,
  95        cx,
  96    )
  97    .await?;
  98    Ok(Rc::new(conn) as _)
  99}
 100
 101const MINIMUM_SUPPORTED_VERSION: acp::ProtocolVersion = acp::ProtocolVersion::V1;
 102
 103impl AcpConnection {
 104    pub async fn stdio(
 105        server_name: SharedString,
 106        command: AgentServerCommand,
 107        root_dir: &Path,
 108        default_mode: Option<acp::SessionModeId>,
 109        default_model: Option<acp::ModelId>,
 110        default_config_options: HashMap<String, String>,
 111        is_remote: bool,
 112        cx: &mut AsyncApp,
 113    ) -> Result<Self> {
 114        let shell = cx.update(|cx| TerminalSettings::get(None, cx).shell.clone())?;
 115        let builder = ShellBuilder::new(&shell, cfg!(windows)).non_interactive();
 116        let mut child =
 117            builder.build_std_command(Some(command.path.display().to_string()), &command.args);
 118        child.envs(command.env.iter().flatten());
 119        if !is_remote {
 120            child.current_dir(root_dir);
 121        }
 122        let mut child = Child::spawn(child, Stdio::piped(), Stdio::piped(), Stdio::piped())?;
 123
 124        let stdout = child.stdout.take().context("Failed to take stdout")?;
 125        let stdin = child.stdin.take().context("Failed to take stdin")?;
 126        let stderr = child.stderr.take().context("Failed to take stderr")?;
 127        log::debug!(
 128            "Spawning external agent server: {:?}, {:?}",
 129            command.path,
 130            command.args
 131        );
 132        log::trace!("Spawned (pid: {})", child.id());
 133
 134        let sessions = Rc::new(RefCell::new(HashMap::default()));
 135
 136        let (release_channel, version) = cx.update(|cx| {
 137            (
 138                release_channel::ReleaseChannel::try_global(cx)
 139                    .map(|release_channel| release_channel.display_name()),
 140                release_channel::AppVersion::global(cx).to_string(),
 141            )
 142        })?;
 143
 144        let client = ClientDelegate {
 145            sessions: sessions.clone(),
 146            cx: cx.clone(),
 147        };
 148        let (connection, io_task) = acp::ClientSideConnection::new(client, stdin, stdout, {
 149            let foreground_executor = cx.foreground_executor().clone();
 150            move |fut| {
 151                foreground_executor.spawn(fut).detach();
 152            }
 153        });
 154
 155        let io_task = cx.background_spawn(io_task);
 156
 157        let stderr_task = cx.background_spawn(async move {
 158            let mut stderr = BufReader::new(stderr);
 159            let mut line = String::new();
 160            while let Ok(n) = stderr.read_line(&mut line).await
 161                && n > 0
 162            {
 163                log::warn!("agent stderr: {}", line.trim());
 164                line.clear();
 165            }
 166            Ok(())
 167        });
 168
 169        let wait_task = cx.spawn({
 170            let sessions = sessions.clone();
 171            let status_fut = child.status();
 172            async move |cx| {
 173                let status = status_fut.await?;
 174
 175                for session in sessions.borrow().values() {
 176                    session
 177                        .thread
 178                        .update(cx, |thread, cx| {
 179                            thread.emit_load_error(LoadError::Exited { status }, cx)
 180                        })
 181                        .ok();
 182                }
 183
 184                anyhow::Ok(())
 185            }
 186        });
 187
 188        let connection = Rc::new(connection);
 189
 190        cx.update(|cx| {
 191            AcpConnectionRegistry::default_global(cx).update(cx, |registry, cx| {
 192                registry.set_active_connection(server_name.clone(), &connection, cx)
 193            });
 194        })?;
 195
 196        let response = connection
 197            .initialize(
 198                acp::InitializeRequest::new(acp::ProtocolVersion::V1)
 199                    .client_capabilities(
 200                        acp::ClientCapabilities::new()
 201                            .fs(acp::FileSystemCapability::new()
 202                                .read_text_file(true)
 203                                .write_text_file(true))
 204                            .terminal(true)
 205                            // Experimental: Allow for rendering terminal output from the agents
 206                            .meta(acp::Meta::from_iter([
 207                                ("terminal_output".into(), true.into()),
 208                                ("terminal-auth".into(), true.into()),
 209                            ])),
 210                    )
 211                    .client_info(
 212                        acp::Implementation::new("zed", version)
 213                            .title(release_channel.map(ToOwned::to_owned)),
 214                    ),
 215            )
 216            .await?;
 217
 218        if response.protocol_version < MINIMUM_SUPPORTED_VERSION {
 219            return Err(UnsupportedVersion.into());
 220        }
 221
 222        let telemetry_id = response
 223            .agent_info
 224            // Use the one the agent provides if we have one
 225            .map(|info| info.name.into())
 226            // Otherwise, just use the name
 227            .unwrap_or_else(|| server_name.clone());
 228
 229        Ok(Self {
 230            auth_methods: response.auth_methods,
 231            root_dir: root_dir.to_owned(),
 232            connection,
 233            server_name,
 234            telemetry_id,
 235            sessions,
 236            agent_capabilities: response.agent_capabilities,
 237            default_mode,
 238            default_model,
 239            default_config_options,
 240            _io_task: io_task,
 241            _wait_task: wait_task,
 242            _stderr_task: stderr_task,
 243            child,
 244        })
 245    }
 246
 247    pub fn prompt_capabilities(&self) -> &acp::PromptCapabilities {
 248        &self.agent_capabilities.prompt_capabilities
 249    }
 250
 251    pub fn root_dir(&self) -> &Path {
 252        &self.root_dir
 253    }
 254}
 255
 256impl Drop for AcpConnection {
 257    fn drop(&mut self) {
 258        self.child.kill().log_err();
 259    }
 260}
 261
 262impl AgentConnection for AcpConnection {
 263    fn telemetry_id(&self) -> SharedString {
 264        self.telemetry_id.clone()
 265    }
 266
 267    fn new_thread(
 268        self: Rc<Self>,
 269        project: Entity<Project>,
 270        cwd: &Path,
 271        cx: &mut App,
 272    ) -> Task<Result<Entity<AcpThread>>> {
 273        let name = self.server_name.clone();
 274        let conn = self.connection.clone();
 275        let sessions = self.sessions.clone();
 276        let default_mode = self.default_mode.clone();
 277        let default_model = self.default_model.clone();
 278        let default_config_options = self.default_config_options.clone();
 279        let cwd = cwd.to_path_buf();
 280        let context_server_store = project.read(cx).context_server_store().read(cx);
 281        let mcp_servers = if project.read(cx).is_local() {
 282            context_server_store
 283                .configured_server_ids()
 284                .iter()
 285                .filter_map(|id| {
 286                    let configuration = context_server_store.configuration_for_server(id)?;
 287                    match &*configuration {
 288                        project::context_server_store::ContextServerConfiguration::Custom {
 289                            command,
 290                            ..
 291                        }
 292                        | project::context_server_store::ContextServerConfiguration::Extension {
 293                            command,
 294                            ..
 295                        } => Some(acp::McpServer::Stdio(
 296                            acp::McpServerStdio::new(id.0.to_string(), &command.path)
 297                                .args(command.args.clone())
 298                                .env(if let Some(env) = command.env.as_ref() {
 299                                    env.iter()
 300                                        .map(|(name, value)| acp::EnvVariable::new(name, value))
 301                                        .collect()
 302                                } else {
 303                                    vec![]
 304                                }),
 305                        )),
 306                        project::context_server_store::ContextServerConfiguration::Http {
 307                            url,
 308                            headers,
 309                        } => Some(acp::McpServer::Http(
 310                            acp::McpServerHttp::new(id.0.to_string(), url.to_string()).headers(
 311                                headers
 312                                    .iter()
 313                                    .map(|(name, value)| acp::HttpHeader::new(name, value))
 314                                    .collect(),
 315                            ),
 316                        )),
 317                    }
 318                })
 319                .collect()
 320        } else {
 321            // In SSH projects, the external agent is running on the remote
 322            // machine, and currently we only run MCP servers on the local
 323            // machine. So don't pass any MCP servers to the agent in that case.
 324            Vec::new()
 325        };
 326
 327        cx.spawn(async move |cx| {
 328            let response = conn
 329                .new_session(acp::NewSessionRequest::new(cwd).mcp_servers(mcp_servers))
 330                .await
 331                .map_err(|err| {
 332                    if err.code == acp::ErrorCode::AuthRequired {
 333                        let mut error = AuthRequired::new();
 334
 335                        if err.message != acp::ErrorCode::AuthRequired.to_string() {
 336                            error = error.with_description(err.message);
 337                        }
 338
 339                        anyhow!(error)
 340                    } else {
 341                        anyhow!(err)
 342                    }
 343                })?;
 344
 345            let use_config_options = cx.update(|cx| cx.has_flag::<AcpBetaFeatureFlag>())?;
 346
 347            // Config options take precedence over legacy modes/models
 348            let (modes, models, config_options) = if use_config_options && let Some(opts) = response.config_options {
 349                (
 350                    None,
 351                    None,
 352                    Some(Rc::new(RefCell::new(opts))),
 353                )
 354            } else {
 355                // Fall back to legacy modes/models
 356                let modes = response.modes.map(|modes| Rc::new(RefCell::new(modes)));
 357                let models = response.models.map(|models| Rc::new(RefCell::new(models)));
 358                (modes, models, None)
 359            };
 360
 361            if let Some(default_mode) = default_mode {
 362                if let Some(modes) = modes.as_ref() {
 363                    let mut modes_ref = modes.borrow_mut();
 364                    let has_mode = modes_ref.available_modes.iter().any(|mode| mode.id == default_mode);
 365
 366                    if has_mode {
 367                        let initial_mode_id = modes_ref.current_mode_id.clone();
 368
 369                        cx.spawn({
 370                            let default_mode = default_mode.clone();
 371                            let session_id = response.session_id.clone();
 372                            let modes = modes.clone();
 373                            let conn = conn.clone();
 374                            async move |_| {
 375                                let result = conn.set_session_mode(acp::SetSessionModeRequest::new(session_id, default_mode))
 376                                .await.log_err();
 377
 378                                if result.is_none() {
 379                                    modes.borrow_mut().current_mode_id = initial_mode_id;
 380                                }
 381                            }
 382                        }).detach();
 383
 384                        modes_ref.current_mode_id = default_mode;
 385                    } else {
 386                        let available_modes = modes_ref
 387                            .available_modes
 388                            .iter()
 389                            .map(|mode| format!("- `{}`: {}", mode.id, mode.name))
 390                            .collect::<Vec<_>>()
 391                            .join("\n");
 392
 393                        log::warn!(
 394                            "`{default_mode}` is not valid {name} mode. Available options:\n{available_modes}",
 395                        );
 396                    }
 397                } else {
 398                    log::warn!(
 399                        "`{name}` does not support modes, but `default_mode` was set in settings.",
 400                    );
 401                }
 402            }
 403
 404            if let Some(default_model) = default_model {
 405                if let Some(models) = models.as_ref() {
 406                    let mut models_ref = models.borrow_mut();
 407                    let has_model = models_ref.available_models.iter().any(|model| model.model_id == default_model);
 408
 409                    if has_model {
 410                        let initial_model_id = models_ref.current_model_id.clone();
 411
 412                        cx.spawn({
 413                            let default_model = default_model.clone();
 414                            let session_id = response.session_id.clone();
 415                            let models = models.clone();
 416                            let conn = conn.clone();
 417                            async move |_| {
 418                                let result = conn.set_session_model(acp::SetSessionModelRequest::new(session_id, default_model))
 419                                .await.log_err();
 420
 421                                if result.is_none() {
 422                                    models.borrow_mut().current_model_id = initial_model_id;
 423                                }
 424                            }
 425                        }).detach();
 426
 427                        models_ref.current_model_id = default_model;
 428                    } else {
 429                        let available_models = models_ref
 430                            .available_models
 431                            .iter()
 432                            .map(|model| format!("- `{}`: {}", model.model_id, model.name))
 433                            .collect::<Vec<_>>()
 434                            .join("\n");
 435
 436                        log::warn!(
 437                            "`{default_model}` is not a valid {name} model. Available options:\n{available_models}",
 438                        );
 439                    }
 440                } else {
 441                    log::warn!(
 442                        "`{name}` does not support model selection, but `default_model` was set in settings.",
 443                    );
 444                }
 445            }
 446
 447            if let Some(config_opts) = config_options.as_ref() {
 448                let defaults_to_apply: Vec<_> = {
 449                    let config_opts_ref = config_opts.borrow();
 450                    config_opts_ref
 451                        .iter()
 452                        .filter_map(|config_option| {
 453                            let default_value = default_config_options.get(&*config_option.id.0)?;
 454
 455                            let is_valid = match &config_option.kind {
 456                                acp::SessionConfigKind::Select(select) => match &select.options {
 457                                    acp::SessionConfigSelectOptions::Ungrouped(options) => {
 458                                        options.iter().any(|opt| &*opt.value.0 == default_value.as_str())
 459                                    }
 460                                    acp::SessionConfigSelectOptions::Grouped(groups) => groups
 461                                        .iter()
 462                                        .any(|g| g.options.iter().any(|opt| &*opt.value.0 == default_value.as_str())),
 463                                    _ => false,
 464                                },
 465                                _ => false,
 466                            };
 467
 468                            if is_valid {
 469                                let initial_value = match &config_option.kind {
 470                                    acp::SessionConfigKind::Select(select) => {
 471                                        Some(select.current_value.clone())
 472                                    }
 473                                    _ => None,
 474                                };
 475                                Some((config_option.id.clone(), default_value.clone(), initial_value))
 476                            } else {
 477                                log::warn!(
 478                                    "`{}` is not a valid value for config option `{}` in {}",
 479                                    default_value,
 480                                    config_option.id.0,
 481                                    name
 482                                );
 483                                None
 484                            }
 485                        })
 486                        .collect()
 487                };
 488
 489                for (config_id, default_value, initial_value) in defaults_to_apply {
 490                    cx.spawn({
 491                        let default_value_id = acp::SessionConfigValueId::new(default_value.clone());
 492                        let session_id = response.session_id.clone();
 493                        let config_id_clone = config_id.clone();
 494                        let config_opts = config_opts.clone();
 495                        let conn = conn.clone();
 496                        async move |_| {
 497                            let result = conn
 498                                .set_session_config_option(
 499                                    acp::SetSessionConfigOptionRequest::new(
 500                                        session_id,
 501                                        config_id_clone.clone(),
 502                                        default_value_id,
 503                                    ),
 504                                )
 505                                .await
 506                                .log_err();
 507
 508                            if result.is_none() {
 509                                if let Some(initial) = initial_value {
 510                                    let mut opts = config_opts.borrow_mut();
 511                                    if let Some(opt) = opts.iter_mut().find(|o| o.id == config_id_clone) {
 512                                        if let acp::SessionConfigKind::Select(select) =
 513                                            &mut opt.kind
 514                                        {
 515                                            select.current_value = initial;
 516                                        }
 517                                    }
 518                                }
 519                            }
 520                        }
 521                    })
 522                    .detach();
 523
 524                    let mut opts = config_opts.borrow_mut();
 525                    if let Some(opt) = opts.iter_mut().find(|o| o.id == config_id) {
 526                        if let acp::SessionConfigKind::Select(select) = &mut opt.kind {
 527                            select.current_value = acp::SessionConfigValueId::new(default_value);
 528                        }
 529                    }
 530                }
 531            }
 532
 533            let session_id = response.session_id;
 534            let action_log = cx.new(|_| ActionLog::new(project.clone()))?;
 535            let thread = cx.new(|cx| {
 536                AcpThread::new(
 537                    self.server_name.clone(),
 538                    self.clone(),
 539                    project,
 540                    action_log,
 541                    session_id.clone(),
 542                    // ACP doesn't currently support per-session prompt capabilities or changing capabilities dynamically.
 543                    watch::Receiver::constant(self.agent_capabilities.prompt_capabilities.clone()),
 544                    cx,
 545                )
 546            })?;
 547
 548
 549            let session = AcpSession {
 550                thread: thread.downgrade(),
 551                suppress_abort_err: false,
 552                session_modes: modes,
 553                models,
 554                config_options: config_options.map(|opts| ConfigOptions::new(opts))
 555            };
 556            sessions.borrow_mut().insert(session_id, session);
 557
 558            Ok(thread)
 559        })
 560    }
 561
 562    fn auth_methods(&self) -> &[acp::AuthMethod] {
 563        &self.auth_methods
 564    }
 565
 566    fn authenticate(&self, method_id: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>> {
 567        let conn = self.connection.clone();
 568        cx.foreground_executor().spawn(async move {
 569            conn.authenticate(acp::AuthenticateRequest::new(method_id))
 570                .await?;
 571            Ok(())
 572        })
 573    }
 574
 575    fn prompt(
 576        &self,
 577        _id: Option<acp_thread::UserMessageId>,
 578        params: acp::PromptRequest,
 579        cx: &mut App,
 580    ) -> Task<Result<acp::PromptResponse>> {
 581        let conn = self.connection.clone();
 582        let sessions = self.sessions.clone();
 583        let session_id = params.session_id.clone();
 584        cx.foreground_executor().spawn(async move {
 585            let result = conn.prompt(params).await;
 586
 587            let mut suppress_abort_err = false;
 588
 589            if let Some(session) = sessions.borrow_mut().get_mut(&session_id) {
 590                suppress_abort_err = session.suppress_abort_err;
 591                session.suppress_abort_err = false;
 592            }
 593
 594            match result {
 595                Ok(response) => Ok(response),
 596                Err(err) => {
 597                    if err.code == acp::ErrorCode::AuthRequired {
 598                        return Err(anyhow!(acp::Error::auth_required()));
 599                    }
 600
 601                    if err.code != ErrorCode::InternalError {
 602                        anyhow::bail!(err)
 603                    }
 604
 605                    let Some(data) = &err.data else {
 606                        anyhow::bail!(err)
 607                    };
 608
 609                    // Temporary workaround until the following PR is generally available:
 610                    // https://github.com/google-gemini/gemini-cli/pull/6656
 611
 612                    #[derive(Deserialize)]
 613                    #[serde(deny_unknown_fields)]
 614                    struct ErrorDetails {
 615                        details: Box<str>,
 616                    }
 617
 618                    match serde_json::from_value(data.clone()) {
 619                        Ok(ErrorDetails { details }) => {
 620                            if suppress_abort_err
 621                                && (details.contains("This operation was aborted")
 622                                    || details.contains("The user aborted a request"))
 623                            {
 624                                Ok(acp::PromptResponse::new(acp::StopReason::Cancelled))
 625                            } else {
 626                                Err(anyhow!(details))
 627                            }
 628                        }
 629                        Err(_) => Err(anyhow!(err)),
 630                    }
 631                }
 632            }
 633        })
 634    }
 635
 636    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
 637        if let Some(session) = self.sessions.borrow_mut().get_mut(session_id) {
 638            session.suppress_abort_err = true;
 639        }
 640        let conn = self.connection.clone();
 641        let params = acp::CancelNotification::new(session_id.clone());
 642        cx.foreground_executor()
 643            .spawn(async move { conn.cancel(params).await })
 644            .detach();
 645    }
 646
 647    fn session_modes(
 648        &self,
 649        session_id: &acp::SessionId,
 650        _cx: &App,
 651    ) -> Option<Rc<dyn acp_thread::AgentSessionModes>> {
 652        let sessions = self.sessions.clone();
 653        let sessions_ref = sessions.borrow();
 654        let Some(session) = sessions_ref.get(session_id) else {
 655            return None;
 656        };
 657
 658        if let Some(modes) = session.session_modes.as_ref() {
 659            Some(Rc::new(AcpSessionModes {
 660                connection: self.connection.clone(),
 661                session_id: session_id.clone(),
 662                state: modes.clone(),
 663            }) as _)
 664        } else {
 665            None
 666        }
 667    }
 668
 669    fn model_selector(
 670        &self,
 671        session_id: &acp::SessionId,
 672    ) -> Option<Rc<dyn acp_thread::AgentModelSelector>> {
 673        let sessions = self.sessions.clone();
 674        let sessions_ref = sessions.borrow();
 675        let Some(session) = sessions_ref.get(session_id) else {
 676            return None;
 677        };
 678
 679        if let Some(models) = session.models.as_ref() {
 680            Some(Rc::new(AcpModelSelector::new(
 681                session_id.clone(),
 682                self.connection.clone(),
 683                models.clone(),
 684            )) as _)
 685        } else {
 686            None
 687        }
 688    }
 689
 690    fn session_config_options(
 691        &self,
 692        session_id: &acp::SessionId,
 693        _cx: &App,
 694    ) -> Option<Rc<dyn acp_thread::AgentSessionConfigOptions>> {
 695        let sessions = self.sessions.borrow();
 696        let session = sessions.get(session_id)?;
 697
 698        let config_opts = session.config_options.as_ref()?;
 699
 700        Some(Rc::new(AcpSessionConfigOptions {
 701            session_id: session_id.clone(),
 702            connection: self.connection.clone(),
 703            state: config_opts.config_options.clone(),
 704            watch_tx: config_opts.tx.clone(),
 705            watch_rx: config_opts.rx.clone(),
 706        }) as _)
 707    }
 708
 709    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
 710        self
 711    }
 712}
 713
 714struct AcpSessionModes {
 715    session_id: acp::SessionId,
 716    connection: Rc<acp::ClientSideConnection>,
 717    state: Rc<RefCell<acp::SessionModeState>>,
 718}
 719
 720impl acp_thread::AgentSessionModes for AcpSessionModes {
 721    fn current_mode(&self) -> acp::SessionModeId {
 722        self.state.borrow().current_mode_id.clone()
 723    }
 724
 725    fn all_modes(&self) -> Vec<acp::SessionMode> {
 726        self.state.borrow().available_modes.clone()
 727    }
 728
 729    fn set_mode(&self, mode_id: acp::SessionModeId, cx: &mut App) -> Task<Result<()>> {
 730        let connection = self.connection.clone();
 731        let session_id = self.session_id.clone();
 732        let old_mode_id;
 733        {
 734            let mut state = self.state.borrow_mut();
 735            old_mode_id = state.current_mode_id.clone();
 736            state.current_mode_id = mode_id.clone();
 737        };
 738        let state = self.state.clone();
 739        cx.foreground_executor().spawn(async move {
 740            let result = connection
 741                .set_session_mode(acp::SetSessionModeRequest::new(session_id, mode_id))
 742                .await;
 743
 744            if result.is_err() {
 745                state.borrow_mut().current_mode_id = old_mode_id;
 746            }
 747
 748            result?;
 749
 750            Ok(())
 751        })
 752    }
 753}
 754
 755struct AcpModelSelector {
 756    session_id: acp::SessionId,
 757    connection: Rc<acp::ClientSideConnection>,
 758    state: Rc<RefCell<acp::SessionModelState>>,
 759}
 760
 761impl AcpModelSelector {
 762    fn new(
 763        session_id: acp::SessionId,
 764        connection: Rc<acp::ClientSideConnection>,
 765        state: Rc<RefCell<acp::SessionModelState>>,
 766    ) -> Self {
 767        Self {
 768            session_id,
 769            connection,
 770            state,
 771        }
 772    }
 773}
 774
 775impl acp_thread::AgentModelSelector for AcpModelSelector {
 776    fn list_models(&self, _cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
 777        Task::ready(Ok(acp_thread::AgentModelList::Flat(
 778            self.state
 779                .borrow()
 780                .available_models
 781                .clone()
 782                .into_iter()
 783                .map(acp_thread::AgentModelInfo::from)
 784                .collect(),
 785        )))
 786    }
 787
 788    fn select_model(&self, model_id: acp::ModelId, cx: &mut App) -> Task<Result<()>> {
 789        let connection = self.connection.clone();
 790        let session_id = self.session_id.clone();
 791        let old_model_id;
 792        {
 793            let mut state = self.state.borrow_mut();
 794            old_model_id = state.current_model_id.clone();
 795            state.current_model_id = model_id.clone();
 796        };
 797        let state = self.state.clone();
 798        cx.foreground_executor().spawn(async move {
 799            let result = connection
 800                .set_session_model(acp::SetSessionModelRequest::new(session_id, model_id))
 801                .await;
 802
 803            if result.is_err() {
 804                state.borrow_mut().current_model_id = old_model_id;
 805            }
 806
 807            result?;
 808
 809            Ok(())
 810        })
 811    }
 812
 813    fn selected_model(&self, _cx: &mut App) -> Task<Result<acp_thread::AgentModelInfo>> {
 814        let state = self.state.borrow();
 815        Task::ready(
 816            state
 817                .available_models
 818                .iter()
 819                .find(|m| m.model_id == state.current_model_id)
 820                .cloned()
 821                .map(acp_thread::AgentModelInfo::from)
 822                .ok_or_else(|| anyhow::anyhow!("Model not found")),
 823        )
 824    }
 825}
 826
 827struct AcpSessionConfigOptions {
 828    session_id: acp::SessionId,
 829    connection: Rc<acp::ClientSideConnection>,
 830    state: Rc<RefCell<Vec<acp::SessionConfigOption>>>,
 831    watch_tx: Rc<RefCell<watch::Sender<()>>>,
 832    watch_rx: watch::Receiver<()>,
 833}
 834
 835impl acp_thread::AgentSessionConfigOptions for AcpSessionConfigOptions {
 836    fn config_options(&self) -> Vec<acp::SessionConfigOption> {
 837        self.state.borrow().clone()
 838    }
 839
 840    fn set_config_option(
 841        &self,
 842        config_id: acp::SessionConfigId,
 843        value: acp::SessionConfigValueId,
 844        cx: &mut App,
 845    ) -> Task<Result<Vec<acp::SessionConfigOption>>> {
 846        let connection = self.connection.clone();
 847        let session_id = self.session_id.clone();
 848        let state = self.state.clone();
 849
 850        let watch_tx = self.watch_tx.clone();
 851
 852        cx.foreground_executor().spawn(async move {
 853            let response = connection
 854                .set_session_config_option(acp::SetSessionConfigOptionRequest::new(
 855                    session_id, config_id, value,
 856                ))
 857                .await?;
 858
 859            *state.borrow_mut() = response.config_options.clone();
 860            watch_tx.borrow_mut().send(()).ok();
 861            Ok(response.config_options)
 862        })
 863    }
 864
 865    fn watch(&self, _cx: &mut App) -> Option<watch::Receiver<()>> {
 866        Some(self.watch_rx.clone())
 867    }
 868}
 869
 870struct ClientDelegate {
 871    sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
 872    cx: AsyncApp,
 873}
 874
 875#[async_trait::async_trait(?Send)]
 876impl acp::Client for ClientDelegate {
 877    async fn request_permission(
 878        &self,
 879        arguments: acp::RequestPermissionRequest,
 880    ) -> Result<acp::RequestPermissionResponse, acp::Error> {
 881        let respect_always_allow_setting;
 882        let thread;
 883        {
 884            let sessions_ref = self.sessions.borrow();
 885            let session = sessions_ref
 886                .get(&arguments.session_id)
 887                .context("Failed to get session")?;
 888            respect_always_allow_setting = session.session_modes.is_none();
 889            thread = session.thread.clone();
 890        }
 891
 892        let cx = &mut self.cx.clone();
 893
 894        let task = thread.update(cx, |thread, cx| {
 895            thread.request_tool_call_authorization(
 896                arguments.tool_call,
 897                arguments.options,
 898                respect_always_allow_setting,
 899                cx,
 900            )
 901        })??;
 902
 903        let outcome = task.await;
 904
 905        Ok(acp::RequestPermissionResponse::new(outcome))
 906    }
 907
 908    async fn write_text_file(
 909        &self,
 910        arguments: acp::WriteTextFileRequest,
 911    ) -> Result<acp::WriteTextFileResponse, acp::Error> {
 912        let cx = &mut self.cx.clone();
 913        let task = self
 914            .session_thread(&arguments.session_id)?
 915            .update(cx, |thread, cx| {
 916                thread.write_text_file(arguments.path, arguments.content, cx)
 917            })?;
 918
 919        task.await?;
 920
 921        Ok(Default::default())
 922    }
 923
 924    async fn read_text_file(
 925        &self,
 926        arguments: acp::ReadTextFileRequest,
 927    ) -> Result<acp::ReadTextFileResponse, acp::Error> {
 928        let task = self.session_thread(&arguments.session_id)?.update(
 929            &mut self.cx.clone(),
 930            |thread, cx| {
 931                thread.read_text_file(arguments.path, arguments.line, arguments.limit, false, cx)
 932            },
 933        )?;
 934
 935        let content = task.await?;
 936
 937        Ok(acp::ReadTextFileResponse::new(content))
 938    }
 939
 940    async fn session_notification(
 941        &self,
 942        notification: acp::SessionNotification,
 943    ) -> Result<(), acp::Error> {
 944        let sessions = self.sessions.borrow();
 945        let session = sessions
 946            .get(&notification.session_id)
 947            .context("Failed to get session")?;
 948
 949        if let acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate {
 950            current_mode_id,
 951            ..
 952        }) = &notification.update
 953        {
 954            if let Some(session_modes) = &session.session_modes {
 955                session_modes.borrow_mut().current_mode_id = current_mode_id.clone();
 956            } else {
 957                log::error!(
 958                    "Got a `CurrentModeUpdate` notification, but they agent didn't specify `modes` during setting setup."
 959                );
 960            }
 961        }
 962
 963        if let acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate {
 964            config_options,
 965            ..
 966        }) = &notification.update
 967        {
 968            if let Some(opts) = &session.config_options {
 969                *opts.config_options.borrow_mut() = config_options.clone();
 970                opts.tx.borrow_mut().send(()).ok();
 971            } else {
 972                log::error!(
 973                    "Got a `ConfigOptionUpdate` notification, but the agent didn't specify `config_options` during session setup."
 974                );
 975            }
 976        }
 977
 978        // Clone so we can inspect meta both before and after handing off to the thread
 979        let update_clone = notification.update.clone();
 980
 981        // Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal.
 982        if let acp::SessionUpdate::ToolCall(tc) = &update_clone {
 983            if let Some(meta) = &tc.meta {
 984                if let Some(terminal_info) = meta.get("terminal_info") {
 985                    if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str())
 986                    {
 987                        let terminal_id = acp::TerminalId::new(id_str);
 988                        let cwd = terminal_info
 989                            .get("cwd")
 990                            .and_then(|v| v.as_str().map(PathBuf::from));
 991
 992                        // Create a minimal display-only lower-level terminal and register it.
 993                        let _ = session.thread.update(&mut self.cx.clone(), |thread, cx| {
 994                            let builder = TerminalBuilder::new_display_only(
 995                                CursorShape::default(),
 996                                AlternateScroll::On,
 997                                None,
 998                                0,
 999                            )?;
1000                            let lower = cx.new(|cx| builder.subscribe(cx));
1001                            thread.on_terminal_provider_event(
1002                                TerminalProviderEvent::Created {
1003                                    terminal_id,
1004                                    label: tc.title.clone(),
1005                                    cwd,
1006                                    output_byte_limit: None,
1007                                    terminal: lower,
1008                                },
1009                                cx,
1010                            );
1011                            anyhow::Ok(())
1012                        });
1013                    }
1014                }
1015            }
1016        }
1017
1018        // Forward the update to the acp_thread as usual.
1019        session.thread.update(&mut self.cx.clone(), |thread, cx| {
1020            thread.handle_session_update(notification.update.clone(), cx)
1021        })??;
1022
1023        // Post-handle: stream terminal output/exit if present on ToolCallUpdate meta.
1024        if let acp::SessionUpdate::ToolCallUpdate(tcu) = &update_clone {
1025            if let Some(meta) = &tcu.meta {
1026                if let Some(term_out) = meta.get("terminal_output") {
1027                    if let Some(id_str) = term_out.get("terminal_id").and_then(|v| v.as_str()) {
1028                        let terminal_id = acp::TerminalId::new(id_str);
1029                        if let Some(s) = term_out.get("data").and_then(|v| v.as_str()) {
1030                            let data = s.as_bytes().to_vec();
1031                            let _ = session.thread.update(&mut self.cx.clone(), |thread, cx| {
1032                                thread.on_terminal_provider_event(
1033                                    TerminalProviderEvent::Output { terminal_id, data },
1034                                    cx,
1035                                );
1036                            });
1037                        }
1038                    }
1039                }
1040
1041                // terminal_exit
1042                if let Some(term_exit) = meta.get("terminal_exit") {
1043                    if let Some(id_str) = term_exit.get("terminal_id").and_then(|v| v.as_str()) {
1044                        let terminal_id = acp::TerminalId::new(id_str);
1045                        let status = acp::TerminalExitStatus::new()
1046                            .exit_code(
1047                                term_exit
1048                                    .get("exit_code")
1049                                    .and_then(|v| v.as_u64())
1050                                    .map(|i| i as u32),
1051                            )
1052                            .signal(
1053                                term_exit
1054                                    .get("signal")
1055                                    .and_then(|v| v.as_str().map(|s| s.to_string())),
1056                            );
1057
1058                        let _ = session.thread.update(&mut self.cx.clone(), |thread, cx| {
1059                            thread.on_terminal_provider_event(
1060                                TerminalProviderEvent::Exit {
1061                                    terminal_id,
1062                                    status,
1063                                },
1064                                cx,
1065                            );
1066                        });
1067                    }
1068                }
1069            }
1070        }
1071
1072        Ok(())
1073    }
1074
1075    async fn create_terminal(
1076        &self,
1077        args: acp::CreateTerminalRequest,
1078    ) -> Result<acp::CreateTerminalResponse, acp::Error> {
1079        let thread = self.session_thread(&args.session_id)?;
1080        let project = thread.read_with(&self.cx, |thread, _cx| thread.project().clone())?;
1081
1082        let terminal_entity = acp_thread::create_terminal_entity(
1083            args.command.clone(),
1084            &args.args,
1085            args.env
1086                .into_iter()
1087                .map(|env| (env.name, env.value))
1088                .collect(),
1089            args.cwd.clone(),
1090            &project,
1091            &mut self.cx.clone(),
1092        )
1093        .await?;
1094
1095        // Register with renderer
1096        let terminal_entity = thread.update(&mut self.cx.clone(), |thread, cx| {
1097            thread.register_terminal_created(
1098                acp::TerminalId::new(uuid::Uuid::new_v4().to_string()),
1099                format!("{} {}", args.command, args.args.join(" ")),
1100                args.cwd.clone(),
1101                args.output_byte_limit,
1102                terminal_entity,
1103                cx,
1104            )
1105        })?;
1106        let terminal_id =
1107            terminal_entity.read_with(&self.cx, |terminal, _| terminal.id().clone())?;
1108        Ok(acp::CreateTerminalResponse::new(terminal_id))
1109    }
1110
1111    async fn kill_terminal_command(
1112        &self,
1113        args: acp::KillTerminalCommandRequest,
1114    ) -> Result<acp::KillTerminalCommandResponse, acp::Error> {
1115        self.session_thread(&args.session_id)?
1116            .update(&mut self.cx.clone(), |thread, cx| {
1117                thread.kill_terminal(args.terminal_id, cx)
1118            })??;
1119
1120        Ok(Default::default())
1121    }
1122
1123    async fn ext_method(&self, _args: acp::ExtRequest) -> Result<acp::ExtResponse, acp::Error> {
1124        Err(acp::Error::method_not_found())
1125    }
1126
1127    async fn ext_notification(&self, _args: acp::ExtNotification) -> Result<(), acp::Error> {
1128        Err(acp::Error::method_not_found())
1129    }
1130
1131    async fn release_terminal(
1132        &self,
1133        args: acp::ReleaseTerminalRequest,
1134    ) -> Result<acp::ReleaseTerminalResponse, acp::Error> {
1135        self.session_thread(&args.session_id)?
1136            .update(&mut self.cx.clone(), |thread, cx| {
1137                thread.release_terminal(args.terminal_id, cx)
1138            })??;
1139
1140        Ok(Default::default())
1141    }
1142
1143    async fn terminal_output(
1144        &self,
1145        args: acp::TerminalOutputRequest,
1146    ) -> Result<acp::TerminalOutputResponse, acp::Error> {
1147        self.session_thread(&args.session_id)?
1148            .read_with(&mut self.cx.clone(), |thread, cx| {
1149                let out = thread
1150                    .terminal(args.terminal_id)?
1151                    .read(cx)
1152                    .current_output(cx);
1153
1154                Ok(out)
1155            })?
1156    }
1157
1158    async fn wait_for_terminal_exit(
1159        &self,
1160        args: acp::WaitForTerminalExitRequest,
1161    ) -> Result<acp::WaitForTerminalExitResponse, acp::Error> {
1162        let exit_status = self
1163            .session_thread(&args.session_id)?
1164            .update(&mut self.cx.clone(), |thread, cx| {
1165                anyhow::Ok(thread.terminal(args.terminal_id)?.read(cx).wait_for_exit())
1166            })??
1167            .await;
1168
1169        Ok(acp::WaitForTerminalExitResponse::new(exit_status))
1170    }
1171}
1172
1173impl ClientDelegate {
1174    fn session_thread(&self, session_id: &acp::SessionId) -> Result<WeakEntity<AcpThread>> {
1175        let sessions = self.sessions.borrow();
1176        sessions
1177            .get(session_id)
1178            .context("Failed to get session")
1179            .map(|session| session.thread.clone())
1180    }
1181}