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::{AtomicBool, AtomicU64, AtomicU8, 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, CallRegistration, 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 STDOUT_LINGER: Duration = Duration::from_millis(100);
104#[cfg(unix)]
106const GROUP_GRACE: Duration = Duration::from_secs(2);
107const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(60);
108pub const DEFAULT_CONTROL_TIMEOUT: Duration = Duration::from_secs(60);
110pub const MIN_CLI_VERSION: &str = "2.1.329";
112const CLOSE_GRACE: Duration = Duration::from_secs(5);
114
115type PermFuture = Pin<Box<dyn Future<Output = ToolDecision> + Send + 'static>>;
118
119#[derive(Clone)]
122pub struct CanUseTool(Arc<dyn Fn(CanUseToolRequest) -> PermFuture + Send + Sync>);
123
124impl CanUseTool {
125 pub fn new<F, Fut>(f: F) -> Self
127 where
128 F: Fn(CanUseToolRequest) -> Fut + Send + Sync + 'static,
129 Fut: Future<Output = ToolDecision> + Send + 'static,
130 {
131 Self(Arc::new(move |req| Box::pin(f(req))))
132 }
133}
134
135type ElicitFuture = Pin<Box<dyn Future<Output = ElicitationResponse> + Send + 'static>>;
136
137#[derive(Clone)]
140pub struct OnElicitation(Arc<dyn Fn(ElicitationRequest) -> ElicitFuture + Send + Sync>);
141
142impl OnElicitation {
143 pub fn new<F, Fut>(f: F) -> Self
145 where
146 F: Fn(ElicitationRequest) -> Fut + Send + Sync + 'static,
147 Fut: Future<Output = ElicitationResponse> + Send + 'static,
148 {
149 Self(Arc::new(move |req| Box::pin(f(req))))
150 }
151}
152
153type DialogFuture = Pin<Box<dyn Future<Output = UserDialogResponse> + Send + 'static>>;
154
155#[derive(Clone)]
160pub struct OnUserDialog(Arc<dyn Fn(UserDialogRequest) -> DialogFuture + Send + Sync>);
161
162impl OnUserDialog {
163 pub fn new<F, Fut>(f: F) -> Self
165 where
166 F: Fn(UserDialogRequest) -> Fut + Send + Sync + 'static,
167 Fut: Future<Output = UserDialogResponse> + Send + 'static,
168 {
169 Self(Arc::new(move |req| Box::pin(f(req))))
170 }
171}
172
173#[derive(Clone)]
175pub struct OnStderr(Arc<dyn Fn(&str) + Send + Sync>);
176
177impl OnStderr {
178 pub fn new(f: impl Fn(&str) + Send + Sync + 'static) -> Self {
180 Self(Arc::new(f))
181 }
182}
183
184#[derive(Debug, Clone, Default)]
186pub struct McpCall {
187 pub timeout: Option<Duration>,
189 pub result_not_for_model: bool,
192 pub check_permissions: bool,
195}
196
197#[derive(Debug, Clone, Default)]
199pub struct ReloadPlugins {
200 pub add_plugins: Vec<serde_json::Value>,
202 pub hold_on_cache_impact: bool,
205 pub refuse_if_busy: bool,
207}
208
209macro_rules! opaque_debug {
210 ($($t:ident),*) => {$(
211 impl fmt::Debug for $t {
212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213 f.write_str(concat!(stringify!($t), "(..)"))
214 }
215 }
216 )*};
217}
218opaque_debug!(CanUseTool, OnElicitation, OnUserDialog, OnStderr);
219
220#[derive(Debug, Clone)]
222pub struct SessionOptions {
223 pub binary: PathBuf,
225 pub cwd: Option<PathBuf>,
227 pub model: Option<String>,
229 pub effort: Option<Effort>,
231 pub permission_mode: Option<PermissionMode>,
233 pub fallback_model: Option<String>,
236 pub thinking: Option<Thinking>,
238 pub thinking_display: Option<ThinkingDisplay>,
240 pub max_thinking_tokens: Option<u32>,
242 pub max_turns: Option<u32>,
245 pub max_budget_usd: Option<f64>,
248 pub task_budget: Option<u32>,
250 pub resume: Option<String>,
252 pub resume_session_at: Option<String>,
255 pub continue_conversation: bool,
257 pub fork_session: bool,
260 pub session_id: Option<String>,
262 pub persist_session: bool,
265 pub name: Option<String>,
267 pub code_mode: bool,
272 pub tool_search: bool,
275 pub include_partial: bool,
277 pub hooks: HookRegistry,
279 pub can_use_tool: Option<CanUseTool>,
282 pub mcp_servers: Vec<SdkMcpServer>,
285 pub allowed_tools: Vec<String>,
287 pub disallowed_tools: Vec<String>,
289 pub tools: Option<Vec<String>>,
292 pub add_dirs: Vec<PathBuf>,
294 pub strict_mcp_config: bool,
296 pub agent: Option<String>,
298 pub append_subagent_system_prompt: Option<String>,
301 pub plugin_dirs: Vec<PathBuf>,
303 pub betas: Vec<String>,
305 pub debug_file: Option<PathBuf>,
307 pub plugin_urls: Vec<String>,
309 pub files: Vec<String>,
311 pub autocompact: Option<Autocompact>,
313 pub permission_prompts: Option<PermissionPrompts>,
315 pub worktree: Option<Option<String>>,
318 pub bare: bool,
320 pub safe_mode: bool,
323 pub restricted: bool,
326 pub disable_slash_commands: bool,
328 pub brief: bool,
330 pub include_hook_events: bool,
333 pub extra_args: Vec<String>,
336 pub control_timeout: Duration,
338 pub on_elicitation: Option<OnElicitation>,
340 pub on_user_dialog: Option<OnUserDialog>,
342 pub on_stderr: Option<OnStderr>,
345 pub setting_sources: Option<Vec<String>>,
351 pub settings: Option<serde_json::Value>,
355 pub record: Option<PathBuf>,
357 pub clear_env: bool,
361 pub env: Vec<(String, String)>,
363}
364
365impl Default for SessionOptions {
366 fn default() -> Self {
367 Self {
368 binary: PathBuf::from("claude"),
369 cwd: None,
370 model: None,
371 effort: None,
372 permission_mode: None,
373 fallback_model: None,
374 thinking: None,
375 thinking_display: None,
376 max_thinking_tokens: None,
377 max_turns: None,
378 max_budget_usd: None,
379 task_budget: None,
380 resume: None,
381 resume_session_at: None,
382 continue_conversation: false,
383 fork_session: false,
384 session_id: None,
385 persist_session: true,
386 name: None,
387 code_mode: false,
388 tool_search: false,
389 include_partial: false,
390 hooks: HookRegistry::new(),
391 can_use_tool: None,
392 mcp_servers: vec![],
393 allowed_tools: vec![],
394 disallowed_tools: vec![],
395 tools: None,
396 add_dirs: vec![],
397 strict_mcp_config: false,
398 agent: None,
399 append_subagent_system_prompt: None,
400 plugin_dirs: vec![],
401 betas: vec![],
402 debug_file: None,
403 plugin_urls: vec![],
404 files: vec![],
405 autocompact: None,
406 permission_prompts: None,
407 worktree: None,
408 bare: false,
409 safe_mode: false,
410 restricted: false,
411 disable_slash_commands: false,
412 brief: false,
413 include_hook_events: false,
414 extra_args: vec![],
415 control_timeout: DEFAULT_CONTROL_TIMEOUT,
416 on_elicitation: None,
417 on_user_dialog: None,
418 on_stderr: None,
419 setting_sources: None,
420 settings: None,
421 record: None,
422 clear_env: false,
423 env: vec![],
424 }
425 }
426}
427
428pub type EventRx = mpsc::UnboundedReceiver<Arc<InboundMessage>>;
433
434#[derive(Default)]
437struct Fanout {
438 subs: Vec<mpsc::UnboundedSender<Arc<InboundMessage>>>,
439 ended: bool,
440}
441
442fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
443 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
444}
445
446type Pending = DashMap<String, oneshot::Sender<InboundControlResponseBody>>;
447
448#[derive(Debug, Clone)]
450pub(crate) struct ExitInfo {
451 pub(crate) code: Option<i32>,
452 pub(crate) stderr: String,
453}
454
455pub(crate) struct Transport {
457 pub(crate) stdin: Box<dyn AsyncWrite + Unpin + Send>,
458 pub(crate) stdout: Box<dyn AsyncRead + Unpin + Send>,
459 pub(crate) exit: Pin<Box<dyn Future<Output = Option<i32>> + Send>>,
461 pub(crate) stderr_tail: Pin<Box<dyn Future<Output = String> + Send>>,
463 pub(crate) pgid: Option<i32>,
466 #[cfg(windows)]
468 pub(crate) job: Option<win32job::Job>,
469}
470
471#[derive(Clone)]
477pub struct Session(Arc<SessionInner>);
478
479#[derive(Clone)]
481pub struct WeakSession(std::sync::Weak<SessionInner>);
482
483impl WeakSession {
484 pub fn upgrade(&self) -> Option<Session> {
486 self.0.upgrade().map(Session)
487 }
488}
489
490impl fmt::Debug for WeakSession {
491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492 f.write_str("WeakSession(..)")
493 }
494}
495
496struct SessionInner {
497 session_id: Arc<RwLock<Option<String>>>,
500 stdin_tx: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
503 fanout: Arc<std::sync::Mutex<Fanout>>,
504 pending: Arc<Pending>,
506 next_request_id: AtomicU64,
507 state: Arc<AtomicU8>,
508 exit: watch::Receiver<Option<ExitInfo>>,
509 pgid: Option<i32>,
510 include_partial: bool,
511 initialize_response: OnceLock<serde_json::Value>,
512 cli_version: OnceLock<String>,
513 control_timeout: Duration,
514 responder: Arc<Responder>,
515 prompts: Arc<PromptsInFlight>,
517 reader_done: watch::Receiver<bool>,
519 closed: AtomicBool,
521 group_ended: AtomicBool,
523 #[cfg(windows)]
525 job: std::sync::Mutex<Option<win32job::Job>>,
526 _tasks: [JoinHandle<()>; 3],
527}
528
529struct Responder {
531 stdin_tx: mpsc::WeakSender<Vec<u8>>,
534 hooks: HookRegistry,
535 can_use_tool: Option<CanUseTool>,
536 on_elicitation: Option<OnElicitation>,
537 on_user_dialog: Option<OnUserDialog>,
538 mcp_servers: Vec<SdkMcpServer>,
540 dynamic_mcp_servers: RwLock<Vec<SdkMcpServer>>,
542 in_flight: DashMap<String, tokio::task::AbortHandle>,
545 session_id: Arc<RwLock<Option<String>>>,
547}
548
549impl Session {
550 pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self> {
557 let binary = if opts.code_mode {
558 check_binary_version(&opts.binary).await?;
560 crate::code_mode::patched_binary(&opts.binary).await?
561 } else {
562 opts.binary.clone()
563 };
564 let mut cmd = Command::new(&binary);
565 if opts.clear_env {
567 cmd.env_clear();
568 }
569 cmd.args([
570 "--output-format", "stream-json",
571 "--verbose",
572 "--input-format", "stream-json",
573 "--await-initialize",
574 "--replay-user-messages",
577 ]);
578 if opts.include_partial {
579 cmd.arg("--include-partial-messages");
580 }
581 if let Some(ref m) = opts.model {
582 cmd.args(["--model", m]);
583 }
584 cmd.args(cli_args(&opts));
585 let allowed: Vec<String> = opts.allowed_tools.iter().cloned()
586 .chain(opts.mcp_servers.iter().flat_map(SdkMcpServer::qualified_tool_names))
587 .collect();
588 if !allowed.is_empty() {
589 cmd.args(["--allowedTools", &allowed.join(",")]);
590 }
591 if !opts.disallowed_tools.is_empty() {
592 cmd.args(["--disallowedTools", &opts.disallowed_tools.join(",")]);
593 }
594 let settings = match (&opts.settings, opts.code_mode) {
595 (Some(serde_json::Value::String(path)), true) => {
597 Some(read_settings_file(path, opts.cwd.as_deref()).await?)
598 }
599 (settings, _) => settings.clone(),
600 };
601 match settings_arg(settings, opts.code_mode)? {
602 Some(serde_json::Value::String(path)) => {
604 cmd.args(["--settings", &path]);
605 }
606 Some(settings) => {
607 cmd.args(["--settings", &settings.to_string()]);
608 }
609 None => {}
610 }
611 cmd.args(&opts.extra_args);
612 if let Some(ref cwd) = opts.cwd {
613 cmd.current_dir(cwd);
614 }
615 cmd.env("CLAUDE_CODE_ENTRYPOINT", "sdk-cli");
619 if opts.code_mode {
620 cmd.env("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE", "1");
621 }
622 if opts.tool_search {
623 cmd.env("ENABLE_TOOL_SEARCH", "1");
624 }
625 for (k, v) in &opts.env {
626 cmd.env(k, v);
627 }
628 cmd.stdin(Stdio::piped())
629 .stdout(Stdio::piped())
630 .stderr(Stdio::piped())
631 .kill_on_drop(false); #[cfg(unix)]
635 cmd.process_group(0);
636
637 let record = open_record(&opts).await?;
639 let mut child = cmd.spawn()?;
640 let pgid = child.id().and_then(|id| i32::try_from(id).ok());
641 #[cfg(windows)]
642 let job = child.raw_handle().and_then(job_for);
643 let (Some(stdin), Some(stdout), Some(stderr)) =
644 (child.stdin.take(), child.stdout.take(), child.stderr.take())
645 else {
646 return Err(SessionError::Io(std::io::Error::other("subprocess pipes missing")));
647 };
648 let tail = Arc::new(std::sync::Mutex::new(VecDeque::with_capacity(STDERR_TAIL_LINES)));
649 let mut drain = tokio::spawn(drain_stderr(stderr, opts.on_stderr.clone(), tail.clone()));
650 let exit = Box::pin(async move { child.wait().await.ok().and_then(|s| s.code()) });
653 let stderr_tail = Box::pin(async move {
654 if tokio::time::timeout(STDERR_LINGER, &mut drain).await.is_err() {
655 drain.abort();
656 }
657 Vec::from(std::mem::take(&mut *lock(&tail))).join("\n")
658 });
659 let transport = Transport {
660 stdin: Box::new(stdin),
661 stdout: Box::new(stdout),
662 exit,
663 stderr_tail,
664 pgid,
665 #[cfg(windows)]
666 job,
667 };
668 Self::connect(transport, opts, init, record).await
669 }
670
671 pub(crate) async fn connect(
674 transport: Transport,
675 opts: SessionOptions,
676 mut init: Initialize,
677 record: Option<tokio::fs::File>,
678 ) -> Result<Self> {
679 let Transport {
680 stdin,
681 stdout,
682 exit: exit_fut,
683 stderr_tail,
684 pgid,
685 #[cfg(windows)]
686 job,
687 } = transport;
688 let (stdin_tx, mut stdin_rx) = mpsc::channel::<Vec<u8>>(256);
689 let fanout = Arc::new(std::sync::Mutex::new(Fanout::default()));
690 let session_id = Arc::new(RwLock::new(None));
691 let pending: Arc<Pending> = Arc::new(DashMap::new());
692 let state = Arc::new(AtomicU8::new(STATE_RUNNING));
693 let (exit_tx, exit_rx) = watch::channel(None);
694 let (reader_done_tx, reader_done) = watch::channel(false);
695 let prompts = Arc::new(PromptsInFlight::default());
696
697 let writer = tokio::spawn(async move {
698 let mut w = BufWriter::new(stdin);
699 while let Some(bytes) = stdin_rx.recv().await {
700 if w.write_all(&bytes).await.is_err()
701 || w.write_all(b"\n").await.is_err()
702 || w.flush().await.is_err()
703 {
704 break;
705 }
706 }
707 let _ = w.shutdown().await;
708 });
709
710 let state2 = state.clone();
711 let watchdog = tokio::spawn(async move {
712 let code = exit_fut.await;
713 state2.store(STATE_DEAD, Ordering::SeqCst);
714 let stderr = stderr_tail.await;
715 let _ = exit_tx.send(Some(ExitInfo { code, stderr }));
716 });
717
718 let responder = Arc::new(Responder {
719 stdin_tx: stdin_tx.downgrade(),
720 hooks: opts.hooks.clone(),
721 can_use_tool: opts.can_use_tool.clone(),
722 on_elicitation: opts.on_elicitation.clone(),
723 on_user_dialog: opts.on_user_dialog.clone(),
724 mcp_servers: opts.mcp_servers.iter().map(SdkMcpServer::for_session).collect(),
725 dynamic_mcp_servers: RwLock::new(vec![]),
726 in_flight: DashMap::new(),
727 session_id: session_id.clone(),
728 });
729 let reader = tokio::spawn(read_loop(stdout, Reader {
730 record,
731 exit: exit_rx.clone(),
732 fanout: fanout.clone(),
733 session_id: session_id.clone(),
734 pending: pending.clone(),
735 prompts: prompts.clone(),
736 responder: responder.clone(),
737 done: reader_done_tx,
738 }));
739
740 let session = Session(Arc::new(SessionInner {
741 session_id,
742 stdin_tx: Mutex::new(Some(stdin_tx)),
743 fanout,
744 pending,
745 next_request_id: AtomicU64::new(0),
746 state,
747 exit: exit_rx,
748 pgid,
749 include_partial: opts.include_partial,
750 initialize_response: OnceLock::new(),
751 cli_version: OnceLock::new(),
752 control_timeout: opts.control_timeout,
753 responder,
754 prompts,
755 reader_done,
756 closed: AtomicBool::new(false),
757 group_ended: AtomicBool::new(false),
758 #[cfg(windows)]
759 job: std::sync::Mutex::new(job),
760 _tasks: [reader, writer, watchdog],
761 }));
762
763 init.hooks = opts.hooks.initialize_config();
764 let body = serde_json::to_value(&init)?;
765 let body = with_subtype(body, "initialize");
766 let response = session.request_with_timeout(&body, INITIALIZE_TIMEOUT).await?;
767 let _ = session.0.initialize_response.set(response);
768 session.check_cli_version().await?;
769 Ok(session)
770 }
771
772 async fn check_cli_version(&self) -> Result<()> {
775 let reply = self.control(&serde_json::json!({ "subtype": "get_binary_version" })).await;
776 let version = match reply {
777 Ok(v) => v.get("version").and_then(|v| v.as_str()).map(str::to_owned),
778 Err(e) => {
779 tracing::warn!(error = %e, "could not read the Claude Code version");
780 None
781 }
782 };
783 let Some(version) = version else { return Ok(()) };
784 if version_lt(&version, MIN_CLI_VERSION) {
785 self.close().await;
786 return Err(SessionError::UnsupportedCliVersion { found: version, min: MIN_CLI_VERSION });
787 }
788 let _ = self.0.cli_version.set(version);
789 Ok(())
790 }
791
792 pub async fn reconnect(previous_id: &str, mut opts: SessionOptions, init: Initialize) -> Result<Self> {
794 opts.resume = Some(previous_id.to_string());
795 Self::spawn(opts, init).await
796 }
797
798 pub async fn send<T: serde::Serialize>(&self, msg: &T) -> Result<()> {
800 if self.0.state.load(Ordering::Acquire) != STATE_RUNNING {
801 return Err(self.dead_error().await);
802 }
803 let bytes = serde_json::to_vec(msg)?;
804 let tx = self.0.stdin_tx.lock().await.clone().ok_or(SessionError::Closed)?;
805 tx.send(bytes).await.map_err(|_| SessionError::Closed)
806 }
807
808 pub async fn control<B: serde::Serialize>(&self, body: &B) -> Result<serde_json::Value> {
811 self.request_with_timeout(body, self.0.control_timeout).await
812 }
813
814 pub async fn interrupt(&self) -> Result<()> {
818 self.control(&serde_json::json!({ "subtype": "interrupt" })).await.map(|_| ())
819 }
820
821 pub async fn interrupt_all(&self) -> Result<()> {
824 let session = self.clone();
827 detached(async move {
828 let reply = session.control(&serde_json::json!({ "subtype": "interrupt", "cancel_queued": true })).await?;
829 let cancelled = reply.get("cancelled").and_then(|c| c.as_array()).into_iter().flatten();
831 for uuid in cancelled.filter_map(serde_json::Value::as_str) {
832 session.0.prompts.remove(uuid);
833 }
834 Ok(())
835 })
836 .await
837 }
838
839 pub async fn set_model(&self, model: Option<&str>) -> Result<()> {
843 self.control(&serde_json::json!({ "subtype": "set_model", "model": model })).await.map(|_| ())
844 }
845
846 pub async fn set_model_and_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
851 self.control(&serde_json::json!({
852 "subtype": "set_model", "model": model, "system_prompt": system_prompt,
853 }))
854 .await
855 .map(|_| ())
856 }
857
858 pub async fn set_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
866 self.control(&serde_json::json!({
867 "subtype": "set_model", "model": model, "system_prompt": system_prompt,
868 "only_if_model_is_current": true,
869 }))
870 .await
871 .map(|_| ())
872 }
873
874 pub async fn set_max_thinking_tokens(&self, tokens: Option<u32>, display: Option<ThinkingDisplay>) -> Result<()> {
878 let mut body = serde_json::json!({ "subtype": "set_max_thinking_tokens", "max_thinking_tokens": tokens });
879 if let Some(d) = display {
880 body["thinking_display"] = d.as_str().into();
881 }
882 self.control(&body).await.map(|_| ())
883 }
884
885 pub async fn set_effort(&self, effort: Option<Effort>) -> Result<()> {
890 let settings = serde_json::json!({ "effortLevel": effort });
891 self.control(&serde_json::json!({ "subtype": "apply_flag_settings", "settings": settings }))
892 .await
893 .map(|_| ())
894 }
895
896 pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()> {
898 self.control(&serde_json::json!({ "subtype": "set_permission_mode", "mode": mode })).await.map(|_| ())
899 }
900
901 pub async fn stop_task(&self, task_id: &str) -> Result<()> {
904 self.control(&serde_json::json!({ "subtype": "stop_task", "task_id": task_id })).await.map(|_| ())
905 }
906
907 pub async fn context_usage(&self, exact: bool) -> Result<serde_json::Value> {
912 let detail = if exact { "full" } else { "summary" };
913 self.control(&serde_json::json!({ "subtype": "get_context_usage", "detail": detail })).await
914 }
915
916 pub async fn cancel_prompt(&self, uuid: &str) -> Result<()> {
921 let session = self.clone();
923 let message_uuid = uuid.to_owned();
924 let dropped = detached(async move {
925 let reply = session
926 .control(&serde_json::json!({ "subtype": "cancel_async_message", "message_uuid": &message_uuid }))
927 .await?;
928 let dropped = reply.get("cancelled").and_then(serde_json::Value::as_bool) == Some(true);
929 if dropped {
930 session.0.prompts.remove(&message_uuid);
932 }
933 Ok(dropped)
934 })
935 .await?;
936 if dropped {
937 return Ok(());
938 }
939 self.control(&serde_json::json!({ "subtype": "interrupt", "for_user_message_uuids": [uuid] }))
940 .await
941 .map(|_| ())
942 }
943
944 pub async fn rename_session(&self, title: &str) -> Result<()> {
946 self.control(&serde_json::json!({ "subtype": "rename_session", "title": title })).await.map(|_| ())
947 }
948
949 pub async fn rewind_files(&self, user_message_id: &str, dry_run: bool) -> Result<serde_json::Value> {
953 self.control(&serde_json::json!({
954 "subtype": "rewind_files", "user_message_id": user_message_id, "dry_run": dry_run,
955 }))
956 .await
957 }
958
959 pub async fn mcp_status(&self) -> Result<serde_json::Value> {
961 self.control(&serde_json::json!({ "subtype": "mcp_status" })).await
962 }
963
964 pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()> {
966 self.control(&serde_json::json!({ "subtype": "mcp_toggle", "serverName": server, "enabled": enabled }))
967 .await
968 .map(|_| ())
969 }
970
971 pub async fn mcp_reconnect(&self, server: &str) -> Result<()> {
973 self.control(&serde_json::json!({ "subtype": "mcp_reconnect", "serverName": server })).await.map(|_| ())
974 }
975
976 pub async fn set_mcp_servers(
982 &self,
983 sdk: Vec<SdkMcpServer>,
984 external: serde_json::Map<String, serde_json::Value>,
985 ) -> Result<serde_json::Value> {
986 let servers = server_map(&sdk, Some(&external));
987 let dynamic = &self.0.responder.dynamic_mcp_servers;
988 let write = || dynamic.write().unwrap_or_else(std::sync::PoisonError::into_inner);
989 let (previous, next) = {
990 let mut current = write();
991 let next: Vec<SdkMcpServer> = sdk
993 .iter()
994 .map(|s| match current.iter().find(|c| c.name == s.name) {
995 Some(running) => s.taking_over(running),
996 None => s.for_session(),
997 })
998 .collect();
999 let mut both = next.clone();
1002 both.extend(current.iter().filter(|c| !next.iter().any(|n| n.name == c.name)).cloned());
1003 (std::mem::replace(&mut *current, both), next)
1004 };
1005 let reply = self.control(&serde_json::json!({ "subtype": "mcp_set_servers", "servers": servers })).await;
1006 match &reply {
1007 Ok(_) => *write() = next,
1008 Err(SessionError::ControlError { .. }) => *write() = previous,
1009 Err(_) => {}
1011 }
1012 reply
1013 }
1014
1015 pub async fn list_models(&self) -> Result<serde_json::Value> {
1017 self.control(&serde_json::json!({ "subtype": "list_models" })).await
1018 }
1019
1020 pub async fn get_settings(&self) -> Result<serde_json::Value> {
1023 self.control(&serde_json::json!({ "subtype": "get_settings" })).await
1024 }
1025
1026 pub async fn update_settings(&self, local: bool, settings: serde_json::Value) -> Result<serde_json::Value> {
1030 let source = if local { "localSettings" } else { "userSettings" };
1031 self.control(&serde_json::json!({ "subtype": "update_settings", "source": source, "settings": settings }))
1032 .await
1033 }
1034
1035 pub async fn get_usage(&self, skip_behaviors: bool) -> Result<serde_json::Value> {
1040 self.control(&serde_json::json!({ "subtype": "get_usage", "skip_behaviors": skip_behaviors })).await
1041 }
1042
1043 pub async fn reload_skills(&self) -> Result<serde_json::Value> {
1045 self.control(&serde_json::json!({ "subtype": "reload_skills" })).await
1046 }
1047
1048 pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<serde_json::Value> {
1050 let mut body = serde_json::json!({
1051 "subtype": "reload_plugins",
1052 "hold_on_cache_impact": opts.hold_on_cache_impact,
1053 "refuse_if_busy": opts.refuse_if_busy,
1054 });
1055 if !opts.add_plugins.is_empty() {
1056 body["add_plugins"] = serde_json::json!(opts.add_plugins);
1057 }
1058 self.control(&body).await
1059 }
1060
1061 pub async fn task_output(&self, task_id: &str) -> Result<serde_json::Value> {
1064 self.control(&serde_json::json!({ "subtype": "get_task_output", "task_id": task_id })).await
1065 }
1066
1067 pub async fn register_repo_root(&self, directory: &str) -> Result<serde_json::Value> {
1071 self.control(&serde_json::json!({
1072 "subtype": "register_repo_root", "directory": directory,
1073 "reload_claude_md": true, "reload_plugins": true, "reload_skills": true,
1074 }))
1075 .await
1076 }
1077
1078 pub async fn mcp_call(&self, tool: &str, arguments: serde_json::Value, opts: McpCall) -> Result<serde_json::Value> {
1083 let mut body = serde_json::json!({ "subtype": "mcp_call", "tool": tool, "arguments": arguments });
1084 if let Some(t) = opts.timeout {
1085 body["timeout_ms"] = serde_json::json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
1086 }
1087 if opts.result_not_for_model {
1088 body["result_not_for_model"] = true.into();
1089 }
1090 if opts.check_permissions {
1091 body["check_permissions"] = true.into();
1092 }
1093 self.control(&body).await
1094 }
1095
1096 pub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<serde_json::Value> {
1099 self.control(&serde_json::json!({ "subtype": "mcp_read_resource", "serverName": server, "uri": uri }))
1100 .await
1101 }
1102
1103 pub async fn read_file(&self, path: &str, max_bytes: Option<u64>, base64: bool) -> Result<serde_json::Value> {
1107 let mut body = serde_json::json!({
1108 "subtype": "read_file", "path": path,
1109 "encoding": if base64 { "base64" } else { "utf-8" },
1110 });
1111 if let Some(n) = max_bytes {
1112 body["max_bytes"] = n.into();
1113 }
1114 self.control(&body).await
1115 }
1116
1117 pub async fn file_suggestions(&self, query: &str) -> Result<serde_json::Value> {
1120 self.control(&serde_json::json!({ "subtype": "file_suggestions", "query": query })).await
1121 }
1122
1123 pub async fn hooks_listing(&self) -> Result<serde_json::Value> {
1126 self.control(&serde_json::json!({ "subtype": "get_hooks_listing" })).await
1127 }
1128
1129 pub async fn permission_rules(&self) -> Result<serde_json::Value> {
1132 self.control(&serde_json::json!({ "subtype": "list_permission_rules" })).await
1133 }
1134
1135 pub async fn session_cost(&self) -> Result<serde_json::Value> {
1138 self.control(&serde_json::json!({ "subtype": "get_session_cost" })).await
1139 }
1140
1141 pub async fn reload_output_styles(&self) -> Result<serde_json::Value> {
1143 self.control(&serde_json::json!({ "subtype": "reload_output_styles" })).await
1144 }
1145
1146 pub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()> {
1149 self.control(&serde_json::json!({ "subtype": "seed_read_state", "path": path, "mtime": mtime_ms }))
1150 .await
1151 .map(|_| ())
1152 }
1153
1154 #[must_use]
1156 pub fn downgrade(&self) -> WeakSession {
1157 WeakSession(Arc::downgrade(&self.0))
1158 }
1159
1160 #[must_use]
1162 pub fn pid(&self) -> Option<u32> {
1163 self.0.pgid.and_then(|p| u32::try_from(p).ok())
1164 }
1165
1166 pub fn cli_version(&self) -> Option<&str> {
1168 self.0.cli_version.get().map(String::as_str)
1169 }
1170
1171 #[must_use = "frames buffer until the receiver is dropped"]
1175 pub fn subscribe(&self) -> EventRx {
1176 let (tx, rx) = mpsc::unbounded_channel();
1177 let mut fanout = lock(&self.0.fanout);
1178 if !fanout.ended {
1179 fanout.subs.push(tx);
1180 }
1181 rx
1182 }
1183
1184 pub fn session_id(&self) -> Option<String> {
1187 self.0.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
1188 }
1189
1190 #[must_use]
1192 pub fn initialize_response(&self) -> Option<&serde_json::Value> {
1193 self.0.initialize_response.get()
1194 }
1195
1196 pub(crate) fn offers_command(&self, name: &str) -> bool {
1200 match self.initialize_response().and_then(|r| r.get("commands")).and_then(|c| c.as_array()) {
1201 Some(commands) => commands.iter().any(|c| c.get("name").and_then(|n| n.as_str()) == Some(name)),
1202 None => true,
1203 }
1204 }
1205
1206 pub(crate) fn launch_permission_mode(&self) -> Option<PermissionMode> {
1209 let mode = self.initialize_response()?.get("current_permission_mode")?.clone();
1210 serde_json::from_value(mode).ok()
1211 }
1212
1213 #[must_use]
1216 pub fn include_partial(&self) -> bool {
1217 self.0.include_partial
1218 }
1219
1220 #[must_use]
1222 pub fn is_busy(&self) -> bool {
1223 !self.0.prompts.is_empty()
1224 }
1225
1226 pub(crate) async fn send_prompt(&self, message: &crate::protocol::UserMessage) -> Result<()> {
1229 self.0.prompts.add(&message.uuid);
1230 let mut counted = UnsentPrompt(Some((&self.0.prompts, &message.uuid)));
1233 self.send(message).await?;
1234 counted.0 = None;
1235 Ok(())
1236 }
1237
1238 #[must_use]
1240 pub fn is_alive(&self) -> bool {
1241 self.0.state.load(Ordering::Acquire) == STATE_RUNNING
1242 }
1243
1244 pub async fn close(&self) -> Option<i32> {
1254 let session = self.clone();
1258 tokio::spawn(async move { session.close_here().await }).await.unwrap_or(None)
1259 }
1260
1261 async fn close_here(&self) -> Option<i32> {
1262 self.0.closed.store(true, Ordering::Release);
1263 let _ = self.0.state.compare_exchange(STATE_RUNNING, STATE_CLOSING, Ordering::SeqCst, Ordering::SeqCst);
1264 #[cfg(unix)]
1265 let pgid = self.0.pgid;
1266 #[cfg(unix)]
1270 let mut groups = if self.0.state.load(Ordering::Acquire) == STATE_DEAD {
1271 vec![]
1272 } else {
1273 blocking(move || tool_groups(pgid)).await
1274 };
1275 self.0.stdin_tx.lock().await.take();
1276 let mut exit = self.wait_exit(CLOSE_GRACE).await;
1277 #[cfg(unix)]
1278 for signal in [nix::sys::signal::Signal::SIGTERM, nix::sys::signal::Signal::SIGKILL] {
1279 if exit.is_some() {
1280 break;
1281 }
1282 for group in blocking(move || tool_groups(pgid)).await {
1283 if !groups.contains(&group) {
1284 groups.push(group);
1285 }
1286 }
1287 self.signal_group(signal);
1288 exit = self.wait_exit(CLOSE_GRACE).await;
1289 }
1290 #[cfg(unix)]
1293 {
1294 groups.extend(pgid);
1295 blocking(move || end_groups(&groups)).await;
1296 }
1297 #[cfg(windows)]
1299 {
1300 let job = lock(&self.0.job).take();
1301 if job.is_none() && exit.is_none() {
1302 let pid = self.0.pgid;
1303 blocking(move || kill_tree(pid)).await;
1304 }
1305 drop(job);
1306 if exit.is_none() {
1307 exit = self.wait_exit(CLOSE_GRACE).await;
1308 }
1309 }
1310 self.0.group_ended.store(true, Ordering::Release);
1311 let mut done = self.0.reader_done.clone();
1313 let _ = tokio::time::timeout(CLOSE_GRACE, done.wait_for(|d| *d)).await;
1314 exit.and_then(|e| e.code)
1315 }
1316
1317 async fn wait_exit(&self, timeout: Duration) -> Option<ExitInfo> {
1318 let mut rx = self.0.exit.clone();
1319 let waited = tokio::time::timeout(timeout, async {
1320 rx.wait_for(Option::is_some).await.ok().and_then(|info| info.clone())
1321 })
1322 .await;
1323 waited.ok().flatten()
1324 }
1325
1326 #[cfg(unix)]
1327 fn signal_group(&self, signal: nix::sys::signal::Signal) {
1328 if let Some(pgid) = self.0.pgid {
1329 let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), signal);
1330 }
1331 }
1332
1333 async fn request_with_timeout<B: serde::Serialize>(
1336 &self,
1337 body: &B,
1338 timeout: Duration,
1339 ) -> Result<serde_json::Value> {
1340 let n = self.0.next_request_id.fetch_add(1, Ordering::Relaxed);
1341 let request_id = format!("req_{n}_{}", std::process::id());
1342 let subtype = serde_json::to_value(body)?
1343 .get("subtype")
1344 .and_then(|s| s.as_str())
1345 .unwrap_or("?")
1346 .to_string();
1347
1348 let (tx, rx) = oneshot::channel();
1350 self.0.pending.insert(request_id.clone(), tx);
1351 let _registered = PendingGuard { pending: &self.0.pending, request_id: &request_id };
1353 if lock(&self.0.fanout).ended {
1356 return Err(self.dead_error().await);
1357 }
1358 let envelope = OutboundControlRequest { kind: "control_request", request_id: &request_id, request: body };
1359 let exchange = async {
1362 self.send(&envelope).await?;
1363 Ok::<_, SessionError>(rx.await)
1364 };
1365 let reply = match tokio::time::timeout(timeout, exchange).await {
1366 Ok(Ok(Ok(reply))) => reply,
1367 Ok(Err(e)) => return Err(e),
1368 Ok(Ok(Err(_))) => return Err(self.dead_error().await),
1370 Err(_) => return Err(SessionError::ControlTimeout(subtype)),
1371 };
1372 match reply.subtype.as_str() {
1373 "success" => Ok(reply.response.unwrap_or(serde_json::Value::Null)),
1374 _ => Err(SessionError::ControlError {
1375 subtype,
1376 error: reply.error.unwrap_or_else(|| "unknown error".into()),
1377 }),
1378 }
1379 }
1380
1381 async fn dead_error(&self) -> SessionError {
1383 if self.0.closed.load(Ordering::Acquire) {
1384 return SessionError::Closed;
1385 }
1386 match self.wait_exit(Duration::from_secs(1)).await {
1388 Some(ExitInfo { code, stderr }) => SessionError::ProcessExited { code, stderr },
1389 None => SessionError::Closed,
1390 }
1391 }
1392}
1393
1394struct PendingGuard<'a> {
1396 pending: &'a Pending,
1397 request_id: &'a str,
1398}
1399
1400impl Drop for PendingGuard<'_> {
1401 fn drop(&mut self) {
1402 self.pending.remove(self.request_id);
1403 }
1404}
1405
1406impl Drop for SessionInner {
1407 fn drop(&mut self) {
1417 #[cfg(unix)]
1418 if let Some(pgid) = self.pgid
1419 && !self.group_ended.load(Ordering::Acquire)
1420 {
1421 use nix::sys::signal::{killpg, Signal};
1422 let group = nix::unistd::Pid::from_raw(pgid);
1423 let running = self.state.load(Ordering::Acquire) != STATE_DEAD;
1424 let mut groups = if running { tool_groups(Some(pgid)) } else { vec![] };
1426 groups.push(pgid);
1427 for &g in &groups {
1428 let _ = killpg(nix::unistd::Pid::from_raw(g), Signal::SIGTERM);
1429 }
1430 let exit = self.exit.clone();
1431 let cleanup = move || {
1432 if running {
1433 let deadline = std::time::Instant::now() + CLOSE_GRACE;
1434 while exit.borrow().is_none()
1435 && killpg(group, None).is_ok()
1436 && std::time::Instant::now() < deadline
1437 {
1438 std::thread::sleep(Duration::from_millis(50));
1439 }
1440 }
1441 end_groups(&groups);
1442 };
1443 if let Err(e) = std::thread::Builder::new().name("claude-session-cleanup".into()).spawn(cleanup) {
1444 tracing::warn!(error = %e, "could not start the session cleanup thread");
1445 }
1446 }
1447 #[cfg(windows)]
1449 if lock(&self.job).is_none()
1450 && !self.group_ended.load(Ordering::Acquire)
1451 && self.state.load(Ordering::Acquire) != STATE_DEAD
1452 {
1453 let pid = self.pgid;
1454 if let Err(e) = std::thread::Builder::new().name("claude-session-cleanup".into()).spawn(move || kill_tree(pid)) {
1455 tracing::warn!(error = %e, "could not start the session cleanup thread");
1456 }
1457 }
1458 }
1459}
1460
1461struct UnsentPrompt<'a>(Option<(&'a PromptsInFlight, &'a str)>);
1463
1464impl Drop for UnsentPrompt<'_> {
1465 fn drop(&mut self) {
1466 if let Some((prompts, uuid)) = self.0 {
1467 prompts.remove(uuid);
1468 }
1469 }
1470}
1471
1472#[derive(Default)]
1474struct PromptsInFlight(std::sync::Mutex<Vec<String>>);
1475
1476impl PromptsInFlight {
1477 fn add(&self, uuid: &str) {
1478 lock(&self.0).push(uuid.to_owned());
1479 }
1480
1481 fn remove(&self, uuid: &str) {
1482 lock(&self.0).retain(|u| !u.eq_ignore_ascii_case(uuid));
1483 }
1484
1485 fn end_turn(&self, result: &ResultMessage) {
1489 let mut prompts = lock(&self.0);
1490 if !result.user_message_uuids.is_empty() {
1491 prompts.retain(|u| !result.answers(u));
1492 } else if result.origin.is_none() && !prompts.is_empty() {
1493 prompts.remove(0);
1494 }
1495 }
1496
1497 fn clear(&self) {
1498 lock(&self.0).clear();
1499 }
1500
1501 fn is_empty(&self) -> bool {
1502 lock(&self.0).is_empty()
1503 }
1504}
1505
1506async fn detached<T: Send + 'static>(work: impl Future<Output = Result<T>> + Send + 'static) -> Result<T> {
1509 tokio::spawn(work)
1510 .await
1511 .unwrap_or_else(|e| Err(SessionError::Io(std::io::Error::other(format!("control task failed: {e}")))))
1512}
1513
1514async fn blocking<T: Default + Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
1516 tokio::task::spawn_blocking(work).await.unwrap_or_default()
1517}
1518
1519#[cfg(unix)]
1522fn tool_groups(pgid: Option<i32>) -> Vec<i32> {
1523 let Some(root) = pgid else { return vec![] };
1524 let host = nix::unistd::getpgrp().as_raw();
1525 crate::process_tree::descendant_groups(&crate::process_tree::snapshot(), root, host)
1526}
1527
1528#[cfg(unix)]
1534fn end_groups(groups: &[i32]) {
1535 use nix::sys::signal::{killpg, Signal};
1536 let pid = nix::unistd::Pid::from_raw;
1537 for &group in groups {
1538 let _ = killpg(pid(group), Signal::SIGTERM);
1539 }
1540 let still_there = |groups: &[i32]| -> Vec<i32> {
1541 groups.iter().copied().filter(|&g| killpg(pid(g), None).is_ok()).collect()
1542 };
1543 let deadline = std::time::Instant::now() + GROUP_GRACE;
1544 let mut left = still_there(groups);
1545 while !left.is_empty() && std::time::Instant::now() < deadline {
1546 std::thread::sleep(Duration::from_millis(50));
1547 left = still_there(&left);
1548 }
1549 for group in left {
1550 let _ = killpg(pid(group), Signal::SIGKILL);
1551 }
1552}
1553
1554async fn check_binary_version(binary: &std::path::Path) -> Result<()> {
1557 let run = Command::new(binary).arg("--version").kill_on_drop(true).output();
1558 let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(30), run).await else {
1559 return Ok(());
1560 };
1561 let stdout = String::from_utf8_lossy(&out.stdout);
1563 let found = stdout.split_whitespace().next().unwrap_or_default().to_owned();
1564 if out.status.success() && !found.is_empty() && version_lt(&found, MIN_CLI_VERSION) {
1565 return Err(SessionError::UnsupportedCliVersion { found, min: MIN_CLI_VERSION });
1566 }
1567 Ok(())
1568}
1569
1570async fn drain_stderr(
1573 stderr: tokio::process::ChildStderr,
1574 on_stderr: Option<OnStderr>,
1575 tail: Arc<std::sync::Mutex<VecDeque<String>>>,
1576) {
1577 let mut lines = LossyLines::new(stderr);
1578 while let Ok(Some(line)) = lines.next_line().await {
1579 if let Some(cb) = &on_stderr
1580 && std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (cb.0)(&line))).is_err()
1581 {
1582 tracing::warn!("on_stderr callback panicked");
1583 }
1584 let mut tail = lock(&tail);
1585 if tail.len() == STDERR_TAIL_LINES {
1586 tail.pop_front();
1587 }
1588 tail.push_back(line);
1589 }
1590}
1591
1592#[cfg(windows)]
1595fn job_for(process: std::os::windows::io::RawHandle) -> Option<win32job::Job> {
1596 let mut limits = win32job::ExtendedLimitInfo::new();
1597 limits.limit_kill_on_job_close();
1598 let job = win32job::Job::create_with_limit_info(&limits)
1599 .inspect_err(|e| tracing::warn!(error = %e, "could not create a job for the CLI"))
1600 .ok()?;
1601 job.assign_process(process as isize)
1602 .inspect_err(|e| tracing::warn!(error = %e, "could not put the CLI in a job"))
1603 .ok()?;
1604 Some(job)
1605}
1606
1607#[cfg(not(unix))]
1610fn kill_tree(pid: Option<i32>) {
1611 if let Some(pid) = pid {
1612 let _ = std::process::Command::new("taskkill")
1613 .args(["/PID", &pid.to_string(), "/T", "/F"])
1614 .stdout(Stdio::null())
1615 .stderr(Stdio::null())
1616 .status();
1617 }
1618}
1619
1620fn cli_args(opts: &SessionOptions) -> Vec<String> {
1622 let mut args: Vec<String> = vec![];
1623 let mut flag = |name: &str, value: Option<String>| {
1624 if let Some(v) = value {
1625 args.push(name.into());
1626 args.push(v);
1627 }
1628 };
1629 flag("--model", opts.model.clone());
1630 flag("--effort", opts.effort.map(|e| e.as_str().into()));
1631 flag("--permission-mode", opts.permission_mode.map(|m| m.as_str().into()));
1632 flag("--fallback-model", opts.fallback_model.clone());
1633 flag("--thinking", opts.thinking.map(|t| t.as_str().into()));
1634 flag("--thinking-display", opts.thinking_display.map(|d| d.as_str().into()));
1635 flag("--max-thinking-tokens", opts.max_thinking_tokens.map(|n| n.to_string()));
1636 flag("--max-turns", opts.max_turns.map(|n| n.to_string()));
1637 flag("--max-budget-usd", opts.max_budget_usd.map(|n| n.to_string()));
1638 flag("--task-budget", opts.task_budget.map(|n| n.to_string()));
1639 flag("--resume", opts.resume.clone());
1640 flag("--resume-session-at", opts.resume_session_at.clone());
1641 flag("--session-id", opts.session_id.clone());
1642 flag("--name", opts.name.clone());
1643 flag("--tools", opts.tools.as_ref().map(|t| t.join(",")));
1644 flag("--agent", opts.agent.clone());
1645 flag("--append-subagent-system-prompt", opts.append_subagent_system_prompt.clone());
1646 flag("--betas", (!opts.betas.is_empty()).then(|| opts.betas.join(",")));
1647 flag("--debug-file", opts.debug_file.as_ref().map(|p| p.display().to_string()));
1648 flag("--setting-sources", opts.setting_sources.as_ref().map(|s| s.join(",")));
1649 flag("--permission-prompt-tool", opts.can_use_tool.as_ref().map(|_| "stdio".into()));
1650 flag(
1651 "--mcp-config",
1652 (!opts.mcp_servers.is_empty())
1653 .then(|| serde_json::json!({ "mcpServers": server_map(&opts.mcp_servers, None) }).to_string()),
1654 );
1655 for dir in &opts.add_dirs {
1656 flag("--add-dir", Some(dir.display().to_string()));
1657 }
1658 for dir in &opts.plugin_dirs {
1659 flag("--plugin-dir", Some(dir.display().to_string()));
1660 }
1661 for url in &opts.plugin_urls {
1662 flag("--plugin-url", Some(url.clone()));
1663 }
1664 for spec in &opts.files {
1665 flag("--file", Some(spec.clone()));
1666 }
1667 flag("--autocompact", opts.autocompact.map(super::protocol::Autocompact::to_arg));
1668 flag("--permission-prompts", opts.permission_prompts.map(|p| p.as_str().into()));
1669 if let Some(Some(name)) = &opts.worktree {
1670 flag("--worktree", Some(name.clone()));
1671 }
1672 if let Some(None) = opts.worktree {
1673 args.push("--worktree".into());
1674 }
1675 for (on, name) in [
1676 (opts.bare, "--bare"),
1677 (opts.safe_mode, "--safe-mode"),
1678 (opts.restricted, "--restricted"),
1679 (opts.disable_slash_commands, "--disable-slash-commands"),
1680 (opts.brief, "--brief"),
1681 (opts.include_hook_events, "--include-hook-events"),
1682 ] {
1683 if on {
1684 args.push(name.into());
1685 }
1686 }
1687 if opts.continue_conversation {
1688 args.push("--continue".into());
1689 }
1690 if opts.fork_session {
1691 args.push("--fork-session".into());
1692 }
1693 if !opts.persist_session {
1694 args.push("--no-session-persistence".into());
1695 }
1696 if opts.strict_mcp_config {
1697 args.push("--strict-mcp-config".into());
1698 }
1699 args
1700}
1701
1702fn version_lt(a: &str, b: &str) -> bool {
1704 let parse = |v: &str| -> Vec<u64> {
1705 v.split(['.', '-', ' '])
1706 .map_while(|part| part.parse().ok())
1707 .collect()
1708 };
1709 parse(a) < parse(b)
1710}
1711
1712pub(crate) fn cancelled_prompt(frame: &serde_json::Value) -> Option<&str> {
1715 let field = |k: &str| frame.get(k).and_then(|v| v.as_str());
1716 (field("type") == Some("command_lifecycle") && field("state") == Some("cancelled"))
1717 .then(|| field("command_uuid"))
1718 .flatten()
1719}
1720
1721pub(crate) async fn open_record(opts: &SessionOptions) -> Result<Option<tokio::fs::File>> {
1723 match &opts.record {
1724 Some(path) => Ok(Some(tokio::fs::File::create(path).await?)),
1725 None => Ok(None),
1726 }
1727}
1728
1729async fn read_settings_file(path: &str, cwd: Option<&std::path::Path>) -> Result<serde_json::Value> {
1732 let path = match cwd {
1733 Some(dir) => dir.join(path),
1734 None => PathBuf::from(path),
1735 };
1736 Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
1737}
1738
1739fn settings_arg(settings: Option<serde_json::Value>, code_mode: bool) -> Result<Option<serde_json::Value>> {
1742 if !code_mode {
1743 return Ok(settings);
1744 }
1745 let mut settings = settings.unwrap_or_else(|| serde_json::json!({}));
1746 let env = settings
1747 .as_object_mut()
1748 .map(|obj| obj.entry("env").or_insert_with(|| serde_json::json!({})))
1749 .and_then(serde_json::Value::as_object_mut)
1750 .ok_or(crate::code_mode::CodeModeError::Settings)?;
1751 env.insert("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE".into(), "1".into());
1752 Ok(Some(settings))
1753}
1754
1755fn with_subtype(mut body: serde_json::Value, subtype: &str) -> serde_json::Value {
1756 if let Some(obj) = body.as_object_mut() {
1757 obj.insert("subtype".into(), subtype.into());
1758 }
1759 body
1760}
1761
1762struct LossyLines<R> {
1766 inner: BufReader<R>,
1767 line: Vec<u8>,
1769}
1770
1771impl<R: AsyncRead + Unpin> LossyLines<R> {
1772 fn new(inner: R) -> Self {
1773 Self { inner: BufReader::new(inner), line: vec![] }
1774 }
1775
1776 async fn next_line(&mut self) -> std::io::Result<Option<String>> {
1779 let n = self.inner.read_until(b'\n', &mut self.line).await?;
1780 if n == 0 && self.line.is_empty() {
1781 return Ok(None);
1782 }
1783 let mut line = std::mem::take(&mut self.line);
1784 if line.last() == Some(&b'\n') {
1785 line.pop();
1786 if line.last() == Some(&b'\r') {
1787 line.pop();
1788 }
1789 }
1790 Ok(Some(String::from_utf8(line).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())))
1791 }
1792
1793 fn buffered_is_empty(&self) -> bool {
1795 self.inner.buffer().is_empty()
1796 }
1797}
1798
1799struct Reader {
1801 record: Option<tokio::fs::File>,
1802 exit: watch::Receiver<Option<ExitInfo>>,
1805 fanout: Arc<std::sync::Mutex<Fanout>>,
1806 session_id: Arc<RwLock<Option<String>>>,
1807 pending: Arc<Pending>,
1808 prompts: Arc<PromptsInFlight>,
1809 responder: Arc<Responder>,
1810 done: watch::Sender<bool>,
1811}
1812
1813async fn read_loop(stdout: Box<dyn AsyncRead + Unpin + Send>, reader: Reader) {
1814 let Reader { record, mut exit, fanout, session_id, pending, prompts, responder, done } = reader;
1815 let cleanup = ReaderCleanup {
1817 fanout: fanout.clone(),
1818 pending,
1819 prompts: prompts.clone(),
1820 responder: responder.clone(),
1821 done,
1822 };
1823 let mut record = record.map(BufWriter::new);
1824 let mut lines = LossyLines::new(stdout);
1825 let mut exited = false;
1826 loop {
1827 let next = if exited {
1829 match tokio::time::timeout(STDOUT_LINGER, lines.next_line()).await {
1830 Ok(next) => next,
1831 Err(_) => {
1832 tracing::debug!("CLI exited but stdout is held open; stopping the reader");
1833 break;
1834 }
1835 }
1836 } else {
1837 tokio::select! {
1838 next = lines.next_line() => next,
1839 _ = exit.wait_for(Option::is_some) => {
1840 exited = true;
1841 continue;
1842 }
1843 }
1844 };
1845 let Ok(Some(line)) = next else { break };
1846 if line.trim().is_empty() {
1847 continue;
1848 }
1849 if let Some(file) = record.as_mut() {
1850 let flush = lines.buffered_is_empty();
1853 if file.write_all(line.as_bytes()).await.is_err()
1854 || file.write_all(b"\n").await.is_err()
1855 || (flush && file.flush().await.is_err())
1856 {
1857 tracing::warn!("recording failed; continuing without it");
1858 record = None;
1859 }
1860 }
1861 match parse_frame(&line) {
1862 InboundMessage::ControlResponse(r) => {
1863 if let Some((_, tx)) = cleanup.pending.remove(&r.response.request_id) {
1864 let _ = tx.send(r.response);
1865 }
1866 }
1867 InboundMessage::ControlRequest(req) => {
1868 let request_id = req.request_id.clone();
1874 let mcp = responder.mcp_target(&req);
1878 let handler = responder.clone();
1879 let task = tokio::spawn(async move { handler.respond(req, mcp).await });
1880 responder.in_flight.insert(request_id.clone(), task.abort_handle());
1881 let responder = responder.clone();
1882 tokio::spawn(async move {
1883 let outcome = task.await;
1884 responder.in_flight.remove(&request_id);
1885 let response = match outcome {
1886 Ok(response) => response,
1887 Err(e) if e.is_cancelled() => return,
1889 Err(e) => ControlResponse::error(&request_id, format!("handler failed: {e}")),
1890 };
1891 responder.write(&response).await;
1892 });
1893 }
1894 InboundMessage::ControlCancelRequest(cancel) => {
1895 if let Some((_, task)) = responder.in_flight.remove(&cancel.request_id) {
1896 task.abort();
1897 }
1898 }
1899 other => {
1900 match &other {
1901 InboundMessage::Result(r) => prompts.end_turn(r),
1902 InboundMessage::Other(frame) => {
1903 if let Some(uuid) = cancelled_prompt(frame) {
1904 prompts.remove(uuid);
1905 }
1906 }
1907 _ => {}
1908 }
1909 if let InboundMessage::System(ref s) = other {
1910 let mut id = session_id.write().unwrap_or_else(std::sync::PoisonError::into_inner);
1911 if id.as_deref() != Some(s.session_id.as_str()) {
1912 *id = Some(s.session_id.clone());
1913 }
1914 }
1915 let msg = Arc::new(other);
1916 lock(&fanout).subs.retain(|tx| tx.send(msg.clone()).is_ok());
1917 }
1918 }
1919 }
1920 if let Some(mut file) = record
1921 && file.flush().await.is_err()
1922 {
1923 tracing::warn!("recording failed to flush");
1924 }
1925}
1926
1927struct ReaderCleanup {
1929 fanout: Arc<std::sync::Mutex<Fanout>>,
1930 pending: Arc<Pending>,
1931 prompts: Arc<PromptsInFlight>,
1932 responder: Arc<Responder>,
1933 done: watch::Sender<bool>,
1934}
1935
1936impl Drop for ReaderCleanup {
1937 fn drop(&mut self) {
1938 {
1939 let mut f = lock(&self.fanout);
1940 f.ended = true;
1941 f.subs.clear();
1942 }
1943 self.pending.clear();
1944 self.prompts.clear();
1945 self.responder.in_flight.retain(|_, task| {
1948 task.abort();
1949 false
1950 });
1951 let _ = self.done.send(true);
1952 }
1953}
1954
1955fn parse_frame(line: &str) -> InboundMessage {
1959 match serde_json::from_str(line) {
1960 Ok(InboundMessage::Unknown) => match serde_json::from_str(line) {
1962 Ok(value) => InboundMessage::Other(value),
1963 Err(_) => InboundMessage::Unknown,
1964 },
1965 Ok(m) => m,
1966 Err(e) => {
1967 let value: Option<serde_json::Value> = serde_json::from_str(line).ok();
1968 let field = |k: &str| value.as_ref().and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(str::to_owned);
1969 if field("type").as_deref() == Some("result") {
1970 tracing::warn!(error = %e, "undecodable result frame; ending the turn with it");
1971 InboundMessage::Result(ResultMessage {
1972 subtype: field("subtype").unwrap_or_else(|| "error_unparsed_result".into()),
1973 is_error: value.as_ref().and_then(|v| v.get("is_error")).and_then(serde_json::Value::as_bool).unwrap_or(false),
1974 result: field("result"),
1975 session_id: field("session_id"),
1976 origin: value.as_ref().and_then(|v| v.get("origin")).filter(|o| !o.is_null()).cloned(),
1978 user_message_uuids: value
1980 .as_ref()
1981 .and_then(|v| v.get("user_message_uuids"))
1982 .and_then(serde_json::Value::as_array)
1983 .into_iter()
1984 .flatten()
1985 .filter_map(|u| u.as_str().map(str::to_owned))
1986 .collect(),
1987 ..ResultMessage::default()
1988 })
1989 } 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())) {
1990 tracing::warn!(error = %e, "undecodable control_request; answering with an error");
1992 InboundMessage::ControlRequest(ControlRequest {
1993 request_id: request_id.to_owned(),
1994 request: ControlRequestBody::Unsupported,
1995 })
1996 } else if let Some(value) = value {
1997 tracing::warn!(error = %e, "undecodable frame; passing it on as Other");
2000 InboundMessage::Other(value)
2001 } else {
2002 tracing::debug!(error = %e, line = %line, "non-JSON stdout line");
2003 InboundMessage::Unknown
2004 }
2005 }
2006 }
2007}
2008
2009type McpTarget = (SdkMcpServer, Option<CallRegistration>);
2012
2013impl Responder {
2014 fn mcp_target(&self, req: &ControlRequest) -> Option<McpTarget> {
2018 let ControlRequestBody::McpMessage(m) = &req.request else { return None };
2019 let server = self.mcp_servers.iter().find(|s| s.name == m.server_name).cloned().or_else(|| {
2020 let dynamic = self.dynamic_mcp_servers.read().unwrap_or_else(std::sync::PoisonError::into_inner);
2021 dynamic.iter().find(|s| s.name == m.server_name).cloned()
2022 })?;
2023 let registration = server.register_call(&m.message);
2024 Some((server, registration))
2025 }
2026
2027 async fn respond(&self, req: ControlRequest, mcp: Option<McpTarget>) -> ControlResponse {
2028 match req.request {
2029 ControlRequestBody::HookCallback(hcb) => {
2030 let span = tracing::info_span!(
2031 "claude.hook",
2032 callback_id = %hcb.callback_id,
2033 event = ?hcb.input.hook_event_name,
2034 tool = hcb.input.tool_name.as_deref().unwrap_or(""),
2035 blocked = tracing::field::Empty,
2036 );
2037 let output = self.hooks.dispatch(&hcb.callback_id, hcb.input).instrument(span.clone()).await;
2038 if let Some(ref o) = output {
2039 span.record("blocked", o.is_block());
2040 }
2041 match output {
2042 Some(output) => match serde_json::to_value(output) {
2043 Ok(v) => ControlResponse::success(&req.request_id, v),
2044 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
2045 },
2046 None => ControlResponse::error(
2047 &req.request_id,
2048 format!("no hook callback registered for id {}", hcb.callback_id),
2049 ),
2050 }
2051 }
2052 ControlRequestBody::CanUseTool(cut) => match &self.can_use_tool {
2053 Some(handler) => {
2054 let original = cut.input.clone();
2055 let decision = match (handler.0)(cut).await {
2056 ToolDecision::Allow { updated_input, updated_permissions } => ToolDecision::Allow {
2058 updated_input: Some(updated_input.unwrap_or(original)),
2059 updated_permissions,
2060 },
2061 deny @ ToolDecision::Deny { .. } => deny,
2062 };
2063 match serde_json::to_value(decision) {
2064 Ok(v) => ControlResponse::success(&req.request_id, v),
2065 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
2066 }
2067 }
2068 None => ControlResponse::error(&req.request_id, "no can_use_tool handler"),
2069 },
2070 ControlRequestBody::McpMessage(m) => {
2071 let span = tracing::info_span!(
2072 "claude.tool",
2073 server = %m.server_name,
2074 method = m.message.get("method").and_then(|v| v.as_str()).unwrap_or(""),
2075 tool = m.message.pointer("/params/name").and_then(|v| v.as_str()).unwrap_or(""),
2076 );
2077 let reply = match mcp {
2078 Some((server, registration)) => {
2079 let session_id = self.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
2080 server.handle_in_session(&m.message, session_id, registration).instrument(span).await
2081 }
2082 None => serde_json::json!({
2083 "jsonrpc": "2.0",
2084 "id": m.message.get("id"),
2085 "error": { "code": -32601, "message": format!("Server '{}' not found", m.server_name) },
2086 }),
2087 };
2088 ControlResponse::success(&req.request_id, serde_json::json!({ "mcp_response": reply }))
2089 }
2090 ControlRequestBody::Elicitation(e) => match &self.on_elicitation {
2091 Some(handler) => match serde_json::to_value((handler.0)(e).await) {
2092 Ok(v) => ControlResponse::success(&req.request_id, v),
2093 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
2094 },
2095 None => ControlResponse::error(&req.request_id, "no on_elicitation handler"),
2096 },
2097 ControlRequestBody::RequestUserDialog(d) => match &self.on_user_dialog {
2098 Some(handler) => match serde_json::to_value((handler.0)(d).await) {
2099 Ok(v) => ControlResponse::success(&req.request_id, v),
2100 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
2101 },
2102 None => ControlResponse::error(&req.request_id, "no on_user_dialog handler"),
2103 },
2104 ControlRequestBody::Unsupported => {
2105 ControlResponse::error(&req.request_id, "unsupported control request subtype")
2106 }
2107 }
2108 }
2109
2110 async fn write(&self, response: &ControlResponse) {
2111 match serde_json::to_vec(response) {
2112 Ok(bytes) => if let Some(tx) = self.stdin_tx.upgrade() {
2113 let _ = tx.send(bytes).await;
2114 } else { tracing::debug!("session closed; dropping control response") },
2115 Err(e) => tracing::warn!(error = %e, "failed to serialize control response"),
2116 }
2117 }
2118}