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