claude.rs

   1mod edit_tool;
   2mod mcp_server;
   3mod permission_tool;
   4mod read_tool;
   5pub mod tools;
   6mod write_tool;
   7
   8use action_log::ActionLog;
   9use collections::HashMap;
  10use context_server::listener::McpServerTool;
  11use language_models::provider::anthropic::AnthropicLanguageModelProvider;
  12use project::Project;
  13use settings::SettingsStore;
  14use smol::process::Child;
  15use std::any::Any;
  16use std::cell::RefCell;
  17use std::fmt::Display;
  18use std::path::{Path, PathBuf};
  19use std::rc::Rc;
  20use util::command::new_smol_command;
  21use uuid::Uuid;
  22
  23use agent_client_protocol as acp;
  24use anyhow::{Context as _, Result, anyhow};
  25use futures::channel::oneshot;
  26use futures::{AsyncBufReadExt, AsyncWriteExt};
  27use futures::{
  28    AsyncRead, AsyncWrite, FutureExt, StreamExt,
  29    channel::mpsc::{self, UnboundedReceiver, UnboundedSender},
  30    io::BufReader,
  31    select_biased,
  32};
  33use gpui::{App, AppContext, AsyncApp, Entity, SharedString, Task, WeakEntity};
  34use serde::{Deserialize, Serialize};
  35use util::{ResultExt, debug_panic};
  36
  37use crate::claude::mcp_server::{ClaudeZedMcpServer, McpConfig};
  38use crate::claude::tools::ClaudeTool;
  39use crate::{AgentServer, AgentServerCommand, AllAgentServersSettings};
  40use acp_thread::{AcpThread, AgentConnection, AuthRequired, LoadError, MentionUri};
  41
  42#[derive(Clone)]
  43pub struct ClaudeCode;
  44
  45impl AgentServer for ClaudeCode {
  46    fn telemetry_id(&self) -> &'static str {
  47        "claude-code"
  48    }
  49
  50    fn name(&self) -> SharedString {
  51        "Claude Code".into()
  52    }
  53
  54    fn empty_state_headline(&self) -> SharedString {
  55        self.name()
  56    }
  57
  58    fn empty_state_message(&self) -> SharedString {
  59        "How can I help you today?".into()
  60    }
  61
  62    fn logo(&self) -> ui::IconName {
  63        ui::IconName::AiClaude
  64    }
  65
  66    fn connect(
  67        &self,
  68        _root_dir: &Path,
  69        _project: &Entity<Project>,
  70        _cx: &mut App,
  71    ) -> Task<Result<Rc<dyn AgentConnection>>> {
  72        let connection = ClaudeAgentConnection {
  73            sessions: Default::default(),
  74        };
  75
  76        Task::ready(Ok(Rc::new(connection) as _))
  77    }
  78
  79    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
  80        self
  81    }
  82}
  83
  84struct ClaudeAgentConnection {
  85    sessions: Rc<RefCell<HashMap<acp::SessionId, ClaudeAgentSession>>>,
  86}
  87
  88impl AgentConnection for ClaudeAgentConnection {
  89    fn new_thread(
  90        self: Rc<Self>,
  91        project: Entity<Project>,
  92        cwd: &Path,
  93        cx: &mut App,
  94    ) -> Task<Result<Entity<AcpThread>>> {
  95        let cwd = cwd.to_owned();
  96        cx.spawn(async move |cx| {
  97            let settings = cx.read_global(|settings: &SettingsStore, _| {
  98                settings.get::<AllAgentServersSettings>(None).claude.clone()
  99            })?;
 100
 101            let Some(command) = AgentServerCommand::resolve(
 102                "claude",
 103                &[],
 104                Some(&util::paths::home_dir().join(".claude/local/claude")),
 105                settings,
 106                &project,
 107                cx,
 108            )
 109            .await
 110            else {
 111                return Err(LoadError::NotInstalled {
 112                    error_message: "Failed to find Claude Code binary".into(),
 113                    install_message: "Install Claude Code".into(),
 114                    install_command: "npm install -g @anthropic-ai/claude-code@latest".into(),
 115                }.into());
 116            };
 117
 118            let api_key =
 119                cx.update(AnthropicLanguageModelProvider::api_key)?
 120                    .await
 121                    .map_err(|err| {
 122                        if err.is::<language_model::AuthenticateError>() {
 123                            anyhow!(AuthRequired::new().with_language_model_provider(
 124                                language_model::ANTHROPIC_PROVIDER_ID
 125                            ))
 126                        } else {
 127                            anyhow!(err)
 128                        }
 129                    })?;
 130
 131            let (mut thread_tx, thread_rx) = watch::channel(WeakEntity::new_invalid());
 132            let fs = project.read_with(cx, |project, _cx| project.fs().clone())?;
 133            let permission_mcp_server = ClaudeZedMcpServer::new(thread_rx.clone(), fs, cx).await?;
 134
 135            let mut mcp_servers = HashMap::default();
 136            mcp_servers.insert(
 137                mcp_server::SERVER_NAME.to_string(),
 138                permission_mcp_server.server_config()?,
 139            );
 140            let mcp_config = McpConfig { mcp_servers };
 141
 142            let mcp_config_file = tempfile::NamedTempFile::new()?;
 143            let (mcp_config_file, mcp_config_path) = mcp_config_file.into_parts();
 144
 145            let mut mcp_config_file = smol::fs::File::from(mcp_config_file);
 146            mcp_config_file
 147                .write_all(serde_json::to_string(&mcp_config)?.as_bytes())
 148                .await?;
 149            mcp_config_file.flush().await?;
 150
 151            let (incoming_message_tx, mut incoming_message_rx) = mpsc::unbounded();
 152            let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
 153
 154            let session_id = acp::SessionId(Uuid::new_v4().to_string().into());
 155
 156            log::trace!("Starting session with id: {}", session_id);
 157
 158            let mut child = spawn_claude(
 159                &command,
 160                ClaudeSessionMode::Start,
 161                session_id.clone(),
 162                api_key,
 163                &mcp_config_path,
 164                &cwd,
 165            )?;
 166
 167            let stdout = child.stdout.take().context("Failed to take stdout")?;
 168            let stdin = child.stdin.take().context("Failed to take stdin")?;
 169            let stderr = child.stderr.take().context("Failed to take stderr")?;
 170
 171            let pid = child.id();
 172            log::trace!("Spawned (pid: {})", pid);
 173
 174            cx.background_spawn(async move {
 175                let mut stderr = BufReader::new(stderr);
 176                let mut line = String::new();
 177                while let Ok(n) = stderr.read_line(&mut line).await
 178                    && n > 0
 179                {
 180                    log::warn!("agent stderr: {}", &line);
 181                    line.clear();
 182                }
 183            })
 184            .detach();
 185
 186            cx.background_spawn(async move {
 187                let mut outgoing_rx = Some(outgoing_rx);
 188
 189                ClaudeAgentSession::handle_io(
 190                    outgoing_rx.take().unwrap(),
 191                    incoming_message_tx.clone(),
 192                    stdin,
 193                    stdout,
 194                )
 195                .await?;
 196
 197                log::trace!("Stopped (pid: {})", pid);
 198
 199                drop(mcp_config_path);
 200                anyhow::Ok(())
 201            })
 202            .detach();
 203
 204            let turn_state = Rc::new(RefCell::new(TurnState::None));
 205
 206            let handler_task = cx.spawn({
 207                let turn_state = turn_state.clone();
 208                let mut thread_rx = thread_rx.clone();
 209                async move |cx| {
 210                    while let Some(message) = incoming_message_rx.next().await {
 211                        ClaudeAgentSession::handle_message(
 212                            thread_rx.clone(),
 213                            message,
 214                            turn_state.clone(),
 215                            cx,
 216                        )
 217                        .await
 218                    }
 219
 220                    if let Some(status) = child.status().await.log_err()
 221                        && let Some(thread) = thread_rx.recv().await.ok()
 222                    {
 223                        let version = claude_version(command.path.clone(), cx).await.log_err();
 224                        let help = claude_help(command.path.clone(), cx).await.log_err();
 225                        thread
 226                            .update(cx, |thread, cx| {
 227                                let error = if let Some(version) = version
 228                                    && let Some(help) = help
 229                                    && (!help.contains("--input-format")
 230                                        || !help.contains("--session-id"))
 231                                {
 232                                    LoadError::Unsupported {
 233                                    error_message: format!(
 234                                            "Your installed version of Claude Code ({}, version {}) does not have required features for use with Zed.",
 235                                            command.path.to_string_lossy(),
 236                                            version,
 237                                        )
 238                                        .into(),
 239                                        upgrade_message: "Upgrade Claude Code to latest".into(),
 240                                        upgrade_command: format!(
 241                                            "{} update",
 242                                            command.path.to_string_lossy()
 243                                        ),
 244                                    }
 245                                } else {
 246                                    LoadError::Exited { status }
 247                                };
 248                                thread.emit_load_error(error, cx);
 249                            })
 250                            .ok();
 251                    }
 252                }
 253            });
 254
 255            let action_log = cx.new(|_| ActionLog::new(project.clone()))?;
 256            let thread = cx.new(|cx| {
 257                AcpThread::new(
 258                    "Claude Code",
 259                    self.clone(),
 260                    project,
 261                    action_log,
 262                    session_id.clone(),
 263                    watch::Receiver::constant(acp::PromptCapabilities {
 264                        image: true,
 265                        audio: false,
 266                        embedded_context: true,
 267                    }),
 268                    cx,
 269                )
 270            })?;
 271
 272            thread_tx.send(thread.downgrade())?;
 273
 274            let session = ClaudeAgentSession {
 275                outgoing_tx,
 276                turn_state,
 277                _handler_task: handler_task,
 278                _mcp_server: Some(permission_mcp_server),
 279            };
 280
 281            self.sessions.borrow_mut().insert(session_id, session);
 282
 283            Ok(thread)
 284        })
 285    }
 286
 287    fn auth_methods(&self) -> &[acp::AuthMethod] {
 288        &[]
 289    }
 290
 291    fn authenticate(&self, _: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
 292        Task::ready(Err(anyhow!("Authentication not supported")))
 293    }
 294
 295    fn prompt(
 296        &self,
 297        params: acp::PromptRequest,
 298        cx: &mut App,
 299    ) -> Task<Result<acp::PromptResponse>> {
 300        let sessions = self.sessions.borrow();
 301        let Some(session) = sessions.get(&params.session_id) else {
 302            return Task::ready(Err(anyhow!(
 303                "Attempted to send message to nonexistent session {}",
 304                params.session_id
 305            )));
 306        };
 307
 308        let (end_tx, end_rx) = oneshot::channel();
 309        session.turn_state.replace(TurnState::InProgress { end_tx });
 310
 311        let content = acp_content_to_claude(params.prompt);
 312
 313        if let Err(err) = session.outgoing_tx.unbounded_send(SdkMessage::User {
 314            message: Message {
 315                role: Role::User,
 316                content: Content::Chunks(content),
 317                id: None,
 318                model: None,
 319                stop_reason: None,
 320                stop_sequence: None,
 321                usage: None,
 322            },
 323            session_id: Some(params.session_id.to_string()),
 324        }) {
 325            return Task::ready(Err(anyhow!(err)));
 326        }
 327
 328        cx.foreground_executor().spawn(async move { end_rx.await? })
 329    }
 330
 331    fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) {
 332        let sessions = self.sessions.borrow();
 333        let Some(session) = sessions.get(session_id) else {
 334            log::warn!("Attempted to cancel nonexistent session {}", session_id);
 335            return;
 336        };
 337
 338        let request_id = new_request_id();
 339
 340        let turn_state = session.turn_state.take();
 341        let TurnState::InProgress { end_tx } = turn_state else {
 342            // Already canceled or idle, put it back
 343            session.turn_state.replace(turn_state);
 344            return;
 345        };
 346
 347        session.turn_state.replace(TurnState::CancelRequested {
 348            end_tx,
 349            request_id: request_id.clone(),
 350        });
 351
 352        session
 353            .outgoing_tx
 354            .unbounded_send(SdkMessage::ControlRequest {
 355                request_id,
 356                request: ControlRequest::Interrupt,
 357            })
 358            .log_err();
 359    }
 360
 361    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
 362        self
 363    }
 364}
 365
 366#[derive(Clone, Copy)]
 367enum ClaudeSessionMode {
 368    Start,
 369    #[expect(dead_code)]
 370    Resume,
 371}
 372
 373fn spawn_claude(
 374    command: &AgentServerCommand,
 375    mode: ClaudeSessionMode,
 376    session_id: acp::SessionId,
 377    api_key: language_models::provider::anthropic::ApiKey,
 378    mcp_config_path: &Path,
 379    root_dir: &Path,
 380) -> Result<Child> {
 381    let child = util::command::new_smol_command(&command.path)
 382        .args([
 383            "--input-format",
 384            "stream-json",
 385            "--output-format",
 386            "stream-json",
 387            "--print",
 388            "--verbose",
 389            "--mcp-config",
 390            mcp_config_path.to_string_lossy().as_ref(),
 391            "--permission-prompt-tool",
 392            &format!(
 393                "mcp__{}__{}",
 394                mcp_server::SERVER_NAME,
 395                permission_tool::PermissionTool::NAME,
 396            ),
 397            "--allowedTools",
 398            &format!(
 399                "mcp__{}__{}",
 400                mcp_server::SERVER_NAME,
 401                read_tool::ReadTool::NAME
 402            ),
 403            "--disallowedTools",
 404            "Read,Write,Edit,MultiEdit",
 405        ])
 406        .args(match mode {
 407            ClaudeSessionMode::Start => ["--session-id".to_string(), session_id.to_string()],
 408            ClaudeSessionMode::Resume => ["--resume".to_string(), session_id.to_string()],
 409        })
 410        .args(command.args.iter().map(|arg| arg.as_str()))
 411        .envs(command.env.iter().flatten())
 412        .env("ANTHROPIC_API_KEY", api_key.key)
 413        .current_dir(root_dir)
 414        .stdin(std::process::Stdio::piped())
 415        .stdout(std::process::Stdio::piped())
 416        .stderr(std::process::Stdio::piped())
 417        .kill_on_drop(true)
 418        .spawn()?;
 419
 420    Ok(child)
 421}
 422
 423fn claude_version(path: PathBuf, cx: &mut AsyncApp) -> Task<Result<semver::Version>> {
 424    cx.background_spawn(async move {
 425        let output = new_smol_command(path).arg("--version").output().await?;
 426        let output = String::from_utf8(output.stdout)?;
 427        let version = output
 428            .trim()
 429            .strip_suffix(" (Claude Code)")
 430            .context("parsing Claude version")?;
 431        let version = semver::Version::parse(version)?;
 432        anyhow::Ok(version)
 433    })
 434}
 435
 436fn claude_help(path: PathBuf, cx: &mut AsyncApp) -> Task<Result<String>> {
 437    cx.background_spawn(async move {
 438        let output = new_smol_command(path).arg("--help").output().await?;
 439        let output = String::from_utf8(output.stdout)?;
 440        anyhow::Ok(output)
 441    })
 442}
 443
 444struct ClaudeAgentSession {
 445    outgoing_tx: UnboundedSender<SdkMessage>,
 446    turn_state: Rc<RefCell<TurnState>>,
 447    _mcp_server: Option<ClaudeZedMcpServer>,
 448    _handler_task: Task<()>,
 449}
 450
 451#[derive(Debug, Default)]
 452enum TurnState {
 453    #[default]
 454    None,
 455    InProgress {
 456        end_tx: oneshot::Sender<Result<acp::PromptResponse>>,
 457    },
 458    CancelRequested {
 459        end_tx: oneshot::Sender<Result<acp::PromptResponse>>,
 460        request_id: String,
 461    },
 462    CancelConfirmed {
 463        end_tx: oneshot::Sender<Result<acp::PromptResponse>>,
 464    },
 465}
 466
 467impl TurnState {
 468    fn is_canceled(&self) -> bool {
 469        matches!(self, TurnState::CancelConfirmed { .. })
 470    }
 471
 472    fn end_tx(self) -> Option<oneshot::Sender<Result<acp::PromptResponse>>> {
 473        match self {
 474            TurnState::None => None,
 475            TurnState::InProgress { end_tx, .. } => Some(end_tx),
 476            TurnState::CancelRequested { end_tx, .. } => Some(end_tx),
 477            TurnState::CancelConfirmed { end_tx } => Some(end_tx),
 478        }
 479    }
 480
 481    fn confirm_cancellation(self, id: &str) -> Self {
 482        match self {
 483            TurnState::CancelRequested { request_id, end_tx } if request_id == id => {
 484                TurnState::CancelConfirmed { end_tx }
 485            }
 486            _ => self,
 487        }
 488    }
 489}
 490
 491impl ClaudeAgentSession {
 492    async fn handle_message(
 493        mut thread_rx: watch::Receiver<WeakEntity<AcpThread>>,
 494        message: SdkMessage,
 495        turn_state: Rc<RefCell<TurnState>>,
 496        cx: &mut AsyncApp,
 497    ) {
 498        match message {
 499            // we should only be sending these out, they don't need to be in the thread
 500            SdkMessage::ControlRequest { .. } => {}
 501            SdkMessage::User {
 502                message,
 503                session_id: _,
 504            } => {
 505                let Some(thread) = thread_rx
 506                    .recv()
 507                    .await
 508                    .log_err()
 509                    .and_then(|entity| entity.upgrade())
 510                else {
 511                    log::error!("Received an SDK message but thread is gone");
 512                    return;
 513                };
 514
 515                for chunk in message.content.chunks() {
 516                    match chunk {
 517                        ContentChunk::Text { text } | ContentChunk::UntaggedText(text) => {
 518                            if !turn_state.borrow().is_canceled() {
 519                                thread
 520                                    .update(cx, |thread, cx| {
 521                                        thread.push_user_content_block(None, text.into(), cx)
 522                                    })
 523                                    .log_err();
 524                            }
 525                        }
 526                        ContentChunk::ToolResult {
 527                            content,
 528                            tool_use_id,
 529                        } => {
 530                            let content = content.to_string();
 531                            thread
 532                                .update(cx, |thread, cx| {
 533                                    let id = acp::ToolCallId(tool_use_id.into());
 534                                    let set_new_content = !content.is_empty()
 535                                        && thread.tool_call(&id).is_none_or(|(_, tool_call)| {
 536                                            // preserve rich diff if we have one
 537                                            tool_call.diffs().next().is_none()
 538                                        });
 539
 540                                    thread.update_tool_call(
 541                                        acp::ToolCallUpdate {
 542                                            id,
 543                                            fields: acp::ToolCallUpdateFields {
 544                                                status: if turn_state.borrow().is_canceled() {
 545                                                    // Do not set to completed if turn was canceled
 546                                                    None
 547                                                } else {
 548                                                    Some(acp::ToolCallStatus::Completed)
 549                                                },
 550                                                content: set_new_content
 551                                                    .then(|| vec![content.into()]),
 552                                                ..Default::default()
 553                                            },
 554                                        },
 555                                        cx,
 556                                    )
 557                                })
 558                                .log_err();
 559                        }
 560                        ContentChunk::Thinking { .. }
 561                        | ContentChunk::RedactedThinking
 562                        | ContentChunk::ToolUse { .. } => {
 563                            debug_panic!(
 564                                "Should not get {:?} with role: assistant. should we handle this?",
 565                                chunk
 566                            );
 567                        }
 568                        ContentChunk::Image { source } => {
 569                            if !turn_state.borrow().is_canceled() {
 570                                thread
 571                                    .update(cx, |thread, cx| {
 572                                        thread.push_user_content_block(None, source.into(), cx)
 573                                    })
 574                                    .log_err();
 575                            }
 576                        }
 577
 578                        ContentChunk::Document | ContentChunk::WebSearchToolResult => {
 579                            thread
 580                                .update(cx, |thread, cx| {
 581                                    thread.push_assistant_content_block(
 582                                        format!("Unsupported content: {:?}", chunk).into(),
 583                                        false,
 584                                        cx,
 585                                    )
 586                                })
 587                                .log_err();
 588                        }
 589                    }
 590                }
 591            }
 592            SdkMessage::Assistant {
 593                message,
 594                session_id: _,
 595            } => {
 596                let Some(thread) = thread_rx
 597                    .recv()
 598                    .await
 599                    .log_err()
 600                    .and_then(|entity| entity.upgrade())
 601                else {
 602                    log::error!("Received an SDK message but thread is gone");
 603                    return;
 604                };
 605
 606                for chunk in message.content.chunks() {
 607                    match chunk {
 608                        ContentChunk::Text { text } | ContentChunk::UntaggedText(text) => {
 609                            thread
 610                                .update(cx, |thread, cx| {
 611                                    thread.push_assistant_content_block(text.into(), false, cx)
 612                                })
 613                                .log_err();
 614                        }
 615                        ContentChunk::Thinking { thinking } => {
 616                            thread
 617                                .update(cx, |thread, cx| {
 618                                    thread.push_assistant_content_block(thinking.into(), true, cx)
 619                                })
 620                                .log_err();
 621                        }
 622                        ContentChunk::RedactedThinking => {
 623                            thread
 624                                .update(cx, |thread, cx| {
 625                                    thread.push_assistant_content_block(
 626                                        "[REDACTED]".into(),
 627                                        true,
 628                                        cx,
 629                                    )
 630                                })
 631                                .log_err();
 632                        }
 633                        ContentChunk::ToolUse { id, name, input } => {
 634                            let claude_tool = ClaudeTool::infer(&name, input);
 635
 636                            thread
 637                                .update(cx, |thread, cx| {
 638                                    if let ClaudeTool::TodoWrite(Some(params)) = claude_tool {
 639                                        thread.update_plan(
 640                                            acp::Plan {
 641                                                entries: params
 642                                                    .todos
 643                                                    .into_iter()
 644                                                    .map(Into::into)
 645                                                    .collect(),
 646                                            },
 647                                            cx,
 648                                        )
 649                                    } else {
 650                                        thread.upsert_tool_call(
 651                                            claude_tool.as_acp(acp::ToolCallId(id.into())),
 652                                            cx,
 653                                        )?;
 654                                    }
 655                                    anyhow::Ok(())
 656                                })
 657                                .log_err();
 658                        }
 659                        ContentChunk::ToolResult { .. } | ContentChunk::WebSearchToolResult => {
 660                            debug_panic!(
 661                                "Should not get tool results with role: assistant. should we handle this?"
 662                            );
 663                        }
 664                        ContentChunk::Image { source } => {
 665                            thread
 666                                .update(cx, |thread, cx| {
 667                                    thread.push_assistant_content_block(source.into(), false, cx)
 668                                })
 669                                .log_err();
 670                        }
 671                        ContentChunk::Document => {
 672                            thread
 673                                .update(cx, |thread, cx| {
 674                                    thread.push_assistant_content_block(
 675                                        format!("Unsupported content: {:?}", chunk).into(),
 676                                        false,
 677                                        cx,
 678                                    )
 679                                })
 680                                .log_err();
 681                        }
 682                    }
 683                }
 684            }
 685            SdkMessage::Result {
 686                is_error,
 687                subtype,
 688                result,
 689                ..
 690            } => {
 691                let turn_state = turn_state.take();
 692                let was_canceled = turn_state.is_canceled();
 693                let Some(end_turn_tx) = turn_state.end_tx() else {
 694                    debug_panic!("Received `SdkMessage::Result` but there wasn't an active turn");
 695                    return;
 696                };
 697
 698                if is_error || (!was_canceled && subtype == ResultErrorType::ErrorDuringExecution) {
 699                    end_turn_tx
 700                        .send(Err(anyhow!(
 701                            "Error: {}",
 702                            result.unwrap_or_else(|| subtype.to_string())
 703                        )))
 704                        .ok();
 705                } else {
 706                    let stop_reason = match subtype {
 707                        ResultErrorType::Success => acp::StopReason::EndTurn,
 708                        ResultErrorType::ErrorMaxTurns => acp::StopReason::MaxTurnRequests,
 709                        ResultErrorType::ErrorDuringExecution => acp::StopReason::Cancelled,
 710                    };
 711                    end_turn_tx
 712                        .send(Ok(acp::PromptResponse { stop_reason }))
 713                        .ok();
 714                }
 715            }
 716            SdkMessage::ControlResponse { response } => {
 717                if matches!(response.subtype, ResultErrorType::Success) {
 718                    let new_state = turn_state.take().confirm_cancellation(&response.request_id);
 719                    turn_state.replace(new_state);
 720                } else {
 721                    log::error!("Control response error: {:?}", response);
 722                }
 723            }
 724            SdkMessage::System { .. } => {}
 725        }
 726    }
 727
 728    async fn handle_io(
 729        mut outgoing_rx: UnboundedReceiver<SdkMessage>,
 730        incoming_tx: UnboundedSender<SdkMessage>,
 731        mut outgoing_bytes: impl Unpin + AsyncWrite,
 732        incoming_bytes: impl Unpin + AsyncRead,
 733    ) -> Result<UnboundedReceiver<SdkMessage>> {
 734        let mut output_reader = BufReader::new(incoming_bytes);
 735        let mut outgoing_line = Vec::new();
 736        let mut incoming_line = String::new();
 737        loop {
 738            select_biased! {
 739                message = outgoing_rx.next() => {
 740                    if let Some(message) = message {
 741                        outgoing_line.clear();
 742                        serde_json::to_writer(&mut outgoing_line, &message)?;
 743                        log::trace!("send: {}", String::from_utf8_lossy(&outgoing_line));
 744                        outgoing_line.push(b'\n');
 745                        outgoing_bytes.write_all(&outgoing_line).await.ok();
 746                    } else {
 747                        break;
 748                    }
 749                }
 750                bytes_read = output_reader.read_line(&mut incoming_line).fuse() => {
 751                    if bytes_read? == 0 {
 752                        break
 753                    }
 754                    log::trace!("recv: {}", &incoming_line);
 755                    match serde_json::from_str::<SdkMessage>(&incoming_line) {
 756                        Ok(message) => {
 757                            incoming_tx.unbounded_send(message).log_err();
 758                        }
 759                        Err(error) => {
 760                            log::error!("failed to parse incoming message: {error}. Raw: {incoming_line}");
 761                        }
 762                    }
 763                    incoming_line.clear();
 764                }
 765            }
 766        }
 767
 768        Ok(outgoing_rx)
 769    }
 770}
 771
 772#[derive(Debug, Clone, Serialize, Deserialize)]
 773struct Message {
 774    role: Role,
 775    content: Content,
 776    #[serde(skip_serializing_if = "Option::is_none")]
 777    id: Option<String>,
 778    #[serde(skip_serializing_if = "Option::is_none")]
 779    model: Option<String>,
 780    #[serde(skip_serializing_if = "Option::is_none")]
 781    stop_reason: Option<String>,
 782    #[serde(skip_serializing_if = "Option::is_none")]
 783    stop_sequence: Option<String>,
 784    #[serde(skip_serializing_if = "Option::is_none")]
 785    usage: Option<Usage>,
 786}
 787
 788#[derive(Debug, Clone, Serialize, Deserialize)]
 789#[serde(untagged)]
 790enum Content {
 791    UntaggedText(String),
 792    Chunks(Vec<ContentChunk>),
 793}
 794
 795impl Content {
 796    pub fn chunks(self) -> impl Iterator<Item = ContentChunk> {
 797        match self {
 798            Self::Chunks(chunks) => chunks.into_iter(),
 799            Self::UntaggedText(text) => vec![ContentChunk::Text { text }].into_iter(),
 800        }
 801    }
 802}
 803
 804impl Display for Content {
 805    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 806        match self {
 807            Content::UntaggedText(txt) => write!(f, "{}", txt),
 808            Content::Chunks(chunks) => {
 809                for chunk in chunks {
 810                    write!(f, "{}", chunk)?;
 811                }
 812                Ok(())
 813            }
 814        }
 815    }
 816}
 817
 818#[derive(Debug, Clone, Serialize, Deserialize)]
 819#[serde(tag = "type", rename_all = "snake_case")]
 820enum ContentChunk {
 821    Text {
 822        text: String,
 823    },
 824    ToolUse {
 825        id: String,
 826        name: String,
 827        input: serde_json::Value,
 828    },
 829    ToolResult {
 830        content: Content,
 831        tool_use_id: String,
 832    },
 833    Thinking {
 834        thinking: String,
 835    },
 836    RedactedThinking,
 837    Image {
 838        source: ImageSource,
 839    },
 840    // TODO
 841    Document,
 842    WebSearchToolResult,
 843    #[serde(untagged)]
 844    UntaggedText(String),
 845}
 846
 847#[derive(Debug, Clone, Serialize, Deserialize)]
 848#[serde(tag = "type", rename_all = "snake_case")]
 849enum ImageSource {
 850    Base64 { data: String, media_type: String },
 851    Url { url: String },
 852}
 853
 854impl Into<acp::ContentBlock> for ImageSource {
 855    fn into(self) -> acp::ContentBlock {
 856        match self {
 857            ImageSource::Base64 { data, media_type } => {
 858                acp::ContentBlock::Image(acp::ImageContent {
 859                    annotations: None,
 860                    data,
 861                    mime_type: media_type,
 862                    uri: None,
 863                })
 864            }
 865            ImageSource::Url { url } => acp::ContentBlock::Image(acp::ImageContent {
 866                annotations: None,
 867                data: "".to_string(),
 868                mime_type: "".to_string(),
 869                uri: Some(url),
 870            }),
 871        }
 872    }
 873}
 874
 875impl Display for ContentChunk {
 876    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 877        match self {
 878            ContentChunk::Text { text } => write!(f, "{}", text),
 879            ContentChunk::Thinking { thinking } => write!(f, "Thinking: {}", thinking),
 880            ContentChunk::RedactedThinking => write!(f, "Thinking: [REDACTED]"),
 881            ContentChunk::UntaggedText(text) => write!(f, "{}", text),
 882            ContentChunk::ToolResult { content, .. } => write!(f, "{}", content),
 883            ContentChunk::Image { .. }
 884            | ContentChunk::Document
 885            | ContentChunk::ToolUse { .. }
 886            | ContentChunk::WebSearchToolResult => {
 887                write!(f, "\n{:?}\n", &self)
 888            }
 889        }
 890    }
 891}
 892
 893#[derive(Debug, Clone, Serialize, Deserialize)]
 894struct Usage {
 895    input_tokens: u32,
 896    cache_creation_input_tokens: u32,
 897    cache_read_input_tokens: u32,
 898    output_tokens: u32,
 899    service_tier: String,
 900}
 901
 902#[derive(Debug, Clone, Serialize, Deserialize)]
 903#[serde(rename_all = "snake_case")]
 904enum Role {
 905    System,
 906    Assistant,
 907    User,
 908}
 909
 910#[derive(Debug, Clone, Serialize, Deserialize)]
 911struct MessageParam {
 912    role: Role,
 913    content: String,
 914}
 915
 916#[derive(Debug, Clone, Serialize, Deserialize)]
 917#[serde(tag = "type", rename_all = "snake_case")]
 918enum SdkMessage {
 919    // An assistant message
 920    Assistant {
 921        message: Message, // from Anthropic SDK
 922        #[serde(skip_serializing_if = "Option::is_none")]
 923        session_id: Option<String>,
 924    },
 925    // A user message
 926    User {
 927        message: Message, // from Anthropic SDK
 928        #[serde(skip_serializing_if = "Option::is_none")]
 929        session_id: Option<String>,
 930    },
 931    // Emitted as the last message in a conversation
 932    Result {
 933        subtype: ResultErrorType,
 934        duration_ms: f64,
 935        duration_api_ms: f64,
 936        is_error: bool,
 937        num_turns: i32,
 938        #[serde(skip_serializing_if = "Option::is_none")]
 939        result: Option<String>,
 940        session_id: String,
 941        total_cost_usd: f64,
 942    },
 943    // Emitted as the first message at the start of a conversation
 944    System {
 945        cwd: String,
 946        session_id: String,
 947        tools: Vec<String>,
 948        model: String,
 949        mcp_servers: Vec<McpServer>,
 950        #[serde(rename = "apiKeySource")]
 951        api_key_source: String,
 952        #[serde(rename = "permissionMode")]
 953        permission_mode: PermissionMode,
 954    },
 955    /// Messages used to control the conversation, outside of chat messages to the model
 956    ControlRequest {
 957        request_id: String,
 958        request: ControlRequest,
 959    },
 960    /// Response to a control request
 961    ControlResponse { response: ControlResponse },
 962}
 963
 964#[derive(Debug, Clone, Serialize, Deserialize)]
 965#[serde(tag = "subtype", rename_all = "snake_case")]
 966enum ControlRequest {
 967    /// Cancel the current conversation
 968    Interrupt,
 969}
 970
 971#[derive(Debug, Clone, Serialize, Deserialize)]
 972struct ControlResponse {
 973    request_id: String,
 974    subtype: ResultErrorType,
 975}
 976
 977#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
 978#[serde(rename_all = "snake_case")]
 979enum ResultErrorType {
 980    Success,
 981    ErrorMaxTurns,
 982    ErrorDuringExecution,
 983}
 984
 985impl Display for ResultErrorType {
 986    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 987        match self {
 988            ResultErrorType::Success => write!(f, "success"),
 989            ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
 990            ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
 991        }
 992    }
 993}
 994
 995fn acp_content_to_claude(prompt: Vec<acp::ContentBlock>) -> Vec<ContentChunk> {
 996    let mut content = Vec::with_capacity(prompt.len());
 997    let mut context = Vec::with_capacity(prompt.len());
 998
 999    for chunk in prompt {
1000        match chunk {
1001            acp::ContentBlock::Text(text_content) => {
1002                content.push(ContentChunk::Text {
1003                    text: text_content.text,
1004                });
1005            }
1006            acp::ContentBlock::ResourceLink(resource_link) => {
1007                match MentionUri::parse(&resource_link.uri) {
1008                    Ok(uri) => {
1009                        content.push(ContentChunk::Text {
1010                            text: format!("{}", uri.as_link()),
1011                        });
1012                    }
1013                    Err(_) => {
1014                        content.push(ContentChunk::Text {
1015                            text: resource_link.uri,
1016                        });
1017                    }
1018                }
1019            }
1020            acp::ContentBlock::Resource(resource) => match resource.resource {
1021                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
1022                    match MentionUri::parse(&resource.uri) {
1023                        Ok(uri) => {
1024                            content.push(ContentChunk::Text {
1025                                text: format!("{}", uri.as_link()),
1026                            });
1027                        }
1028                        Err(_) => {
1029                            content.push(ContentChunk::Text {
1030                                text: resource.uri.clone(),
1031                            });
1032                        }
1033                    }
1034
1035                    context.push(ContentChunk::Text {
1036                        text: format!(
1037                            "\n<context ref=\"{}\">\n{}\n</context>",
1038                            resource.uri, resource.text
1039                        ),
1040                    });
1041                }
1042                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
1043                    // Unsupported by SDK
1044                }
1045            },
1046            acp::ContentBlock::Image(acp::ImageContent {
1047                data, mime_type, ..
1048            }) => content.push(ContentChunk::Image {
1049                source: ImageSource::Base64 {
1050                    data,
1051                    media_type: mime_type,
1052                },
1053            }),
1054            acp::ContentBlock::Audio(_) => {
1055                // Unsupported by SDK
1056            }
1057        }
1058    }
1059
1060    content.extend(context);
1061    content
1062}
1063
1064fn new_request_id() -> String {
1065    use rand::Rng;
1066    // In the Claude Code TS SDK they just generate a random 12 character string,
1067    // `Math.random().toString(36).substring(2, 15)`
1068    rand::thread_rng()
1069        .sample_iter(&rand::distributions::Alphanumeric)
1070        .take(12)
1071        .map(char::from)
1072        .collect()
1073}
1074
1075#[derive(Debug, Clone, Serialize, Deserialize)]
1076struct McpServer {
1077    name: String,
1078    status: String,
1079}
1080
1081#[derive(Debug, Clone, Serialize, Deserialize)]
1082#[serde(rename_all = "camelCase")]
1083enum PermissionMode {
1084    Default,
1085    AcceptEdits,
1086    BypassPermissions,
1087    Plan,
1088}
1089
1090#[cfg(test)]
1091pub(crate) mod tests {
1092    use super::*;
1093    use crate::e2e_tests;
1094    use gpui::TestAppContext;
1095    use serde_json::json;
1096
1097    crate::common_e2e_tests!(async |_, _, _| ClaudeCode, allow_option_id = "allow");
1098
1099    pub fn local_command() -> AgentServerCommand {
1100        AgentServerCommand {
1101            path: "claude".into(),
1102            args: vec![],
1103            env: None,
1104        }
1105    }
1106
1107    #[gpui::test]
1108    #[cfg_attr(not(feature = "e2e"), ignore)]
1109    async fn test_todo_plan(cx: &mut TestAppContext) {
1110        let fs = e2e_tests::init_test(cx).await;
1111        let project = Project::test(fs, [], cx).await;
1112        let thread =
1113            e2e_tests::new_test_thread(ClaudeCode, project.clone(), "/private/tmp", cx).await;
1114
1115        thread
1116            .update(cx, |thread, cx| {
1117                thread.send_raw(
1118                    "Create a todo plan for initializing a new React app. I'll follow it myself, do not execute on it.",
1119                    cx,
1120                )
1121            })
1122            .await
1123            .unwrap();
1124
1125        let mut entries_len = 0;
1126
1127        thread.read_with(cx, |thread, _| {
1128            entries_len = thread.plan().entries.len();
1129            assert!(!thread.plan().entries.is_empty(), "Empty plan");
1130        });
1131
1132        thread
1133            .update(cx, |thread, cx| {
1134                thread.send_raw(
1135                    "Mark the first entry status as in progress without acting on it.",
1136                    cx,
1137                )
1138            })
1139            .await
1140            .unwrap();
1141
1142        thread.read_with(cx, |thread, _| {
1143            assert!(matches!(
1144                thread.plan().entries[0].status,
1145                acp::PlanEntryStatus::InProgress
1146            ));
1147            assert_eq!(thread.plan().entries.len(), entries_len);
1148        });
1149
1150        thread
1151            .update(cx, |thread, cx| {
1152                thread.send_raw(
1153                    "Now mark the first entry as completed without acting on it.",
1154                    cx,
1155                )
1156            })
1157            .await
1158            .unwrap();
1159
1160        thread.read_with(cx, |thread, _| {
1161            assert!(matches!(
1162                thread.plan().entries[0].status,
1163                acp::PlanEntryStatus::Completed
1164            ));
1165            assert_eq!(thread.plan().entries.len(), entries_len);
1166        });
1167    }
1168
1169    #[test]
1170    fn test_deserialize_content_untagged_text() {
1171        let json = json!("Hello, world!");
1172        let content: Content = serde_json::from_value(json).unwrap();
1173        match content {
1174            Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
1175            _ => panic!("Expected UntaggedText variant"),
1176        }
1177    }
1178
1179    #[test]
1180    fn test_deserialize_content_chunks() {
1181        let json = json!([
1182            {
1183                "type": "text",
1184                "text": "Hello"
1185            },
1186            {
1187                "type": "tool_use",
1188                "id": "tool_123",
1189                "name": "calculator",
1190                "input": {"operation": "add", "a": 1, "b": 2}
1191            }
1192        ]);
1193        let content: Content = serde_json::from_value(json).unwrap();
1194        match content {
1195            Content::Chunks(chunks) => {
1196                assert_eq!(chunks.len(), 2);
1197                match &chunks[0] {
1198                    ContentChunk::Text { text } => assert_eq!(text, "Hello"),
1199                    _ => panic!("Expected Text chunk"),
1200                }
1201                match &chunks[1] {
1202                    ContentChunk::ToolUse { id, name, input } => {
1203                        assert_eq!(id, "tool_123");
1204                        assert_eq!(name, "calculator");
1205                        assert_eq!(input["operation"], "add");
1206                        assert_eq!(input["a"], 1);
1207                        assert_eq!(input["b"], 2);
1208                    }
1209                    _ => panic!("Expected ToolUse chunk"),
1210                }
1211            }
1212            _ => panic!("Expected Chunks variant"),
1213        }
1214    }
1215
1216    #[test]
1217    fn test_deserialize_tool_result_untagged_text() {
1218        let json = json!({
1219            "type": "tool_result",
1220            "content": "Result content",
1221            "tool_use_id": "tool_456"
1222        });
1223        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
1224        match chunk {
1225            ContentChunk::ToolResult {
1226                content,
1227                tool_use_id,
1228            } => {
1229                match content {
1230                    Content::UntaggedText(text) => assert_eq!(text, "Result content"),
1231                    _ => panic!("Expected UntaggedText content"),
1232                }
1233                assert_eq!(tool_use_id, "tool_456");
1234            }
1235            _ => panic!("Expected ToolResult variant"),
1236        }
1237    }
1238
1239    #[test]
1240    fn test_deserialize_tool_result_chunks() {
1241        let json = json!({
1242            "type": "tool_result",
1243            "content": [
1244                {
1245                    "type": "text",
1246                    "text": "Processing complete"
1247                },
1248                {
1249                    "type": "text",
1250                    "text": "Result: 42"
1251                }
1252            ],
1253            "tool_use_id": "tool_789"
1254        });
1255        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
1256        match chunk {
1257            ContentChunk::ToolResult {
1258                content,
1259                tool_use_id,
1260            } => {
1261                match content {
1262                    Content::Chunks(chunks) => {
1263                        assert_eq!(chunks.len(), 2);
1264                        match &chunks[0] {
1265                            ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
1266                            _ => panic!("Expected Text chunk"),
1267                        }
1268                        match &chunks[1] {
1269                            ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
1270                            _ => panic!("Expected Text chunk"),
1271                        }
1272                    }
1273                    _ => panic!("Expected Chunks content"),
1274                }
1275                assert_eq!(tool_use_id, "tool_789");
1276            }
1277            _ => panic!("Expected ToolResult variant"),
1278        }
1279    }
1280
1281    #[test]
1282    fn test_acp_content_to_claude() {
1283        let acp_content = vec![
1284            acp::ContentBlock::Text(acp::TextContent {
1285                text: "Hello world".to_string(),
1286                annotations: None,
1287            }),
1288            acp::ContentBlock::Image(acp::ImageContent {
1289                data: "base64data".to_string(),
1290                mime_type: "image/png".to_string(),
1291                annotations: None,
1292                uri: None,
1293            }),
1294            acp::ContentBlock::ResourceLink(acp::ResourceLink {
1295                uri: "file:///path/to/example.rs".to_string(),
1296                name: "example.rs".to_string(),
1297                annotations: None,
1298                description: None,
1299                mime_type: None,
1300                size: None,
1301                title: None,
1302            }),
1303            acp::ContentBlock::Resource(acp::EmbeddedResource {
1304                annotations: None,
1305                resource: acp::EmbeddedResourceResource::TextResourceContents(
1306                    acp::TextResourceContents {
1307                        mime_type: None,
1308                        text: "fn main() { println!(\"Hello!\"); }".to_string(),
1309                        uri: "file:///path/to/code.rs".to_string(),
1310                    },
1311                ),
1312            }),
1313            acp::ContentBlock::ResourceLink(acp::ResourceLink {
1314                uri: "invalid_uri_format".to_string(),
1315                name: "invalid.txt".to_string(),
1316                annotations: None,
1317                description: None,
1318                mime_type: None,
1319                size: None,
1320                title: None,
1321            }),
1322        ];
1323
1324        let claude_content = acp_content_to_claude(acp_content);
1325
1326        assert_eq!(claude_content.len(), 6);
1327
1328        match &claude_content[0] {
1329            ContentChunk::Text { text } => assert_eq!(text, "Hello world"),
1330            _ => panic!("Expected Text chunk"),
1331        }
1332
1333        match &claude_content[1] {
1334            ContentChunk::Image { source } => match source {
1335                ImageSource::Base64 { data, media_type } => {
1336                    assert_eq!(data, "base64data");
1337                    assert_eq!(media_type, "image/png");
1338                }
1339                _ => panic!("Expected Base64 image source"),
1340            },
1341            _ => panic!("Expected Image chunk"),
1342        }
1343
1344        match &claude_content[2] {
1345            ContentChunk::Text { text } => {
1346                assert!(text.contains("example.rs"));
1347                assert!(text.contains("file:///path/to/example.rs"));
1348            }
1349            _ => panic!("Expected Text chunk for ResourceLink"),
1350        }
1351
1352        match &claude_content[3] {
1353            ContentChunk::Text { text } => {
1354                assert!(text.contains("code.rs"));
1355                assert!(text.contains("file:///path/to/code.rs"));
1356            }
1357            _ => panic!("Expected Text chunk for Resource"),
1358        }
1359
1360        match &claude_content[4] {
1361            ContentChunk::Text { text } => {
1362                assert_eq!(text, "invalid_uri_format");
1363            }
1364            _ => panic!("Expected Text chunk for invalid URI"),
1365        }
1366
1367        match &claude_content[5] {
1368            ContentChunk::Text { text } => {
1369                assert!(text.contains("<context ref=\"file:///path/to/code.rs\">"));
1370                assert!(text.contains("fn main() { println!(\"Hello!\"); }"));
1371                assert!(text.contains("</context>"));
1372            }
1373            _ => panic!("Expected Text chunk for context"),
1374        }
1375    }
1376}