1use std::collections::VecDeque;
14use std::fmt;
15use std::future::Future;
16use std::path::PathBuf;
17use std::pin::Pin;
18use std::process::Stdio;
19use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering};
20use std::sync::{Arc, OnceLock, RwLock};
21use std::time::Duration;
22
23use dashmap::DashMap;
24use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
25use tokio::process::Command;
26use tokio::sync::{mpsc, oneshot, watch, Mutex};
27use tokio::task::JoinHandle;
28use tracing::Instrument;
29
30use crate::hooks::HookRegistry;
31use crate::mcp::{server_map, SdkMcpServer};
32use crate::protocol::{
33 Autocompact, CanUseToolRequest, ControlRequest, ControlRequestBody, ControlResponse, Effort,
34 ElicitationRequest, ElicitationResponse, InboundControlResponseBody, InboundMessage, Initialize,
35 OutboundControlRequest, PermissionMode, PermissionPrompts, ResultMessage, Thinking, ThinkingDisplay,
36 ToolDecision,
37 UserDialogRequest, UserDialogResponse,
38};
39
40#[derive(Debug, thiserror::Error)]
44#[non_exhaustive]
45pub enum SessionError {
46 #[error("io: {0}")]
48 Io(#[from] std::io::Error),
49 #[error("json: {0}")]
51 Json(#[from] serde_json::Error),
52 #[error("process exited (code: {code:?}); stderr tail:\n{stderr}")]
54 ProcessExited {
55 code: Option<i32>,
57 stderr: String,
59 },
60 #[error("session closed")]
62 Closed,
63 #[error("control request `{subtype}` failed: {error}")]
65 ControlError {
66 subtype: String,
68 error: String,
70 },
71 #[error("control request `{0}` timed out")]
74 ControlTimeout(String),
75 #[error("code mode: {0}")]
77 CodeMode(#[from] crate::code_mode::CodeModeError),
78 #[error("Claude Code {found} is older than {min}, the oldest version this SDK supports; run `claude update`")]
80 UnsupportedCliVersion {
81 found: String,
83 min: &'static str,
85 },
86 #[error("invalid recording: {0}")]
88 InvalidRecording(String),
89}
90
91pub type Result<T> = std::result::Result<T, SessionError>;
93
94const STATE_RUNNING: u8 = 0;
95const STATE_CLOSING: u8 = 1;
96const STATE_DEAD: u8 = 2;
97
98const STDERR_TAIL_LINES: usize = 40;
99const STDERR_LINGER: Duration = Duration::from_millis(500);
101const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(60);
102pub const DEFAULT_CONTROL_TIMEOUT: Duration = Duration::from_secs(60);
104pub const MIN_CLI_VERSION: &str = "2.1.329";
106const CLOSE_GRACE: Duration = Duration::from_secs(5);
108
109type PermFuture = Pin<Box<dyn Future<Output = ToolDecision> + Send + 'static>>;
112
113#[derive(Clone)]
116pub struct CanUseTool(Arc<dyn Fn(CanUseToolRequest) -> PermFuture + Send + Sync>);
117
118impl CanUseTool {
119 pub fn new<F, Fut>(f: F) -> Self
121 where
122 F: Fn(CanUseToolRequest) -> Fut + Send + Sync + 'static,
123 Fut: Future<Output = ToolDecision> + Send + 'static,
124 {
125 Self(Arc::new(move |req| Box::pin(f(req))))
126 }
127}
128
129type ElicitFuture = Pin<Box<dyn Future<Output = ElicitationResponse> + Send + 'static>>;
130
131#[derive(Clone)]
134pub struct OnElicitation(Arc<dyn Fn(ElicitationRequest) -> ElicitFuture + Send + Sync>);
135
136impl OnElicitation {
137 pub fn new<F, Fut>(f: F) -> Self
139 where
140 F: Fn(ElicitationRequest) -> Fut + Send + Sync + 'static,
141 Fut: Future<Output = ElicitationResponse> + Send + 'static,
142 {
143 Self(Arc::new(move |req| Box::pin(f(req))))
144 }
145}
146
147type DialogFuture = Pin<Box<dyn Future<Output = UserDialogResponse> + Send + 'static>>;
148
149#[derive(Clone)]
154pub struct OnUserDialog(Arc<dyn Fn(UserDialogRequest) -> DialogFuture + Send + Sync>);
155
156impl OnUserDialog {
157 pub fn new<F, Fut>(f: F) -> Self
159 where
160 F: Fn(UserDialogRequest) -> Fut + Send + Sync + 'static,
161 Fut: Future<Output = UserDialogResponse> + Send + 'static,
162 {
163 Self(Arc::new(move |req| Box::pin(f(req))))
164 }
165}
166
167#[derive(Clone)]
169pub struct OnStderr(Arc<dyn Fn(&str) + Send + Sync>);
170
171impl OnStderr {
172 pub fn new(f: impl Fn(&str) + Send + Sync + 'static) -> Self {
174 Self(Arc::new(f))
175 }
176}
177
178#[derive(Debug, Clone, Default)]
180pub struct McpCall {
181 pub timeout: Option<Duration>,
183 pub result_not_for_model: bool,
186 pub check_permissions: bool,
189}
190
191#[derive(Debug, Clone, Default)]
193pub struct ReloadPlugins {
194 pub add_plugins: Vec<serde_json::Value>,
196 pub hold_on_cache_impact: bool,
199 pub refuse_if_busy: bool,
201}
202
203macro_rules! opaque_debug {
204 ($($t:ident),*) => {$(
205 impl fmt::Debug for $t {
206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207 f.write_str(concat!(stringify!($t), "(..)"))
208 }
209 }
210 )*};
211}
212opaque_debug!(CanUseTool, OnElicitation, OnUserDialog, OnStderr);
213
214#[derive(Debug, Clone)]
216pub struct SessionOptions {
217 pub binary: PathBuf,
219 pub cwd: Option<PathBuf>,
221 pub model: Option<String>,
223 pub effort: Option<Effort>,
225 pub permission_mode: Option<PermissionMode>,
227 pub fallback_model: Option<String>,
230 pub thinking: Option<Thinking>,
232 pub thinking_display: Option<ThinkingDisplay>,
234 pub max_thinking_tokens: Option<u32>,
236 pub max_turns: Option<u32>,
239 pub max_budget_usd: Option<f64>,
242 pub task_budget: Option<u32>,
244 pub resume: Option<String>,
246 pub resume_session_at: Option<String>,
249 pub continue_conversation: bool,
251 pub fork_session: bool,
254 pub session_id: Option<String>,
256 pub persist_session: bool,
259 pub name: Option<String>,
261 pub code_mode: bool,
266 pub tool_search: bool,
269 pub include_partial: bool,
271 pub hooks: HookRegistry,
273 pub can_use_tool: Option<CanUseTool>,
276 pub mcp_servers: Vec<SdkMcpServer>,
279 pub allowed_tools: Vec<String>,
281 pub disallowed_tools: Vec<String>,
283 pub tools: Option<Vec<String>>,
286 pub add_dirs: Vec<PathBuf>,
288 pub strict_mcp_config: bool,
290 pub agent: Option<String>,
292 pub append_subagent_system_prompt: Option<String>,
295 pub plugin_dirs: Vec<PathBuf>,
297 pub betas: Vec<String>,
299 pub debug_file: Option<PathBuf>,
301 pub plugin_urls: Vec<String>,
303 pub files: Vec<String>,
305 pub autocompact: Option<Autocompact>,
307 pub permission_prompts: Option<PermissionPrompts>,
309 pub worktree: Option<Option<String>>,
312 pub bare: bool,
314 pub safe_mode: bool,
317 pub restricted: bool,
320 pub disable_slash_commands: bool,
322 pub brief: bool,
324 pub include_hook_events: bool,
327 pub extra_args: Vec<String>,
330 pub control_timeout: Duration,
332 pub on_elicitation: Option<OnElicitation>,
334 pub on_user_dialog: Option<OnUserDialog>,
336 pub on_stderr: Option<OnStderr>,
339 pub setting_sources: Option<Vec<String>>,
345 pub settings: Option<serde_json::Value>,
349 pub record: Option<PathBuf>,
351 pub clear_env: bool,
355 pub env: Vec<(String, String)>,
357}
358
359impl Default for SessionOptions {
360 fn default() -> Self {
361 Self {
362 binary: PathBuf::from("claude"),
363 cwd: None,
364 model: None,
365 effort: None,
366 permission_mode: None,
367 fallback_model: None,
368 thinking: None,
369 thinking_display: None,
370 max_thinking_tokens: None,
371 max_turns: None,
372 max_budget_usd: None,
373 task_budget: None,
374 resume: None,
375 resume_session_at: None,
376 continue_conversation: false,
377 fork_session: false,
378 session_id: None,
379 persist_session: true,
380 name: None,
381 code_mode: false,
382 tool_search: false,
383 include_partial: false,
384 hooks: HookRegistry::new(),
385 can_use_tool: None,
386 mcp_servers: vec![],
387 allowed_tools: vec![],
388 disallowed_tools: vec![],
389 tools: None,
390 add_dirs: vec![],
391 strict_mcp_config: false,
392 agent: None,
393 append_subagent_system_prompt: None,
394 plugin_dirs: vec![],
395 betas: vec![],
396 debug_file: None,
397 plugin_urls: vec![],
398 files: vec![],
399 autocompact: None,
400 permission_prompts: None,
401 worktree: None,
402 bare: false,
403 safe_mode: false,
404 restricted: false,
405 disable_slash_commands: false,
406 brief: false,
407 include_hook_events: false,
408 extra_args: vec![],
409 control_timeout: DEFAULT_CONTROL_TIMEOUT,
410 on_elicitation: None,
411 on_user_dialog: None,
412 on_stderr: None,
413 setting_sources: None,
414 settings: None,
415 record: None,
416 clear_env: false,
417 env: vec![],
418 }
419 }
420}
421
422pub type EventRx = mpsc::UnboundedReceiver<Arc<InboundMessage>>;
427
428#[derive(Default)]
431struct Fanout {
432 subs: Vec<mpsc::UnboundedSender<Arc<InboundMessage>>>,
433 ended: bool,
434}
435
436fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
437 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
438}
439
440type Pending = DashMap<String, oneshot::Sender<InboundControlResponseBody>>;
441
442#[derive(Debug, Clone)]
444pub(crate) struct ExitInfo {
445 pub(crate) code: Option<i32>,
446 pub(crate) stderr: String,
447}
448
449pub(crate) struct Transport {
451 pub(crate) stdin: Box<dyn AsyncWrite + Unpin + Send>,
452 pub(crate) stdout: Box<dyn AsyncRead + Unpin + Send>,
453 pub(crate) exit: Pin<Box<dyn Future<Output = ExitInfo> + Send>>,
455 pub(crate) pgid: Option<i32>,
458}
459
460#[derive(Clone)]
466pub struct Session(Arc<SessionInner>);
467
468#[derive(Clone)]
470pub struct WeakSession(std::sync::Weak<SessionInner>);
471
472impl WeakSession {
473 pub fn upgrade(&self) -> Option<Session> {
475 self.0.upgrade().map(Session)
476 }
477}
478
479impl fmt::Debug for WeakSession {
480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481 f.write_str("WeakSession(..)")
482 }
483}
484
485struct SessionInner {
486 session_id: Arc<RwLock<Option<String>>>,
489 stdin_tx: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
492 fanout: Arc<std::sync::Mutex<Fanout>>,
493 pending: Arc<Pending>,
495 next_request_id: AtomicU64,
496 state: Arc<AtomicU8>,
497 exit: watch::Receiver<Option<ExitInfo>>,
498 pgid: Option<i32>,
499 include_partial: bool,
500 initialize_response: OnceLock<serde_json::Value>,
501 cli_version: OnceLock<String>,
502 control_timeout: Duration,
503 responder: Arc<Responder>,
504 turns_in_flight: Arc<AtomicUsize>,
506 reader_done: watch::Receiver<bool>,
508 _tasks: [JoinHandle<()>; 3],
509}
510
511struct Responder {
513 stdin_tx: mpsc::WeakSender<Vec<u8>>,
516 hooks: HookRegistry,
517 can_use_tool: Option<CanUseTool>,
518 on_elicitation: Option<OnElicitation>,
519 on_user_dialog: Option<OnUserDialog>,
520 mcp_servers: Vec<SdkMcpServer>,
522 dynamic_mcp_servers: RwLock<Vec<SdkMcpServer>>,
524 in_flight: DashMap<String, tokio::task::AbortHandle>,
527}
528
529impl Session {
530 pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self> {
537 let binary = if opts.code_mode {
538 crate::code_mode::patched_binary(&opts.binary).await?
539 } else {
540 opts.binary.clone()
541 };
542 let mut cmd = Command::new(&binary);
543 if opts.clear_env {
545 cmd.env_clear();
546 }
547 cmd.args([
548 "--output-format", "stream-json",
549 "--verbose",
550 "--input-format", "stream-json",
551 "--await-initialize",
552 "--replay-user-messages",
555 ]);
556 if opts.include_partial {
557 cmd.arg("--include-partial-messages");
558 }
559 if let Some(ref m) = opts.model {
560 cmd.args(["--model", m]);
561 }
562 cmd.args(cli_args(&opts));
563 let allowed: Vec<String> = opts.allowed_tools.iter().cloned()
564 .chain(opts.mcp_servers.iter().flat_map(SdkMcpServer::qualified_tool_names))
565 .collect();
566 if !allowed.is_empty() {
567 cmd.args(["--allowedTools", &allowed.join(",")]);
568 }
569 if !opts.disallowed_tools.is_empty() {
570 cmd.args(["--disallowedTools", &opts.disallowed_tools.join(",")]);
571 }
572 let settings = match (&opts.settings, opts.code_mode) {
573 (Some(serde_json::Value::String(path)), true) => {
575 Some(read_settings_file(path, opts.cwd.as_deref()).await?)
576 }
577 (settings, _) => settings.clone(),
578 };
579 match settings_arg(settings, opts.code_mode)? {
580 Some(serde_json::Value::String(path)) => {
582 cmd.args(["--settings", &path]);
583 }
584 Some(settings) => {
585 cmd.args(["--settings", &settings.to_string()]);
586 }
587 None => {}
588 }
589 cmd.args(&opts.extra_args);
590 if let Some(ref cwd) = opts.cwd {
591 cmd.current_dir(cwd);
592 }
593 cmd.env("CLAUDE_CODE_ENTRYPOINT", "sdk-cli");
597 if opts.code_mode {
598 cmd.env("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE", "1");
599 }
600 if opts.tool_search {
601 cmd.env("ENABLE_TOOL_SEARCH", "1");
602 }
603 for (k, v) in &opts.env {
604 cmd.env(k, v);
605 }
606 cmd.stdin(Stdio::piped())
607 .stdout(Stdio::piped())
608 .stderr(Stdio::piped())
609 .kill_on_drop(false); #[cfg(unix)]
613 cmd.process_group(0);
614
615 let record = open_record(&opts).await?;
617 let mut child = cmd.spawn()?;
618 let pgid = child.id().and_then(|id| i32::try_from(id).ok());
619 let (Some(stdin), Some(stdout), Some(stderr)) =
620 (child.stdin.take(), child.stdout.take(), child.stderr.take())
621 else {
622 return Err(SessionError::Io(std::io::Error::other("subprocess pipes missing")));
623 };
624 let tail = Arc::new(std::sync::Mutex::new(VecDeque::with_capacity(STDERR_TAIL_LINES)));
625 let mut drain = tokio::spawn(drain_stderr(stderr, opts.on_stderr.clone(), tail.clone()));
626 let exit = Box::pin(async move {
627 let code = child.wait().await.ok().and_then(|s| s.code());
630 if tokio::time::timeout(STDERR_LINGER, &mut drain).await.is_err() {
631 drain.abort();
632 }
633 let stderr = Vec::from(std::mem::take(&mut *lock(&tail))).join("\n");
634 ExitInfo { code, stderr }
635 });
636 let transport = Transport { stdin: Box::new(stdin), stdout: Box::new(stdout), exit, pgid };
637 Self::connect(transport, opts, init, record).await
638 }
639
640 pub(crate) async fn connect(
643 transport: Transport,
644 opts: SessionOptions,
645 mut init: Initialize,
646 record: Option<tokio::fs::File>,
647 ) -> Result<Self> {
648 let Transport { stdin, stdout, exit: exit_fut, pgid } = transport;
649 let (stdin_tx, mut stdin_rx) = mpsc::channel::<Vec<u8>>(256);
650 let fanout = Arc::new(std::sync::Mutex::new(Fanout::default()));
651 let session_id = Arc::new(RwLock::new(None));
652 let pending: Arc<Pending> = Arc::new(DashMap::new());
653 let state = Arc::new(AtomicU8::new(STATE_RUNNING));
654 let (exit_tx, exit_rx) = watch::channel(None);
655 let (reader_done_tx, reader_done) = watch::channel(false);
656 let turns_in_flight = Arc::new(AtomicUsize::new(0));
657
658 let writer = tokio::spawn(async move {
659 let mut w = BufWriter::new(stdin);
660 while let Some(bytes) = stdin_rx.recv().await {
661 if w.write_all(&bytes).await.is_err()
662 || w.write_all(b"\n").await.is_err()
663 || w.flush().await.is_err()
664 {
665 break;
666 }
667 }
668 let _ = w.shutdown().await;
669 });
670
671 let state2 = state.clone();
672 let watchdog = tokio::spawn(async move {
673 let info = exit_fut.await;
674 state2.store(STATE_DEAD, Ordering::SeqCst);
675 let _ = exit_tx.send(Some(info));
676 });
677
678 let responder = Arc::new(Responder {
679 stdin_tx: stdin_tx.downgrade(),
680 hooks: opts.hooks.clone(),
681 can_use_tool: opts.can_use_tool.clone(),
682 on_elicitation: opts.on_elicitation.clone(),
683 on_user_dialog: opts.on_user_dialog.clone(),
684 mcp_servers: opts.mcp_servers.clone(),
685 dynamic_mcp_servers: RwLock::new(vec![]),
686 in_flight: DashMap::new(),
687 });
688 let reader = tokio::spawn(read_loop(stdout, Reader {
689 record,
690 fanout: fanout.clone(),
691 session_id: session_id.clone(),
692 pending: pending.clone(),
693 turns_in_flight: turns_in_flight.clone(),
694 responder: responder.clone(),
695 done: reader_done_tx,
696 }));
697
698 let session = Session(Arc::new(SessionInner {
699 session_id,
700 stdin_tx: Mutex::new(Some(stdin_tx)),
701 fanout,
702 pending,
703 next_request_id: AtomicU64::new(0),
704 state,
705 exit: exit_rx,
706 pgid,
707 include_partial: opts.include_partial,
708 initialize_response: OnceLock::new(),
709 cli_version: OnceLock::new(),
710 control_timeout: opts.control_timeout,
711 responder,
712 turns_in_flight,
713 reader_done,
714 _tasks: [reader, writer, watchdog],
715 }));
716
717 init.hooks = opts.hooks.initialize_config();
718 let body = serde_json::to_value(&init)?;
719 let body = with_subtype(body, "initialize");
720 let response = session.request_with_timeout(&body, INITIALIZE_TIMEOUT).await?;
721 let _ = session.0.initialize_response.set(response);
722 session.check_cli_version().await?;
723 Ok(session)
724 }
725
726 async fn check_cli_version(&self) -> Result<()> {
729 let reply = self.control(&serde_json::json!({ "subtype": "get_binary_version" })).await;
730 let version = match reply {
731 Ok(v) => v.get("version").and_then(|v| v.as_str()).map(str::to_owned),
732 Err(e) => {
733 tracing::warn!(error = %e, "could not read the Claude Code version");
734 None
735 }
736 };
737 let Some(version) = version else { return Ok(()) };
738 if version_lt(&version, MIN_CLI_VERSION) {
739 self.close().await;
740 return Err(SessionError::UnsupportedCliVersion { found: version, min: MIN_CLI_VERSION });
741 }
742 let _ = self.0.cli_version.set(version);
743 Ok(())
744 }
745
746 pub async fn reconnect(previous_id: &str, mut opts: SessionOptions, init: Initialize) -> Result<Self> {
748 opts.resume = Some(previous_id.to_string());
749 Self::spawn(opts, init).await
750 }
751
752 pub async fn send<T: serde::Serialize>(&self, msg: &T) -> Result<()> {
754 if self.0.state.load(Ordering::Acquire) != STATE_RUNNING {
755 return Err(self.dead_error().await);
756 }
757 let bytes = serde_json::to_vec(msg)?;
758 let tx = self.0.stdin_tx.lock().await.clone().ok_or(SessionError::Closed)?;
759 tx.send(bytes).await.map_err(|_| SessionError::Closed)
760 }
761
762 pub async fn control<B: serde::Serialize>(&self, body: &B) -> Result<serde_json::Value> {
765 self.request_with_timeout(body, self.0.control_timeout).await
766 }
767
768 pub async fn interrupt(&self) -> Result<()> {
772 self.control(&serde_json::json!({ "subtype": "interrupt" })).await.map(|_| ())
773 }
774
775 pub async fn interrupt_all(&self) -> Result<()> {
778 let reply = self.control(&serde_json::json!({ "subtype": "interrupt", "cancel_queued": true })).await?;
779 let cancelled = reply.get("cancelled").and_then(|c| c.as_array()).map_or(0, Vec::len);
781 for _ in 0..cancelled {
782 decrement(&self.0.turns_in_flight);
783 }
784 Ok(())
785 }
786
787 pub async fn set_model(&self, model: Option<&str>) -> Result<()> {
791 self.control(&serde_json::json!({ "subtype": "set_model", "model": model })).await.map(|_| ())
792 }
793
794 pub async fn set_model_and_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
799 self.control(&serde_json::json!({
800 "subtype": "set_model", "model": model, "system_prompt": system_prompt,
801 }))
802 .await
803 .map(|_| ())
804 }
805
806 pub async fn set_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
814 self.control(&serde_json::json!({
815 "subtype": "set_model", "model": model, "system_prompt": system_prompt,
816 "only_if_model_is_current": true,
817 }))
818 .await
819 .map(|_| ())
820 }
821
822 pub async fn set_max_thinking_tokens(&self, tokens: Option<u32>, display: Option<ThinkingDisplay>) -> Result<()> {
826 let mut body = serde_json::json!({ "subtype": "set_max_thinking_tokens", "max_thinking_tokens": tokens });
827 if let Some(d) = display {
828 body["thinking_display"] = d.as_str().into();
829 }
830 self.control(&body).await.map(|_| ())
831 }
832
833 pub async fn set_effort(&self, effort: Option<Effort>) -> Result<()> {
838 let settings = serde_json::json!({ "effortLevel": effort });
839 self.control(&serde_json::json!({ "subtype": "apply_flag_settings", "settings": settings }))
840 .await
841 .map(|_| ())
842 }
843
844 pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()> {
846 self.control(&serde_json::json!({ "subtype": "set_permission_mode", "mode": mode })).await.map(|_| ())
847 }
848
849 pub async fn stop_task(&self, task_id: &str) -> Result<()> {
852 self.control(&serde_json::json!({ "subtype": "stop_task", "task_id": task_id })).await.map(|_| ())
853 }
854
855 pub async fn context_usage(&self, exact: bool) -> Result<serde_json::Value> {
860 let detail = if exact { "full" } else { "summary" };
861 self.control(&serde_json::json!({ "subtype": "get_context_usage", "detail": detail })).await
862 }
863
864 pub async fn cancel_prompt(&self, uuid: &str) -> Result<()> {
869 let dropped = self
870 .control(&serde_json::json!({ "subtype": "cancel_async_message", "message_uuid": uuid }))
871 .await?;
872 if dropped.get("cancelled").and_then(serde_json::Value::as_bool) == Some(true) {
873 decrement(&self.0.turns_in_flight);
875 return Ok(());
876 }
877 self.control(&serde_json::json!({ "subtype": "interrupt", "for_user_message_uuids": [uuid] }))
878 .await
879 .map(|_| ())
880 }
881
882 pub async fn rename_session(&self, title: &str) -> Result<()> {
884 self.control(&serde_json::json!({ "subtype": "rename_session", "title": title })).await.map(|_| ())
885 }
886
887 pub async fn rewind_files(&self, user_message_id: &str, dry_run: bool) -> Result<serde_json::Value> {
891 self.control(&serde_json::json!({
892 "subtype": "rewind_files", "user_message_id": user_message_id, "dry_run": dry_run,
893 }))
894 .await
895 }
896
897 pub async fn mcp_status(&self) -> Result<serde_json::Value> {
899 self.control(&serde_json::json!({ "subtype": "mcp_status" })).await
900 }
901
902 pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()> {
904 self.control(&serde_json::json!({ "subtype": "mcp_toggle", "serverName": server, "enabled": enabled }))
905 .await
906 .map(|_| ())
907 }
908
909 pub async fn mcp_reconnect(&self, server: &str) -> Result<()> {
911 self.control(&serde_json::json!({ "subtype": "mcp_reconnect", "serverName": server })).await.map(|_| ())
912 }
913
914 pub async fn set_mcp_servers(
920 &self,
921 sdk: Vec<SdkMcpServer>,
922 external: serde_json::Map<String, serde_json::Value>,
923 ) -> Result<serde_json::Value> {
924 let servers = server_map(&sdk, Some(&external));
925 *self.0.responder.dynamic_mcp_servers.write().unwrap_or_else(std::sync::PoisonError::into_inner) = sdk;
926 self.control(&serde_json::json!({ "subtype": "mcp_set_servers", "servers": servers })).await
927 }
928
929 pub async fn list_models(&self) -> Result<serde_json::Value> {
931 self.control(&serde_json::json!({ "subtype": "list_models" })).await
932 }
933
934 pub async fn get_settings(&self) -> Result<serde_json::Value> {
937 self.control(&serde_json::json!({ "subtype": "get_settings" })).await
938 }
939
940 pub async fn update_settings(&self, local: bool, settings: serde_json::Value) -> Result<serde_json::Value> {
944 let source = if local { "localSettings" } else { "userSettings" };
945 self.control(&serde_json::json!({ "subtype": "update_settings", "source": source, "settings": settings }))
946 .await
947 }
948
949 pub async fn get_usage(&self, skip_behaviors: bool) -> Result<serde_json::Value> {
954 self.control(&serde_json::json!({ "subtype": "get_usage", "skip_behaviors": skip_behaviors })).await
955 }
956
957 pub async fn reload_skills(&self) -> Result<serde_json::Value> {
959 self.control(&serde_json::json!({ "subtype": "reload_skills" })).await
960 }
961
962 pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<serde_json::Value> {
964 let mut body = serde_json::json!({
965 "subtype": "reload_plugins",
966 "hold_on_cache_impact": opts.hold_on_cache_impact,
967 "refuse_if_busy": opts.refuse_if_busy,
968 });
969 if !opts.add_plugins.is_empty() {
970 body["add_plugins"] = serde_json::json!(opts.add_plugins);
971 }
972 self.control(&body).await
973 }
974
975 pub async fn task_output(&self, task_id: &str) -> Result<serde_json::Value> {
978 self.control(&serde_json::json!({ "subtype": "get_task_output", "task_id": task_id })).await
979 }
980
981 pub async fn register_repo_root(&self, directory: &str) -> Result<serde_json::Value> {
985 self.control(&serde_json::json!({
986 "subtype": "register_repo_root", "directory": directory,
987 "reload_claude_md": true, "reload_plugins": true, "reload_skills": true,
988 }))
989 .await
990 }
991
992 pub async fn mcp_call(&self, tool: &str, arguments: serde_json::Value, opts: McpCall) -> Result<serde_json::Value> {
997 let mut body = serde_json::json!({ "subtype": "mcp_call", "tool": tool, "arguments": arguments });
998 if let Some(t) = opts.timeout {
999 body["timeout_ms"] = serde_json::json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
1000 }
1001 if opts.result_not_for_model {
1002 body["result_not_for_model"] = true.into();
1003 }
1004 if opts.check_permissions {
1005 body["check_permissions"] = true.into();
1006 }
1007 self.control(&body).await
1008 }
1009
1010 pub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<serde_json::Value> {
1013 self.control(&serde_json::json!({ "subtype": "mcp_read_resource", "serverName": server, "uri": uri }))
1014 .await
1015 }
1016
1017 pub async fn read_file(&self, path: &str, max_bytes: Option<u64>, base64: bool) -> Result<serde_json::Value> {
1021 let mut body = serde_json::json!({
1022 "subtype": "read_file", "path": path,
1023 "encoding": if base64 { "base64" } else { "utf-8" },
1024 });
1025 if let Some(n) = max_bytes {
1026 body["max_bytes"] = n.into();
1027 }
1028 self.control(&body).await
1029 }
1030
1031 pub async fn file_suggestions(&self, query: &str) -> Result<serde_json::Value> {
1034 self.control(&serde_json::json!({ "subtype": "file_suggestions", "query": query })).await
1035 }
1036
1037 pub async fn hooks_listing(&self) -> Result<serde_json::Value> {
1040 self.control(&serde_json::json!({ "subtype": "get_hooks_listing" })).await
1041 }
1042
1043 pub async fn permission_rules(&self) -> Result<serde_json::Value> {
1046 self.control(&serde_json::json!({ "subtype": "list_permission_rules" })).await
1047 }
1048
1049 pub async fn session_cost(&self) -> Result<serde_json::Value> {
1052 self.control(&serde_json::json!({ "subtype": "get_session_cost" })).await
1053 }
1054
1055 pub async fn reload_output_styles(&self) -> Result<serde_json::Value> {
1057 self.control(&serde_json::json!({ "subtype": "reload_output_styles" })).await
1058 }
1059
1060 pub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()> {
1063 self.control(&serde_json::json!({ "subtype": "seed_read_state", "path": path, "mtime": mtime_ms }))
1064 .await
1065 .map(|_| ())
1066 }
1067
1068 #[must_use]
1070 pub fn downgrade(&self) -> WeakSession {
1071 WeakSession(Arc::downgrade(&self.0))
1072 }
1073
1074 #[must_use]
1076 pub fn pid(&self) -> Option<u32> {
1077 self.0.pgid.and_then(|p| u32::try_from(p).ok())
1078 }
1079
1080 pub fn cli_version(&self) -> Option<&str> {
1082 self.0.cli_version.get().map(String::as_str)
1083 }
1084
1085 #[must_use = "frames buffer until the receiver is dropped"]
1089 pub fn subscribe(&self) -> EventRx {
1090 let (tx, rx) = mpsc::unbounded_channel();
1091 let mut fanout = lock(&self.0.fanout);
1092 if !fanout.ended {
1093 fanout.subs.push(tx);
1094 }
1095 rx
1096 }
1097
1098 pub fn session_id(&self) -> Option<String> {
1101 self.0.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
1102 }
1103
1104 #[must_use]
1106 pub fn initialize_response(&self) -> Option<&serde_json::Value> {
1107 self.0.initialize_response.get()
1108 }
1109
1110 #[must_use]
1113 pub fn include_partial(&self) -> bool {
1114 self.0.include_partial
1115 }
1116
1117 #[must_use]
1119 pub fn is_busy(&self) -> bool {
1120 self.0.turns_in_flight.load(Ordering::Acquire) > 0
1121 }
1122
1123 pub(crate) async fn send_prompt(&self, message: &crate::protocol::UserMessage) -> Result<()> {
1126 self.0.turns_in_flight.fetch_add(1, Ordering::AcqRel);
1127 let sent = self.send(message).await;
1128 if sent.is_err() {
1129 decrement(&self.0.turns_in_flight);
1130 }
1131 sent
1132 }
1133
1134 #[must_use]
1136 pub fn is_alive(&self) -> bool {
1137 self.0.state.load(Ordering::Acquire) == STATE_RUNNING
1138 }
1139
1140 pub async fn close(&self) -> Option<i32> {
1145 let _ = self.0.state.compare_exchange(STATE_RUNNING, STATE_CLOSING, Ordering::SeqCst, Ordering::SeqCst);
1146 self.0.stdin_tx.lock().await.take();
1147 let mut exit = self.wait_exit(CLOSE_GRACE).await;
1148 #[cfg(unix)]
1149 for signal in [nix::sys::signal::Signal::SIGTERM, nix::sys::signal::Signal::SIGKILL] {
1150 if exit.is_some() {
1151 break;
1152 }
1153 self.signal_group(signal);
1154 exit = self.wait_exit(CLOSE_GRACE).await;
1155 }
1156 #[cfg(unix)]
1158 self.signal_group(nix::sys::signal::Signal::SIGTERM);
1159 #[cfg(not(unix))]
1160 if exit.is_none() {
1161 kill_tree(self.0.pgid);
1162 exit = self.wait_exit(CLOSE_GRACE).await;
1163 }
1164 let mut done = self.0.reader_done.clone();
1166 let _ = tokio::time::timeout(CLOSE_GRACE, done.wait_for(|d| *d)).await;
1167 exit.and_then(|e| e.code)
1168 }
1169
1170 async fn wait_exit(&self, timeout: Duration) -> Option<ExitInfo> {
1171 let mut rx = self.0.exit.clone();
1172 let waited = tokio::time::timeout(timeout, async {
1173 rx.wait_for(Option::is_some).await.ok().and_then(|info| info.clone())
1174 })
1175 .await;
1176 waited.ok().flatten()
1177 }
1178
1179 #[cfg(unix)]
1180 fn signal_group(&self, signal: nix::sys::signal::Signal) {
1181 if let Some(pgid) = self.0.pgid {
1182 let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), signal);
1183 }
1184 }
1185
1186 async fn request_with_timeout<B: serde::Serialize>(
1189 &self,
1190 body: &B,
1191 timeout: Duration,
1192 ) -> Result<serde_json::Value> {
1193 let n = self.0.next_request_id.fetch_add(1, Ordering::Relaxed);
1194 let request_id = format!("req_{n}_{}", std::process::id());
1195 let subtype = serde_json::to_value(body)?
1196 .get("subtype")
1197 .and_then(|s| s.as_str())
1198 .unwrap_or("?")
1199 .to_string();
1200
1201 let (tx, rx) = oneshot::channel();
1203 self.0.pending.insert(request_id.clone(), tx);
1204 let _registered = PendingGuard { pending: &self.0.pending, request_id: &request_id };
1206 if lock(&self.0.fanout).ended {
1209 return Err(self.dead_error().await);
1210 }
1211 let envelope = OutboundControlRequest { kind: "control_request", request_id: &request_id, request: body };
1212 self.send(&envelope).await?;
1213
1214 let reply = match tokio::time::timeout(timeout, rx).await {
1215 Ok(Ok(reply)) => reply,
1216 Ok(Err(_)) => return Err(self.dead_error().await),
1218 Err(_) => return Err(SessionError::ControlTimeout(subtype)),
1219 };
1220 match reply.subtype.as_str() {
1221 "success" => Ok(reply.response.unwrap_or(serde_json::Value::Null)),
1222 _ => Err(SessionError::ControlError {
1223 subtype,
1224 error: reply.error.unwrap_or_else(|| "unknown error".into()),
1225 }),
1226 }
1227 }
1228
1229 async fn dead_error(&self) -> SessionError {
1231 if self.0.state.load(Ordering::Acquire) == STATE_CLOSING {
1232 return SessionError::Closed;
1233 }
1234 match self.wait_exit(Duration::from_secs(1)).await {
1236 Some(ExitInfo { code, stderr }) => SessionError::ProcessExited { code, stderr },
1237 None => SessionError::Closed,
1238 }
1239 }
1240}
1241
1242struct PendingGuard<'a> {
1244 pending: &'a Pending,
1245 request_id: &'a str,
1246}
1247
1248impl Drop for PendingGuard<'_> {
1249 fn drop(&mut self) {
1250 self.pending.remove(self.request_id);
1251 }
1252}
1253
1254impl Drop for SessionInner {
1255 fn drop(&mut self) {
1260 #[cfg(unix)]
1261 if let Some(pgid) = self.pgid
1262 && self.state.load(Ordering::Acquire) != STATE_DEAD
1263 {
1264 use nix::sys::signal::{killpg, Signal};
1265 let group = nix::unistd::Pid::from_raw(pgid);
1266 let _ = killpg(group, Signal::SIGTERM);
1267 if let Ok(runtime) = tokio::runtime::Handle::try_current() {
1268 let mut exit = self.exit.clone();
1269 runtime.spawn(async move {
1270 let exited = tokio::time::timeout(CLOSE_GRACE, exit.wait_for(Option::is_some)).await;
1271 if !matches!(exited, Ok(Ok(_))) {
1272 let _ = killpg(group, Signal::SIGKILL);
1273 }
1274 });
1275 }
1276 }
1277 #[cfg(not(unix))]
1278 if self.state.load(Ordering::Acquire) != STATE_DEAD {
1279 kill_tree(self.pgid);
1280 }
1281 }
1282}
1283
1284async fn drain_stderr(
1287 stderr: tokio::process::ChildStderr,
1288 on_stderr: Option<OnStderr>,
1289 tail: Arc<std::sync::Mutex<VecDeque<String>>>,
1290) {
1291 let mut lines = BufReader::new(stderr).lines();
1292 while let Ok(Some(line)) = lines.next_line().await {
1293 if let Some(cb) = &on_stderr
1294 && std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (cb.0)(&line))).is_err()
1295 {
1296 tracing::warn!("on_stderr callback panicked");
1297 }
1298 let mut tail = lock(&tail);
1299 if tail.len() == STDERR_TAIL_LINES {
1300 tail.pop_front();
1301 }
1302 tail.push_back(line);
1303 }
1304}
1305
1306#[cfg(not(unix))]
1308fn kill_tree(pid: Option<i32>) {
1309 if let Some(pid) = pid {
1310 let _ = std::process::Command::new("taskkill")
1311 .args(["/PID", &pid.to_string(), "/T", "/F"])
1312 .stdout(Stdio::null())
1313 .stderr(Stdio::null())
1314 .status();
1315 }
1316}
1317
1318fn cli_args(opts: &SessionOptions) -> Vec<String> {
1320 let mut args: Vec<String> = vec![];
1321 let mut flag = |name: &str, value: Option<String>| {
1322 if let Some(v) = value {
1323 args.push(name.into());
1324 args.push(v);
1325 }
1326 };
1327 flag("--model", opts.model.clone());
1328 flag("--effort", opts.effort.map(|e| e.as_str().into()));
1329 flag("--permission-mode", opts.permission_mode.map(|m| m.as_str().into()));
1330 flag("--fallback-model", opts.fallback_model.clone());
1331 flag("--thinking", opts.thinking.map(|t| t.as_str().into()));
1332 flag("--thinking-display", opts.thinking_display.map(|d| d.as_str().into()));
1333 flag("--max-thinking-tokens", opts.max_thinking_tokens.map(|n| n.to_string()));
1334 flag("--max-turns", opts.max_turns.map(|n| n.to_string()));
1335 flag("--max-budget-usd", opts.max_budget_usd.map(|n| n.to_string()));
1336 flag("--task-budget", opts.task_budget.map(|n| n.to_string()));
1337 flag("--resume", opts.resume.clone());
1338 flag("--resume-session-at", opts.resume_session_at.clone());
1339 flag("--session-id", opts.session_id.clone());
1340 flag("--name", opts.name.clone());
1341 flag("--tools", opts.tools.as_ref().map(|t| t.join(",")));
1342 flag("--agent", opts.agent.clone());
1343 flag("--append-subagent-system-prompt", opts.append_subagent_system_prompt.clone());
1344 flag("--betas", (!opts.betas.is_empty()).then(|| opts.betas.join(",")));
1345 flag("--debug-file", opts.debug_file.as_ref().map(|p| p.display().to_string()));
1346 flag("--setting-sources", opts.setting_sources.as_ref().map(|s| s.join(",")));
1347 flag("--permission-prompt-tool", opts.can_use_tool.as_ref().map(|_| "stdio".into()));
1348 flag(
1349 "--mcp-config",
1350 (!opts.mcp_servers.is_empty())
1351 .then(|| serde_json::json!({ "mcpServers": server_map(&opts.mcp_servers, None) }).to_string()),
1352 );
1353 for dir in &opts.add_dirs {
1354 flag("--add-dir", Some(dir.display().to_string()));
1355 }
1356 for dir in &opts.plugin_dirs {
1357 flag("--plugin-dir", Some(dir.display().to_string()));
1358 }
1359 for url in &opts.plugin_urls {
1360 flag("--plugin-url", Some(url.clone()));
1361 }
1362 for spec in &opts.files {
1363 flag("--file", Some(spec.clone()));
1364 }
1365 flag("--autocompact", opts.autocompact.map(super::protocol::Autocompact::to_arg));
1366 flag("--permission-prompts", opts.permission_prompts.map(|p| p.as_str().into()));
1367 if let Some(Some(name)) = &opts.worktree {
1368 flag("--worktree", Some(name.clone()));
1369 }
1370 if let Some(None) = opts.worktree {
1371 args.push("--worktree".into());
1372 }
1373 for (on, name) in [
1374 (opts.bare, "--bare"),
1375 (opts.safe_mode, "--safe-mode"),
1376 (opts.restricted, "--restricted"),
1377 (opts.disable_slash_commands, "--disable-slash-commands"),
1378 (opts.brief, "--brief"),
1379 (opts.include_hook_events, "--include-hook-events"),
1380 ] {
1381 if on {
1382 args.push(name.into());
1383 }
1384 }
1385 if opts.continue_conversation {
1386 args.push("--continue".into());
1387 }
1388 if opts.fork_session {
1389 args.push("--fork-session".into());
1390 }
1391 if !opts.persist_session {
1392 args.push("--no-session-persistence".into());
1393 }
1394 if opts.strict_mcp_config {
1395 args.push("--strict-mcp-config".into());
1396 }
1397 args
1398}
1399
1400fn version_lt(a: &str, b: &str) -> bool {
1402 let parse = |v: &str| -> Vec<u64> {
1403 v.split(['.', '-', ' '])
1404 .map_while(|part| part.parse().ok())
1405 .collect()
1406 };
1407 parse(a) < parse(b)
1408}
1409
1410fn decrement(n: &AtomicUsize) {
1412 let mut current = n.load(Ordering::Acquire);
1413 while current > 0 {
1414 match n.compare_exchange_weak(current, current - 1, Ordering::AcqRel, Ordering::Acquire) {
1415 Ok(_) => break,
1416 Err(actual) => current = actual,
1417 }
1418 }
1419}
1420
1421pub(crate) async fn open_record(opts: &SessionOptions) -> Result<Option<tokio::fs::File>> {
1423 match &opts.record {
1424 Some(path) => Ok(Some(tokio::fs::File::create(path).await?)),
1425 None => Ok(None),
1426 }
1427}
1428
1429async fn read_settings_file(path: &str, cwd: Option<&std::path::Path>) -> Result<serde_json::Value> {
1432 let path = match cwd {
1433 Some(dir) => dir.join(path),
1434 None => PathBuf::from(path),
1435 };
1436 Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
1437}
1438
1439fn settings_arg(settings: Option<serde_json::Value>, code_mode: bool) -> Result<Option<serde_json::Value>> {
1442 if !code_mode {
1443 return Ok(settings);
1444 }
1445 let mut settings = settings.unwrap_or_else(|| serde_json::json!({}));
1446 let env = settings
1447 .as_object_mut()
1448 .map(|obj| obj.entry("env").or_insert_with(|| serde_json::json!({})))
1449 .and_then(serde_json::Value::as_object_mut)
1450 .ok_or(crate::code_mode::CodeModeError::Settings)?;
1451 env.insert("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE".into(), "1".into());
1452 Ok(Some(settings))
1453}
1454
1455fn with_subtype(mut body: serde_json::Value, subtype: &str) -> serde_json::Value {
1456 if let Some(obj) = body.as_object_mut() {
1457 obj.insert("subtype".into(), subtype.into());
1458 }
1459 body
1460}
1461
1462struct Reader {
1464 record: Option<tokio::fs::File>,
1465 fanout: Arc<std::sync::Mutex<Fanout>>,
1466 session_id: Arc<RwLock<Option<String>>>,
1467 pending: Arc<Pending>,
1468 turns_in_flight: Arc<AtomicUsize>,
1469 responder: Arc<Responder>,
1470 done: watch::Sender<bool>,
1471}
1472
1473async fn read_loop(stdout: Box<dyn AsyncRead + Unpin + Send>, reader: Reader) {
1474 let Reader { record, fanout, session_id, pending, turns_in_flight, responder, done } = reader;
1475 let cleanup = ReaderCleanup {
1477 fanout: fanout.clone(),
1478 pending,
1479 turns_in_flight: turns_in_flight.clone(),
1480 responder: responder.clone(),
1481 done,
1482 };
1483 let mut record = record.map(BufWriter::new);
1484 let mut lines = BufReader::new(stdout).lines();
1485 while let Ok(Some(line)) = lines.next_line().await {
1486 if line.trim().is_empty() {
1487 continue;
1488 }
1489 if let Some(file) = record.as_mut() {
1490 let flush = lines.get_ref().buffer().is_empty();
1493 if file.write_all(line.as_bytes()).await.is_err()
1494 || file.write_all(b"\n").await.is_err()
1495 || (flush && file.flush().await.is_err())
1496 {
1497 tracing::warn!("recording failed; continuing without it");
1498 record = None;
1499 }
1500 }
1501 match parse_frame(&line) {
1502 InboundMessage::ControlResponse(r) => {
1503 if let Some((_, tx)) = cleanup.pending.remove(&r.response.request_id) {
1504 let _ = tx.send(r.response);
1505 }
1506 }
1507 InboundMessage::ControlRequest(req) => {
1508 let request_id = req.request_id.clone();
1514 let handler = responder.clone();
1515 let task = tokio::spawn(async move { handler.respond(req).await });
1516 responder.in_flight.insert(request_id.clone(), task.abort_handle());
1517 let responder = responder.clone();
1518 tokio::spawn(async move {
1519 let outcome = task.await;
1520 responder.in_flight.remove(&request_id);
1521 let response = match outcome {
1522 Ok(response) => response,
1523 Err(e) if e.is_cancelled() => return,
1525 Err(e) => ControlResponse::error(&request_id, format!("handler failed: {e}")),
1526 };
1527 responder.write(&response).await;
1528 });
1529 }
1530 InboundMessage::ControlCancelRequest(cancel) => {
1531 if let Some((_, task)) = responder.in_flight.remove(&cancel.request_id) {
1532 task.abort();
1533 }
1534 }
1535 other => {
1536 if let InboundMessage::Result(ref r) = other
1537 && r.origin.is_none()
1538 {
1539 decrement(&turns_in_flight);
1540 }
1541 if let InboundMessage::System(ref s) = other {
1542 let mut id = session_id.write().unwrap_or_else(std::sync::PoisonError::into_inner);
1543 if id.as_deref() != Some(s.session_id.as_str()) {
1544 *id = Some(s.session_id.clone());
1545 }
1546 }
1547 let msg = Arc::new(other);
1548 lock(&fanout).subs.retain(|tx| tx.send(msg.clone()).is_ok());
1549 }
1550 }
1551 }
1552 if let Some(mut file) = record
1553 && file.flush().await.is_err()
1554 {
1555 tracing::warn!("recording failed to flush");
1556 }
1557}
1558
1559struct ReaderCleanup {
1561 fanout: Arc<std::sync::Mutex<Fanout>>,
1562 pending: Arc<Pending>,
1563 turns_in_flight: Arc<AtomicUsize>,
1564 responder: Arc<Responder>,
1565 done: watch::Sender<bool>,
1566}
1567
1568impl Drop for ReaderCleanup {
1569 fn drop(&mut self) {
1570 {
1571 let mut f = lock(&self.fanout);
1572 f.ended = true;
1573 f.subs.clear();
1574 }
1575 self.pending.clear();
1576 self.turns_in_flight.store(0, Ordering::Release);
1577 self.responder.in_flight.retain(|_, task| {
1580 task.abort();
1581 false
1582 });
1583 let _ = self.done.send(true);
1584 }
1585}
1586
1587fn parse_frame(line: &str) -> InboundMessage {
1591 match serde_json::from_str(line) {
1592 Ok(InboundMessage::Unknown) => match serde_json::from_str(line) {
1594 Ok(value) => InboundMessage::Other(value),
1595 Err(_) => InboundMessage::Unknown,
1596 },
1597 Ok(m) => m,
1598 Err(e) => {
1599 let value: Option<serde_json::Value> = serde_json::from_str(line).ok();
1600 let field = |k: &str| value.as_ref().and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(str::to_owned);
1601 if field("type").as_deref() == Some("result") {
1602 tracing::warn!(error = %e, "undecodable result frame; ending the turn with it");
1603 InboundMessage::Result(ResultMessage {
1604 subtype: field("subtype").unwrap_or_else(|| "error_unparsed_result".into()),
1605 is_error: value.as_ref().and_then(|v| v.get("is_error")).and_then(serde_json::Value::as_bool).unwrap_or(false),
1606 result: field("result"),
1607 session_id: field("session_id"),
1608 origin: value.as_ref().and_then(|v| v.get("origin")).cloned(),
1609 ..ResultMessage::default()
1610 })
1611 } else if let (Some("control_request"), Some(request_id)) = (field("type").as_deref(), value.as_ref().and_then(|v| v.get("request_id")).and_then(|v| v.as_str())) {
1612 tracing::warn!(error = %e, "undecodable control_request; answering with an error");
1614 InboundMessage::ControlRequest(ControlRequest {
1615 request_id: request_id.to_owned(),
1616 request: ControlRequestBody::Unsupported,
1617 })
1618 } else if let Some(value) = value {
1619 tracing::warn!(error = %e, "undecodable frame; passing it on as Other");
1622 InboundMessage::Other(value)
1623 } else {
1624 tracing::debug!(error = %e, line = %line, "non-JSON stdout line");
1625 InboundMessage::Unknown
1626 }
1627 }
1628 }
1629}
1630
1631impl Responder {
1632 async fn respond(&self, req: ControlRequest) -> ControlResponse {
1633 match req.request {
1634 ControlRequestBody::HookCallback(hcb) => {
1635 let span = tracing::info_span!(
1636 "claude.hook",
1637 callback_id = %hcb.callback_id,
1638 event = ?hcb.input.hook_event_name,
1639 tool = hcb.input.tool_name.as_deref().unwrap_or(""),
1640 blocked = tracing::field::Empty,
1641 );
1642 let output = self.hooks.dispatch(&hcb.callback_id, hcb.input).instrument(span.clone()).await;
1643 if let Some(ref o) = output {
1644 span.record("blocked", o.is_block());
1645 }
1646 match output {
1647 Some(output) => match serde_json::to_value(output) {
1648 Ok(v) => ControlResponse::success(&req.request_id, v),
1649 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1650 },
1651 None => ControlResponse::error(
1652 &req.request_id,
1653 format!("no hook callback registered for id {}", hcb.callback_id),
1654 ),
1655 }
1656 }
1657 ControlRequestBody::CanUseTool(cut) => match &self.can_use_tool {
1658 Some(handler) => {
1659 let original = cut.input.clone();
1660 let decision = match (handler.0)(cut).await {
1661 ToolDecision::Allow { updated_input, updated_permissions } => ToolDecision::Allow {
1663 updated_input: Some(updated_input.unwrap_or(original)),
1664 updated_permissions,
1665 },
1666 deny @ ToolDecision::Deny { .. } => deny,
1667 };
1668 match serde_json::to_value(decision) {
1669 Ok(v) => ControlResponse::success(&req.request_id, v),
1670 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1671 }
1672 }
1673 None => ControlResponse::error(&req.request_id, "no can_use_tool handler"),
1674 },
1675 ControlRequestBody::McpMessage(m) => {
1676 let span = tracing::info_span!(
1677 "claude.tool",
1678 server = %m.server_name,
1679 method = m.message.get("method").and_then(|v| v.as_str()).unwrap_or(""),
1680 tool = m.message.pointer("/params/name").and_then(|v| v.as_str()).unwrap_or(""),
1681 );
1682 let server = self.mcp_servers.iter().find(|s| s.name == m.server_name).cloned().or_else(|| {
1683 let dynamic = self.dynamic_mcp_servers.read().unwrap_or_else(std::sync::PoisonError::into_inner);
1684 dynamic.iter().find(|s| s.name == m.server_name).cloned()
1685 });
1686 let reply = match server {
1687 Some(server) => server.handle(&m.message).instrument(span).await,
1688 None => serde_json::json!({
1689 "jsonrpc": "2.0",
1690 "id": m.message.get("id"),
1691 "error": { "code": -32601, "message": format!("Server '{}' not found", m.server_name) },
1692 }),
1693 };
1694 ControlResponse::success(&req.request_id, serde_json::json!({ "mcp_response": reply }))
1695 }
1696 ControlRequestBody::Elicitation(e) => match &self.on_elicitation {
1697 Some(handler) => match serde_json::to_value((handler.0)(e).await) {
1698 Ok(v) => ControlResponse::success(&req.request_id, v),
1699 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1700 },
1701 None => ControlResponse::error(&req.request_id, "no on_elicitation handler"),
1702 },
1703 ControlRequestBody::RequestUserDialog(d) => match &self.on_user_dialog {
1704 Some(handler) => match serde_json::to_value((handler.0)(d).await) {
1705 Ok(v) => ControlResponse::success(&req.request_id, v),
1706 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1707 },
1708 None => ControlResponse::error(&req.request_id, "no on_user_dialog handler"),
1709 },
1710 ControlRequestBody::Unsupported => {
1711 ControlResponse::error(&req.request_id, "unsupported control request subtype")
1712 }
1713 }
1714 }
1715
1716 async fn write(&self, response: &ControlResponse) {
1717 match serde_json::to_vec(response) {
1718 Ok(bytes) => if let Some(tx) = self.stdin_tx.upgrade() {
1719 let _ = tx.send(bytes).await;
1720 } else { tracing::debug!("session closed; dropping control response") },
1721 Err(e) => tracing::warn!(error = %e, "failed to serialize control response"),
1722 }
1723 }
1724}