1pub mod tools;
2
3use collections::HashMap;
4use project::Project;
5use settings::SettingsStore;
6use smol::process::Child;
7use std::cell::RefCell;
8use std::fmt::Display;
9use std::path::Path;
10use std::pin::pin;
11use std::rc::Rc;
12use uuid::Uuid;
13
14use agent_client_protocol as acp;
15use anyhow::{Result, anyhow};
16use futures::channel::oneshot;
17use futures::{AsyncBufReadExt, AsyncWriteExt};
18use futures::{
19 AsyncRead, AsyncWrite, FutureExt, StreamExt,
20 channel::mpsc::{self, UnboundedReceiver, UnboundedSender},
21 io::BufReader,
22 select_biased,
23};
24use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity};
25use serde::{Deserialize, Serialize};
26use util::ResultExt;
27
28use crate::claude::tools::ClaudeTool;
29use crate::mcp_server::{self, McpConfig, ZedMcpServer};
30use crate::{AgentServer, AgentServerCommand, AllAgentServersSettings};
31use acp_thread::{AcpThread, AgentConnection};
32
33#[derive(Clone)]
34pub struct ClaudeCode;
35
36impl AgentServer for ClaudeCode {
37 fn name(&self) -> &'static str {
38 "Claude Code"
39 }
40
41 fn empty_state_headline(&self) -> &'static str {
42 self.name()
43 }
44
45 fn empty_state_message(&self) -> &'static str {
46 ""
47 }
48
49 fn logo(&self) -> ui::IconName {
50 ui::IconName::AiClaude
51 }
52
53 fn connect(
54 &self,
55 root_dir: &Path,
56 project: &Entity<Project>,
57 cx: &mut App,
58 ) -> Task<Result<Rc<dyn AgentConnection>>> {
59 let project = project.clone();
60 let root_dir = root_dir.to_path_buf();
61 cx.spawn(async move |cx| {
62 let threads_map = Rc::new(RefCell::new(HashMap::default()));
63 let permission_mcp_server = ZedMcpServer::new(threads_map.clone(), cx).await?;
64
65 let mut mcp_servers = HashMap::default();
66 mcp_servers.insert(
67 crate::mcp_server::SERVER_NAME.to_string(),
68 permission_mcp_server.server_config()?,
69 );
70 let mcp_config = McpConfig { mcp_servers };
71
72 let mcp_config_file = tempfile::NamedTempFile::new()?;
73 let (mcp_config_file, mcp_config_path) = mcp_config_file.into_parts();
74
75 let mut mcp_config_file = smol::fs::File::from(mcp_config_file);
76 mcp_config_file
77 .write_all(serde_json::to_string(&mcp_config)?.as_bytes())
78 .await?;
79 mcp_config_file.flush().await?;
80
81 let settings = cx.read_global(|settings: &SettingsStore, _| {
82 settings.get::<AllAgentServersSettings>(None).claude.clone()
83 })?;
84
85 let Some(command) =
86 AgentServerCommand::resolve("claude", &[], settings, &project, cx).await
87 else {
88 anyhow::bail!("Failed to find claude binary");
89 };
90
91 let (incoming_message_tx, mut incoming_message_rx) = mpsc::unbounded();
92 let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
93 let (cancel_tx, mut cancel_rx) = mpsc::unbounded::<oneshot::Sender<Result<()>>>();
94
95 let session_id = acp::SessionId(Uuid::new_v4().to_string().into());
96
97 log::trace!("Starting session with id: {}", session_id);
98
99 cx.background_spawn({
100 let session_id = session_id.clone();
101 async move {
102 let mut outgoing_rx = Some(outgoing_rx);
103 let mut mode = ClaudeSessionMode::Start;
104
105 loop {
106 let mut child = spawn_claude(
107 &command,
108 mode,
109 session_id.clone(),
110 &mcp_config_path,
111 &root_dir,
112 )
113 .await?;
114 mode = ClaudeSessionMode::Resume;
115
116 let pid = child.id();
117 log::trace!("Spawned (pid: {})", pid);
118
119 let mut io_fut = pin!(
120 ClaudeAgentConnection::handle_io(
121 outgoing_rx.take().unwrap(),
122 incoming_message_tx.clone(),
123 child.stdin.take().unwrap(),
124 child.stdout.take().unwrap(),
125 )
126 .fuse()
127 );
128
129 select_biased! {
130 done_tx = cancel_rx.next() => {
131 if let Some(done_tx) = done_tx {
132 log::trace!("Interrupted (pid: {})", pid);
133 let result = send_interrupt(pid as i32);
134 outgoing_rx.replace(io_fut.await?);
135 done_tx.send(result).log_err();
136 continue;
137 }
138 }
139 result = io_fut => {
140 result?;
141 }
142 }
143
144 log::trace!("Stopped (pid: {})", pid);
145 break;
146 }
147
148 drop(mcp_config_path);
149 anyhow::Ok(())
150 }
151 })
152 .detach();
153
154 let end_turn_tx = Rc::new(RefCell::new(None));
155 let handler_task = cx.spawn({
156 let end_turn_tx = end_turn_tx.clone();
157 let threads_map = threads_map.clone();
158 async move |cx| {
159 while let Some(message) = incoming_message_rx.next().await {
160 ClaudeAgentConnection::handle_message(
161 threads_map.clone(),
162 message,
163 end_turn_tx.clone(),
164 cx,
165 )
166 .await
167 }
168 }
169 });
170
171 let connection = ClaudeAgentConnection {
172 threads_map,
173 outgoing_tx,
174 end_turn_tx,
175 cancel_tx,
176 session_id,
177 _handler_task: handler_task,
178 _mcp_server: Some(permission_mcp_server),
179 };
180
181 Ok(Rc::new(connection) as _)
182 })
183 }
184}
185
186#[cfg(unix)]
187fn send_interrupt(pid: libc::pid_t) -> anyhow::Result<()> {
188 let pid = nix::unistd::Pid::from_raw(pid);
189
190 nix::sys::signal::kill(pid, nix::sys::signal::SIGINT)
191 .map_err(|e| anyhow!("Failed to interrupt process: {}", e))
192}
193
194#[cfg(windows)]
195fn send_interrupt(_pid: i32) -> anyhow::Result<()> {
196 panic!("Cancel not implemented on Windows")
197}
198
199impl AgentConnection for ClaudeAgentConnection {
200 fn new_thread(
201 &self,
202 project: Entity<Project>,
203 _cwd: &Path,
204 connection: Rc<dyn AgentConnection>,
205 cx: &mut AsyncApp,
206 ) -> Task<Result<Entity<AcpThread>>> {
207 let session_id = self.session_id.clone();
208 let thread_result = cx
209 .new(|cx| AcpThread::new(connection, "Claude".into(), project, session_id.clone(), cx));
210
211 if let Ok(thread) = &thread_result {
212 self.threads_map
213 .borrow_mut()
214 .insert(session_id, thread.downgrade());
215 }
216
217 Task::ready(thread_result)
218 }
219
220 fn authenticate(&self, _cx: &mut App) -> Task<Result<()>> {
221 Task::ready(Err(anyhow!("Authentication not supported")))
222 }
223
224 fn prompt(&self, params: acp::PromptToolArguments, cx: &mut App) -> Task<Result<()>> {
225 let (tx, rx) = oneshot::channel();
226 self.end_turn_tx.borrow_mut().replace(tx);
227
228 let mut content = String::new();
229 for chunk in params.prompt {
230 match chunk {
231 acp::ContentBlock::Text(text_content) => {
232 content.push_str(&text_content.text);
233 }
234 acp::ContentBlock::ResourceLink(resource_link) => {
235 content.push_str(&format!("@{}", resource_link.uri));
236 }
237 acp::ContentBlock::Audio(_)
238 | acp::ContentBlock::Image(_)
239 | acp::ContentBlock::Resource(_) => {
240 // TODO
241 }
242 }
243 }
244
245 if let Err(err) = self.outgoing_tx.unbounded_send(SdkMessage::User {
246 message: Message {
247 role: Role::User,
248 content: Content::UntaggedText(content),
249 id: None,
250 model: None,
251 stop_reason: None,
252 stop_sequence: None,
253 usage: None,
254 },
255 session_id: Some(params.session_id.to_string()),
256 }) {
257 return Task::ready(Err(anyhow!(err)));
258 }
259
260 cx.foreground_executor().spawn(async move {
261 rx.await??;
262 Ok(())
263 })
264 }
265
266 fn cancel(&self, cx: &mut App) {
267 let (done_tx, done_rx) = oneshot::channel();
268 if self.cancel_tx.unbounded_send(done_tx).log_err().is_some() {
269 cx.foreground_executor()
270 .spawn(async move { done_rx.await? })
271 .detach_and_log_err(cx);
272 }
273 }
274}
275
276#[derive(Clone, Copy)]
277enum ClaudeSessionMode {
278 Start,
279 Resume,
280}
281
282async fn spawn_claude(
283 command: &AgentServerCommand,
284 mode: ClaudeSessionMode,
285 session_id: acp::SessionId,
286 mcp_config_path: &Path,
287 root_dir: &Path,
288) -> Result<Child> {
289 let child = util::command::new_smol_command(&command.path)
290 .args([
291 "--input-format",
292 "stream-json",
293 "--output-format",
294 "stream-json",
295 "--print",
296 "--verbose",
297 "--mcp-config",
298 mcp_config_path.to_string_lossy().as_ref(),
299 "--permission-prompt-tool",
300 &format!(
301 "mcp__{}__{}",
302 mcp_server::SERVER_NAME,
303 mcp_server::PERMISSION_TOOL
304 ),
305 "--allowedTools",
306 "mcp__zed__Read,mcp__zed__Edit",
307 "--disallowedTools",
308 "Read,Edit",
309 ])
310 .args(match mode {
311 ClaudeSessionMode::Start => ["--session-id".to_string(), session_id.to_string()],
312 ClaudeSessionMode::Resume => ["--resume".to_string(), session_id.to_string()],
313 })
314 .args(command.args.iter().map(|arg| arg.as_str()))
315 .current_dir(root_dir)
316 .stdin(std::process::Stdio::piped())
317 .stdout(std::process::Stdio::piped())
318 .stderr(std::process::Stdio::inherit())
319 .kill_on_drop(true)
320 .spawn()?;
321
322 Ok(child)
323}
324
325struct ClaudeAgentConnection {
326 threads_map: Rc<RefCell<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
327 session_id: acp::SessionId,
328 outgoing_tx: UnboundedSender<SdkMessage>,
329 end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<()>>>>>,
330 cancel_tx: UnboundedSender<oneshot::Sender<Result<()>>>,
331 _mcp_server: Option<ZedMcpServer>,
332 _handler_task: Task<()>,
333}
334
335impl ClaudeAgentConnection {
336 async fn handle_message(
337 threads_map: Rc<RefCell<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
338 message: SdkMessage,
339 end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<()>>>>>,
340 cx: &mut AsyncApp,
341 ) {
342 match message {
343 SdkMessage::Assistant {
344 message,
345 session_id,
346 }
347 | SdkMessage::User {
348 message,
349 session_id,
350 } => {
351 let threads_map = threads_map.borrow();
352 let Some(thread) = session_id
353 .and_then(|session_id| threads_map.get(&acp::SessionId(session_id.into())))
354 .and_then(|entity| entity.upgrade())
355 else {
356 log::error!("Thread not found for session");
357 return;
358 };
359 for chunk in message.content.chunks() {
360 match chunk {
361 ContentChunk::Text { text } | ContentChunk::UntaggedText(text) => {
362 thread
363 .update(cx, |thread, cx| {
364 thread.push_assistant_chunk(text.into(), false, cx)
365 })
366 .log_err();
367 }
368 ContentChunk::ToolUse { id, name, input } => {
369 let claude_tool = ClaudeTool::infer(&name, input);
370
371 thread
372 .update(cx, |thread, cx| {
373 if let ClaudeTool::TodoWrite(Some(params)) = claude_tool {
374 thread.update_plan(
375 acp::Plan {
376 entries: params
377 .todos
378 .into_iter()
379 .map(Into::into)
380 .collect(),
381 },
382 cx,
383 )
384 } else {
385 thread.upsert_tool_call(
386 claude_tool.as_acp(acp::ToolCallId(id.into())),
387 cx,
388 );
389 }
390 })
391 .log_err();
392 }
393 ContentChunk::ToolResult {
394 content,
395 tool_use_id,
396 } => {
397 let content = content.to_string();
398 thread
399 .update(cx, |thread, cx| {
400 thread.update_tool_call(
401 acp::ToolCallId(tool_use_id.into()),
402 acp::ToolCallStatus::Completed,
403 (!content.is_empty()).then(|| vec![content.into()]),
404 cx,
405 )
406 })
407 .log_err();
408 }
409 ContentChunk::Image
410 | ContentChunk::Document
411 | ContentChunk::Thinking
412 | ContentChunk::RedactedThinking
413 | ContentChunk::WebSearchToolResult => {
414 thread
415 .update(cx, |thread, cx| {
416 thread.push_assistant_chunk(
417 format!("Unsupported content: {:?}", chunk).into(),
418 false,
419 cx,
420 )
421 })
422 .log_err();
423 }
424 }
425 }
426 }
427 SdkMessage::Result {
428 is_error, subtype, ..
429 } => {
430 if let Some(end_turn_tx) = end_turn_tx.borrow_mut().take() {
431 if is_error {
432 end_turn_tx.send(Err(anyhow!("Error: {subtype}"))).ok();
433 } else {
434 end_turn_tx.send(Ok(())).ok();
435 }
436 }
437 }
438 SdkMessage::System { .. } => {}
439 }
440 }
441
442 async fn handle_io(
443 mut outgoing_rx: UnboundedReceiver<SdkMessage>,
444 incoming_tx: UnboundedSender<SdkMessage>,
445 mut outgoing_bytes: impl Unpin + AsyncWrite,
446 incoming_bytes: impl Unpin + AsyncRead,
447 ) -> Result<UnboundedReceiver<SdkMessage>> {
448 let mut output_reader = BufReader::new(incoming_bytes);
449 let mut outgoing_line = Vec::new();
450 let mut incoming_line = String::new();
451 loop {
452 select_biased! {
453 message = outgoing_rx.next() => {
454 if let Some(message) = message {
455 outgoing_line.clear();
456 serde_json::to_writer(&mut outgoing_line, &message)?;
457 log::trace!("send: {}", String::from_utf8_lossy(&outgoing_line));
458 outgoing_line.push(b'\n');
459 outgoing_bytes.write_all(&outgoing_line).await.ok();
460 } else {
461 break;
462 }
463 }
464 bytes_read = output_reader.read_line(&mut incoming_line).fuse() => {
465 if bytes_read? == 0 {
466 break
467 }
468 log::trace!("recv: {}", &incoming_line);
469 match serde_json::from_str::<SdkMessage>(&incoming_line) {
470 Ok(message) => {
471 incoming_tx.unbounded_send(message).log_err();
472 }
473 Err(error) => {
474 log::error!("failed to parse incoming message: {error}. Raw: {incoming_line}");
475 }
476 }
477 incoming_line.clear();
478 }
479 }
480 }
481
482 Ok(outgoing_rx)
483 }
484}
485
486#[derive(Debug, Clone, Serialize, Deserialize)]
487struct Message {
488 role: Role,
489 content: Content,
490 #[serde(skip_serializing_if = "Option::is_none")]
491 id: Option<String>,
492 #[serde(skip_serializing_if = "Option::is_none")]
493 model: Option<String>,
494 #[serde(skip_serializing_if = "Option::is_none")]
495 stop_reason: Option<String>,
496 #[serde(skip_serializing_if = "Option::is_none")]
497 stop_sequence: Option<String>,
498 #[serde(skip_serializing_if = "Option::is_none")]
499 usage: Option<Usage>,
500}
501
502#[derive(Debug, Clone, Serialize, Deserialize)]
503#[serde(untagged)]
504enum Content {
505 UntaggedText(String),
506 Chunks(Vec<ContentChunk>),
507}
508
509impl Content {
510 pub fn chunks(self) -> impl Iterator<Item = ContentChunk> {
511 match self {
512 Self::Chunks(chunks) => chunks.into_iter(),
513 Self::UntaggedText(text) => vec![ContentChunk::Text { text: text.clone() }].into_iter(),
514 }
515 }
516}
517
518impl Display for Content {
519 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520 match self {
521 Content::UntaggedText(txt) => write!(f, "{}", txt),
522 Content::Chunks(chunks) => {
523 for chunk in chunks {
524 write!(f, "{}", chunk)?;
525 }
526 Ok(())
527 }
528 }
529 }
530}
531
532#[derive(Debug, Clone, Serialize, Deserialize)]
533#[serde(tag = "type", rename_all = "snake_case")]
534enum ContentChunk {
535 Text {
536 text: String,
537 },
538 ToolUse {
539 id: String,
540 name: String,
541 input: serde_json::Value,
542 },
543 ToolResult {
544 content: Content,
545 tool_use_id: String,
546 },
547 // TODO
548 Image,
549 Document,
550 Thinking,
551 RedactedThinking,
552 WebSearchToolResult,
553 #[serde(untagged)]
554 UntaggedText(String),
555}
556
557impl Display for ContentChunk {
558 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
559 match self {
560 ContentChunk::Text { text } => write!(f, "{}", text),
561 ContentChunk::UntaggedText(text) => write!(f, "{}", text),
562 ContentChunk::ToolResult { content, .. } => write!(f, "{}", content),
563 ContentChunk::Image
564 | ContentChunk::Document
565 | ContentChunk::Thinking
566 | ContentChunk::RedactedThinking
567 | ContentChunk::ToolUse { .. }
568 | ContentChunk::WebSearchToolResult => {
569 write!(f, "\n{:?}\n", &self)
570 }
571 }
572 }
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize)]
576struct Usage {
577 input_tokens: u32,
578 cache_creation_input_tokens: u32,
579 cache_read_input_tokens: u32,
580 output_tokens: u32,
581 service_tier: String,
582}
583
584#[derive(Debug, Clone, Serialize, Deserialize)]
585#[serde(rename_all = "snake_case")]
586enum Role {
587 System,
588 Assistant,
589 User,
590}
591
592#[derive(Debug, Clone, Serialize, Deserialize)]
593struct MessageParam {
594 role: Role,
595 content: String,
596}
597
598#[derive(Debug, Clone, Serialize, Deserialize)]
599#[serde(tag = "type", rename_all = "snake_case")]
600enum SdkMessage {
601 // An assistant message
602 Assistant {
603 message: Message, // from Anthropic SDK
604 #[serde(skip_serializing_if = "Option::is_none")]
605 session_id: Option<String>,
606 },
607
608 // A user message
609 User {
610 message: Message, // from Anthropic SDK
611 #[serde(skip_serializing_if = "Option::is_none")]
612 session_id: Option<String>,
613 },
614
615 // Emitted as the last message in a conversation
616 Result {
617 subtype: ResultErrorType,
618 duration_ms: f64,
619 duration_api_ms: f64,
620 is_error: bool,
621 num_turns: i32,
622 #[serde(skip_serializing_if = "Option::is_none")]
623 result: Option<String>,
624 session_id: String,
625 total_cost_usd: f64,
626 },
627 // Emitted as the first message at the start of a conversation
628 System {
629 cwd: String,
630 session_id: String,
631 tools: Vec<String>,
632 model: String,
633 mcp_servers: Vec<McpServer>,
634 #[serde(rename = "apiKeySource")]
635 api_key_source: String,
636 #[serde(rename = "permissionMode")]
637 permission_mode: PermissionMode,
638 },
639}
640
641#[derive(Debug, Clone, Serialize, Deserialize)]
642#[serde(rename_all = "snake_case")]
643enum ResultErrorType {
644 Success,
645 ErrorMaxTurns,
646 ErrorDuringExecution,
647}
648
649impl Display for ResultErrorType {
650 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
651 match self {
652 ResultErrorType::Success => write!(f, "success"),
653 ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
654 ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
655 }
656 }
657}
658
659#[derive(Debug, Clone, Serialize, Deserialize)]
660struct McpServer {
661 name: String,
662 status: String,
663}
664
665#[derive(Debug, Clone, Serialize, Deserialize)]
666#[serde(rename_all = "camelCase")]
667enum PermissionMode {
668 Default,
669 AcceptEdits,
670 BypassPermissions,
671 Plan,
672}
673
674#[cfg(test)]
675pub(crate) mod tests {
676 use super::*;
677 use serde_json::json;
678
679 crate::common_e2e_tests!(ClaudeCode);
680
681 pub fn local_command() -> AgentServerCommand {
682 AgentServerCommand {
683 path: "claude".into(),
684 args: vec![],
685 env: None,
686 }
687 }
688
689 #[test]
690 fn test_deserialize_content_untagged_text() {
691 let json = json!("Hello, world!");
692 let content: Content = serde_json::from_value(json).unwrap();
693 match content {
694 Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
695 _ => panic!("Expected UntaggedText variant"),
696 }
697 }
698
699 #[test]
700 fn test_deserialize_content_chunks() {
701 let json = json!([
702 {
703 "type": "text",
704 "text": "Hello"
705 },
706 {
707 "type": "tool_use",
708 "id": "tool_123",
709 "name": "calculator",
710 "input": {"operation": "add", "a": 1, "b": 2}
711 }
712 ]);
713 let content: Content = serde_json::from_value(json).unwrap();
714 match content {
715 Content::Chunks(chunks) => {
716 assert_eq!(chunks.len(), 2);
717 match &chunks[0] {
718 ContentChunk::Text { text } => assert_eq!(text, "Hello"),
719 _ => panic!("Expected Text chunk"),
720 }
721 match &chunks[1] {
722 ContentChunk::ToolUse { id, name, input } => {
723 assert_eq!(id, "tool_123");
724 assert_eq!(name, "calculator");
725 assert_eq!(input["operation"], "add");
726 assert_eq!(input["a"], 1);
727 assert_eq!(input["b"], 2);
728 }
729 _ => panic!("Expected ToolUse chunk"),
730 }
731 }
732 _ => panic!("Expected Chunks variant"),
733 }
734 }
735
736 #[test]
737 fn test_deserialize_tool_result_untagged_text() {
738 let json = json!({
739 "type": "tool_result",
740 "content": "Result content",
741 "tool_use_id": "tool_456"
742 });
743 let chunk: ContentChunk = serde_json::from_value(json).unwrap();
744 match chunk {
745 ContentChunk::ToolResult {
746 content,
747 tool_use_id,
748 } => {
749 match content {
750 Content::UntaggedText(text) => assert_eq!(text, "Result content"),
751 _ => panic!("Expected UntaggedText content"),
752 }
753 assert_eq!(tool_use_id, "tool_456");
754 }
755 _ => panic!("Expected ToolResult variant"),
756 }
757 }
758
759 #[test]
760 fn test_deserialize_tool_result_chunks() {
761 let json = json!({
762 "type": "tool_result",
763 "content": [
764 {
765 "type": "text",
766 "text": "Processing complete"
767 },
768 {
769 "type": "text",
770 "text": "Result: 42"
771 }
772 ],
773 "tool_use_id": "tool_789"
774 });
775 let chunk: ContentChunk = serde_json::from_value(json).unwrap();
776 match chunk {
777 ContentChunk::ToolResult {
778 content,
779 tool_use_id,
780 } => {
781 match content {
782 Content::Chunks(chunks) => {
783 assert_eq!(chunks.len(), 2);
784 match &chunks[0] {
785 ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
786 _ => panic!("Expected Text chunk"),
787 }
788 match &chunks[1] {
789 ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
790 _ => panic!("Expected Text chunk"),
791 }
792 }
793 _ => panic!("Expected Chunks content"),
794 }
795 assert_eq!(tool_use_id, "tool_789");
796 }
797 _ => panic!("Expected ToolResult variant"),
798 }
799 }
800}