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