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