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, 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 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}
467
468#[derive(Clone)]
474pub struct Session(Arc<SessionInner>);
475
476#[derive(Clone)]
478pub struct WeakSession(std::sync::Weak<SessionInner>);
479
480impl WeakSession {
481 pub fn upgrade(&self) -> Option<Session> {
483 self.0.upgrade().map(Session)
484 }
485}
486
487impl fmt::Debug for WeakSession {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489 f.write_str("WeakSession(..)")
490 }
491}
492
493struct SessionInner {
494 session_id: Arc<RwLock<Option<String>>>,
497 stdin_tx: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
500 fanout: Arc<std::sync::Mutex<Fanout>>,
501 pending: Arc<Pending>,
503 next_request_id: AtomicU64,
504 state: Arc<AtomicU8>,
505 exit: watch::Receiver<Option<ExitInfo>>,
506 pgid: Option<i32>,
507 include_partial: bool,
508 initialize_response: OnceLock<serde_json::Value>,
509 cli_version: OnceLock<String>,
510 control_timeout: Duration,
511 responder: Arc<Responder>,
512 turns_in_flight: Arc<AtomicUsize>,
514 reader_done: watch::Receiver<bool>,
516 group_ended: AtomicBool,
518 _tasks: [JoinHandle<()>; 3],
519}
520
521struct Responder {
523 stdin_tx: mpsc::WeakSender<Vec<u8>>,
526 hooks: HookRegistry,
527 can_use_tool: Option<CanUseTool>,
528 on_elicitation: Option<OnElicitation>,
529 on_user_dialog: Option<OnUserDialog>,
530 mcp_servers: Vec<SdkMcpServer>,
532 dynamic_mcp_servers: RwLock<Vec<SdkMcpServer>>,
534 in_flight: DashMap<String, tokio::task::AbortHandle>,
537 session_id: Arc<RwLock<Option<String>>>,
539}
540
541impl Session {
542 pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self> {
549 let binary = if opts.code_mode {
550 check_binary_version(&opts.binary).await?;
552 crate::code_mode::patched_binary(&opts.binary).await?
553 } else {
554 opts.binary.clone()
555 };
556 let mut cmd = Command::new(&binary);
557 if opts.clear_env {
559 cmd.env_clear();
560 }
561 cmd.args([
562 "--output-format", "stream-json",
563 "--verbose",
564 "--input-format", "stream-json",
565 "--await-initialize",
566 "--replay-user-messages",
569 ]);
570 if opts.include_partial {
571 cmd.arg("--include-partial-messages");
572 }
573 if let Some(ref m) = opts.model {
574 cmd.args(["--model", m]);
575 }
576 cmd.args(cli_args(&opts));
577 let allowed: Vec<String> = opts.allowed_tools.iter().cloned()
578 .chain(opts.mcp_servers.iter().flat_map(SdkMcpServer::qualified_tool_names))
579 .collect();
580 if !allowed.is_empty() {
581 cmd.args(["--allowedTools", &allowed.join(",")]);
582 }
583 if !opts.disallowed_tools.is_empty() {
584 cmd.args(["--disallowedTools", &opts.disallowed_tools.join(",")]);
585 }
586 let settings = match (&opts.settings, opts.code_mode) {
587 (Some(serde_json::Value::String(path)), true) => {
589 Some(read_settings_file(path, opts.cwd.as_deref()).await?)
590 }
591 (settings, _) => settings.clone(),
592 };
593 match settings_arg(settings, opts.code_mode)? {
594 Some(serde_json::Value::String(path)) => {
596 cmd.args(["--settings", &path]);
597 }
598 Some(settings) => {
599 cmd.args(["--settings", &settings.to_string()]);
600 }
601 None => {}
602 }
603 cmd.args(&opts.extra_args);
604 if let Some(ref cwd) = opts.cwd {
605 cmd.current_dir(cwd);
606 }
607 cmd.env("CLAUDE_CODE_ENTRYPOINT", "sdk-cli");
611 if opts.code_mode {
612 cmd.env("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE", "1");
613 }
614 if opts.tool_search {
615 cmd.env("ENABLE_TOOL_SEARCH", "1");
616 }
617 for (k, v) in &opts.env {
618 cmd.env(k, v);
619 }
620 cmd.stdin(Stdio::piped())
621 .stdout(Stdio::piped())
622 .stderr(Stdio::piped())
623 .kill_on_drop(false); #[cfg(unix)]
627 cmd.process_group(0);
628
629 let record = open_record(&opts).await?;
631 let mut child = cmd.spawn()?;
632 let pgid = child.id().and_then(|id| i32::try_from(id).ok());
633 let (Some(stdin), Some(stdout), Some(stderr)) =
634 (child.stdin.take(), child.stdout.take(), child.stderr.take())
635 else {
636 return Err(SessionError::Io(std::io::Error::other("subprocess pipes missing")));
637 };
638 let tail = Arc::new(std::sync::Mutex::new(VecDeque::with_capacity(STDERR_TAIL_LINES)));
639 let mut drain = tokio::spawn(drain_stderr(stderr, opts.on_stderr.clone(), tail.clone()));
640 let exit = Box::pin(async move { child.wait().await.ok().and_then(|s| s.code()) });
643 let stderr_tail = Box::pin(async move {
644 if tokio::time::timeout(STDERR_LINGER, &mut drain).await.is_err() {
645 drain.abort();
646 }
647 Vec::from(std::mem::take(&mut *lock(&tail))).join("\n")
648 });
649 let transport =
650 Transport { stdin: Box::new(stdin), stdout: Box::new(stdout), exit, stderr_tail, pgid };
651 Self::connect(transport, opts, init, record).await
652 }
653
654 pub(crate) async fn connect(
657 transport: Transport,
658 opts: SessionOptions,
659 mut init: Initialize,
660 record: Option<tokio::fs::File>,
661 ) -> Result<Self> {
662 let Transport { stdin, stdout, exit: exit_fut, stderr_tail, pgid } = transport;
663 let (stdin_tx, mut stdin_rx) = mpsc::channel::<Vec<u8>>(256);
664 let fanout = Arc::new(std::sync::Mutex::new(Fanout::default()));
665 let session_id = Arc::new(RwLock::new(None));
666 let pending: Arc<Pending> = Arc::new(DashMap::new());
667 let state = Arc::new(AtomicU8::new(STATE_RUNNING));
668 let (exit_tx, exit_rx) = watch::channel(None);
669 let (reader_done_tx, reader_done) = watch::channel(false);
670 let turns_in_flight = Arc::new(AtomicUsize::new(0));
671
672 let writer = tokio::spawn(async move {
673 let mut w = BufWriter::new(stdin);
674 while let Some(bytes) = stdin_rx.recv().await {
675 if w.write_all(&bytes).await.is_err()
676 || w.write_all(b"\n").await.is_err()
677 || w.flush().await.is_err()
678 {
679 break;
680 }
681 }
682 let _ = w.shutdown().await;
683 });
684
685 let state2 = state.clone();
686 let watchdog = tokio::spawn(async move {
687 let code = exit_fut.await;
688 state2.store(STATE_DEAD, Ordering::SeqCst);
689 let stderr = stderr_tail.await;
690 let _ = exit_tx.send(Some(ExitInfo { code, stderr }));
691 });
692
693 let responder = Arc::new(Responder {
694 stdin_tx: stdin_tx.downgrade(),
695 hooks: opts.hooks.clone(),
696 can_use_tool: opts.can_use_tool.clone(),
697 on_elicitation: opts.on_elicitation.clone(),
698 on_user_dialog: opts.on_user_dialog.clone(),
699 mcp_servers: opts.mcp_servers.iter().map(SdkMcpServer::for_session).collect(),
700 dynamic_mcp_servers: RwLock::new(vec![]),
701 in_flight: DashMap::new(),
702 session_id: session_id.clone(),
703 });
704 let reader = tokio::spawn(read_loop(stdout, Reader {
705 record,
706 exit: exit_rx.clone(),
707 fanout: fanout.clone(),
708 session_id: session_id.clone(),
709 pending: pending.clone(),
710 turns_in_flight: turns_in_flight.clone(),
711 responder: responder.clone(),
712 done: reader_done_tx,
713 }));
714
715 let session = Session(Arc::new(SessionInner {
716 session_id,
717 stdin_tx: Mutex::new(Some(stdin_tx)),
718 fanout,
719 pending,
720 next_request_id: AtomicU64::new(0),
721 state,
722 exit: exit_rx,
723 pgid,
724 include_partial: opts.include_partial,
725 initialize_response: OnceLock::new(),
726 cli_version: OnceLock::new(),
727 control_timeout: opts.control_timeout,
728 responder,
729 turns_in_flight,
730 reader_done,
731 group_ended: AtomicBool::new(false),
732 _tasks: [reader, writer, watchdog],
733 }));
734
735 init.hooks = opts.hooks.initialize_config();
736 let body = serde_json::to_value(&init)?;
737 let body = with_subtype(body, "initialize");
738 let response = session.request_with_timeout(&body, INITIALIZE_TIMEOUT).await?;
739 let _ = session.0.initialize_response.set(response);
740 session.check_cli_version().await?;
741 Ok(session)
742 }
743
744 async fn check_cli_version(&self) -> Result<()> {
747 let reply = self.control(&serde_json::json!({ "subtype": "get_binary_version" })).await;
748 let version = match reply {
749 Ok(v) => v.get("version").and_then(|v| v.as_str()).map(str::to_owned),
750 Err(e) => {
751 tracing::warn!(error = %e, "could not read the Claude Code version");
752 None
753 }
754 };
755 let Some(version) = version else { return Ok(()) };
756 if version_lt(&version, MIN_CLI_VERSION) {
757 self.close().await;
758 return Err(SessionError::UnsupportedCliVersion { found: version, min: MIN_CLI_VERSION });
759 }
760 let _ = self.0.cli_version.set(version);
761 Ok(())
762 }
763
764 pub async fn reconnect(previous_id: &str, mut opts: SessionOptions, init: Initialize) -> Result<Self> {
766 opts.resume = Some(previous_id.to_string());
767 Self::spawn(opts, init).await
768 }
769
770 pub async fn send<T: serde::Serialize>(&self, msg: &T) -> Result<()> {
772 if self.0.state.load(Ordering::Acquire) != STATE_RUNNING {
773 return Err(self.dead_error().await);
774 }
775 let bytes = serde_json::to_vec(msg)?;
776 let tx = self.0.stdin_tx.lock().await.clone().ok_or(SessionError::Closed)?;
777 tx.send(bytes).await.map_err(|_| SessionError::Closed)
778 }
779
780 pub async fn control<B: serde::Serialize>(&self, body: &B) -> Result<serde_json::Value> {
783 self.request_with_timeout(body, self.0.control_timeout).await
784 }
785
786 pub async fn interrupt(&self) -> Result<()> {
790 self.control(&serde_json::json!({ "subtype": "interrupt" })).await.map(|_| ())
791 }
792
793 pub async fn interrupt_all(&self) -> Result<()> {
796 let session = self.clone();
799 detached(async move {
800 let reply = session.control(&serde_json::json!({ "subtype": "interrupt", "cancel_queued": true })).await?;
801 let cancelled = reply.get("cancelled").and_then(|c| c.as_array()).map_or(0, Vec::len);
803 for _ in 0..cancelled {
804 decrement(&session.0.turns_in_flight);
805 }
806 Ok(())
807 })
808 .await
809 }
810
811 pub async fn set_model(&self, model: Option<&str>) -> Result<()> {
815 self.control(&serde_json::json!({ "subtype": "set_model", "model": model })).await.map(|_| ())
816 }
817
818 pub async fn set_model_and_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
823 self.control(&serde_json::json!({
824 "subtype": "set_model", "model": model, "system_prompt": system_prompt,
825 }))
826 .await
827 .map(|_| ())
828 }
829
830 pub async fn set_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
838 self.control(&serde_json::json!({
839 "subtype": "set_model", "model": model, "system_prompt": system_prompt,
840 "only_if_model_is_current": true,
841 }))
842 .await
843 .map(|_| ())
844 }
845
846 pub async fn set_max_thinking_tokens(&self, tokens: Option<u32>, display: Option<ThinkingDisplay>) -> Result<()> {
850 let mut body = serde_json::json!({ "subtype": "set_max_thinking_tokens", "max_thinking_tokens": tokens });
851 if let Some(d) = display {
852 body["thinking_display"] = d.as_str().into();
853 }
854 self.control(&body).await.map(|_| ())
855 }
856
857 pub async fn set_effort(&self, effort: Option<Effort>) -> Result<()> {
862 let settings = serde_json::json!({ "effortLevel": effort });
863 self.control(&serde_json::json!({ "subtype": "apply_flag_settings", "settings": settings }))
864 .await
865 .map(|_| ())
866 }
867
868 pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()> {
870 self.control(&serde_json::json!({ "subtype": "set_permission_mode", "mode": mode })).await.map(|_| ())
871 }
872
873 pub async fn stop_task(&self, task_id: &str) -> Result<()> {
876 self.control(&serde_json::json!({ "subtype": "stop_task", "task_id": task_id })).await.map(|_| ())
877 }
878
879 pub async fn context_usage(&self, exact: bool) -> Result<serde_json::Value> {
884 let detail = if exact { "full" } else { "summary" };
885 self.control(&serde_json::json!({ "subtype": "get_context_usage", "detail": detail })).await
886 }
887
888 pub async fn cancel_prompt(&self, uuid: &str) -> Result<()> {
893 let session = self.clone();
895 let message_uuid = uuid.to_owned();
896 let dropped = detached(async move {
897 let reply = session
898 .control(&serde_json::json!({ "subtype": "cancel_async_message", "message_uuid": message_uuid }))
899 .await?;
900 let dropped = reply.get("cancelled").and_then(serde_json::Value::as_bool) == Some(true);
901 if dropped {
902 decrement(&session.0.turns_in_flight);
904 }
905 Ok(dropped)
906 })
907 .await?;
908 if dropped {
909 return Ok(());
910 }
911 self.control(&serde_json::json!({ "subtype": "interrupt", "for_user_message_uuids": [uuid] }))
912 .await
913 .map(|_| ())
914 }
915
916 pub async fn rename_session(&self, title: &str) -> Result<()> {
918 self.control(&serde_json::json!({ "subtype": "rename_session", "title": title })).await.map(|_| ())
919 }
920
921 pub async fn rewind_files(&self, user_message_id: &str, dry_run: bool) -> Result<serde_json::Value> {
925 self.control(&serde_json::json!({
926 "subtype": "rewind_files", "user_message_id": user_message_id, "dry_run": dry_run,
927 }))
928 .await
929 }
930
931 pub async fn mcp_status(&self) -> Result<serde_json::Value> {
933 self.control(&serde_json::json!({ "subtype": "mcp_status" })).await
934 }
935
936 pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()> {
938 self.control(&serde_json::json!({ "subtype": "mcp_toggle", "serverName": server, "enabled": enabled }))
939 .await
940 .map(|_| ())
941 }
942
943 pub async fn mcp_reconnect(&self, server: &str) -> Result<()> {
945 self.control(&serde_json::json!({ "subtype": "mcp_reconnect", "serverName": server })).await.map(|_| ())
946 }
947
948 pub async fn set_mcp_servers(
954 &self,
955 sdk: Vec<SdkMcpServer>,
956 external: serde_json::Map<String, serde_json::Value>,
957 ) -> Result<serde_json::Value> {
958 let servers = server_map(&sdk, Some(&external));
959 *self.0.responder.dynamic_mcp_servers.write().unwrap_or_else(std::sync::PoisonError::into_inner) =
960 sdk.iter().map(SdkMcpServer::for_session).collect();
961 self.control(&serde_json::json!({ "subtype": "mcp_set_servers", "servers": servers })).await
962 }
963
964 pub async fn list_models(&self) -> Result<serde_json::Value> {
966 self.control(&serde_json::json!({ "subtype": "list_models" })).await
967 }
968
969 pub async fn get_settings(&self) -> Result<serde_json::Value> {
972 self.control(&serde_json::json!({ "subtype": "get_settings" })).await
973 }
974
975 pub async fn update_settings(&self, local: bool, settings: serde_json::Value) -> Result<serde_json::Value> {
979 let source = if local { "localSettings" } else { "userSettings" };
980 self.control(&serde_json::json!({ "subtype": "update_settings", "source": source, "settings": settings }))
981 .await
982 }
983
984 pub async fn get_usage(&self, skip_behaviors: bool) -> Result<serde_json::Value> {
989 self.control(&serde_json::json!({ "subtype": "get_usage", "skip_behaviors": skip_behaviors })).await
990 }
991
992 pub async fn reload_skills(&self) -> Result<serde_json::Value> {
994 self.control(&serde_json::json!({ "subtype": "reload_skills" })).await
995 }
996
997 pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<serde_json::Value> {
999 let mut body = serde_json::json!({
1000 "subtype": "reload_plugins",
1001 "hold_on_cache_impact": opts.hold_on_cache_impact,
1002 "refuse_if_busy": opts.refuse_if_busy,
1003 });
1004 if !opts.add_plugins.is_empty() {
1005 body["add_plugins"] = serde_json::json!(opts.add_plugins);
1006 }
1007 self.control(&body).await
1008 }
1009
1010 pub async fn task_output(&self, task_id: &str) -> Result<serde_json::Value> {
1013 self.control(&serde_json::json!({ "subtype": "get_task_output", "task_id": task_id })).await
1014 }
1015
1016 pub async fn register_repo_root(&self, directory: &str) -> Result<serde_json::Value> {
1020 self.control(&serde_json::json!({
1021 "subtype": "register_repo_root", "directory": directory,
1022 "reload_claude_md": true, "reload_plugins": true, "reload_skills": true,
1023 }))
1024 .await
1025 }
1026
1027 pub async fn mcp_call(&self, tool: &str, arguments: serde_json::Value, opts: McpCall) -> Result<serde_json::Value> {
1032 let mut body = serde_json::json!({ "subtype": "mcp_call", "tool": tool, "arguments": arguments });
1033 if let Some(t) = opts.timeout {
1034 body["timeout_ms"] = serde_json::json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
1035 }
1036 if opts.result_not_for_model {
1037 body["result_not_for_model"] = true.into();
1038 }
1039 if opts.check_permissions {
1040 body["check_permissions"] = true.into();
1041 }
1042 self.control(&body).await
1043 }
1044
1045 pub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<serde_json::Value> {
1048 self.control(&serde_json::json!({ "subtype": "mcp_read_resource", "serverName": server, "uri": uri }))
1049 .await
1050 }
1051
1052 pub async fn read_file(&self, path: &str, max_bytes: Option<u64>, base64: bool) -> Result<serde_json::Value> {
1056 let mut body = serde_json::json!({
1057 "subtype": "read_file", "path": path,
1058 "encoding": if base64 { "base64" } else { "utf-8" },
1059 });
1060 if let Some(n) = max_bytes {
1061 body["max_bytes"] = n.into();
1062 }
1063 self.control(&body).await
1064 }
1065
1066 pub async fn file_suggestions(&self, query: &str) -> Result<serde_json::Value> {
1069 self.control(&serde_json::json!({ "subtype": "file_suggestions", "query": query })).await
1070 }
1071
1072 pub async fn hooks_listing(&self) -> Result<serde_json::Value> {
1075 self.control(&serde_json::json!({ "subtype": "get_hooks_listing" })).await
1076 }
1077
1078 pub async fn permission_rules(&self) -> Result<serde_json::Value> {
1081 self.control(&serde_json::json!({ "subtype": "list_permission_rules" })).await
1082 }
1083
1084 pub async fn session_cost(&self) -> Result<serde_json::Value> {
1087 self.control(&serde_json::json!({ "subtype": "get_session_cost" })).await
1088 }
1089
1090 pub async fn reload_output_styles(&self) -> Result<serde_json::Value> {
1092 self.control(&serde_json::json!({ "subtype": "reload_output_styles" })).await
1093 }
1094
1095 pub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()> {
1098 self.control(&serde_json::json!({ "subtype": "seed_read_state", "path": path, "mtime": mtime_ms }))
1099 .await
1100 .map(|_| ())
1101 }
1102
1103 #[must_use]
1105 pub fn downgrade(&self) -> WeakSession {
1106 WeakSession(Arc::downgrade(&self.0))
1107 }
1108
1109 #[must_use]
1111 pub fn pid(&self) -> Option<u32> {
1112 self.0.pgid.and_then(|p| u32::try_from(p).ok())
1113 }
1114
1115 pub fn cli_version(&self) -> Option<&str> {
1117 self.0.cli_version.get().map(String::as_str)
1118 }
1119
1120 #[must_use = "frames buffer until the receiver is dropped"]
1124 pub fn subscribe(&self) -> EventRx {
1125 let (tx, rx) = mpsc::unbounded_channel();
1126 let mut fanout = lock(&self.0.fanout);
1127 if !fanout.ended {
1128 fanout.subs.push(tx);
1129 }
1130 rx
1131 }
1132
1133 pub fn session_id(&self) -> Option<String> {
1136 self.0.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
1137 }
1138
1139 #[must_use]
1141 pub fn initialize_response(&self) -> Option<&serde_json::Value> {
1142 self.0.initialize_response.get()
1143 }
1144
1145 #[must_use]
1148 pub fn include_partial(&self) -> bool {
1149 self.0.include_partial
1150 }
1151
1152 #[must_use]
1154 pub fn is_busy(&self) -> bool {
1155 self.0.turns_in_flight.load(Ordering::Acquire) > 0
1156 }
1157
1158 pub(crate) async fn send_prompt(&self, message: &crate::protocol::UserMessage) -> Result<()> {
1161 self.0.turns_in_flight.fetch_add(1, Ordering::AcqRel);
1162 let mut counted = UnsentTurn(Some(&self.0.turns_in_flight));
1165 self.send(message).await?;
1166 counted.0 = None;
1167 Ok(())
1168 }
1169
1170 #[must_use]
1172 pub fn is_alive(&self) -> bool {
1173 self.0.state.load(Ordering::Acquire) == STATE_RUNNING
1174 }
1175
1176 pub async fn close(&self) -> Option<i32> {
1183 #[cfg(unix)]
1184 let pgid = self.0.pgid;
1185 let _ = self.0.state.compare_exchange(STATE_RUNNING, STATE_CLOSING, Ordering::SeqCst, Ordering::SeqCst);
1186 #[cfg(unix)]
1189 let mut groups = blocking(move || tool_groups(pgid)).await;
1190 self.0.stdin_tx.lock().await.take();
1191 let mut exit = self.wait_exit(CLOSE_GRACE).await;
1192 #[cfg(unix)]
1193 for signal in [nix::sys::signal::Signal::SIGTERM, nix::sys::signal::Signal::SIGKILL] {
1194 if exit.is_some() {
1195 break;
1196 }
1197 for group in blocking(move || tool_groups(pgid)).await {
1198 if !groups.contains(&group) {
1199 groups.push(group);
1200 }
1201 }
1202 self.signal_group(signal);
1203 exit = self.wait_exit(CLOSE_GRACE).await;
1204 }
1205 #[cfg(unix)]
1208 {
1209 groups.extend(pgid);
1210 blocking(move || end_groups(&groups)).await;
1211 }
1212 #[cfg(not(unix))]
1213 if exit.is_none() {
1214 kill_tree(self.0.pgid);
1215 exit = self.wait_exit(CLOSE_GRACE).await;
1216 }
1217 self.0.group_ended.store(true, Ordering::Release);
1218 let mut done = self.0.reader_done.clone();
1220 let _ = tokio::time::timeout(CLOSE_GRACE, done.wait_for(|d| *d)).await;
1221 exit.and_then(|e| e.code)
1222 }
1223
1224 async fn wait_exit(&self, timeout: Duration) -> Option<ExitInfo> {
1225 let mut rx = self.0.exit.clone();
1226 let waited = tokio::time::timeout(timeout, async {
1227 rx.wait_for(Option::is_some).await.ok().and_then(|info| info.clone())
1228 })
1229 .await;
1230 waited.ok().flatten()
1231 }
1232
1233 #[cfg(unix)]
1234 fn signal_group(&self, signal: nix::sys::signal::Signal) {
1235 if let Some(pgid) = self.0.pgid {
1236 let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), signal);
1237 }
1238 }
1239
1240 async fn request_with_timeout<B: serde::Serialize>(
1243 &self,
1244 body: &B,
1245 timeout: Duration,
1246 ) -> Result<serde_json::Value> {
1247 let n = self.0.next_request_id.fetch_add(1, Ordering::Relaxed);
1248 let request_id = format!("req_{n}_{}", std::process::id());
1249 let subtype = serde_json::to_value(body)?
1250 .get("subtype")
1251 .and_then(|s| s.as_str())
1252 .unwrap_or("?")
1253 .to_string();
1254
1255 let (tx, rx) = oneshot::channel();
1257 self.0.pending.insert(request_id.clone(), tx);
1258 let _registered = PendingGuard { pending: &self.0.pending, request_id: &request_id };
1260 if lock(&self.0.fanout).ended {
1263 return Err(self.dead_error().await);
1264 }
1265 let envelope = OutboundControlRequest { kind: "control_request", request_id: &request_id, request: body };
1266 let exchange = async {
1269 self.send(&envelope).await?;
1270 Ok::<_, SessionError>(rx.await)
1271 };
1272 let reply = match tokio::time::timeout(timeout, exchange).await {
1273 Ok(Ok(Ok(reply))) => reply,
1274 Ok(Err(e)) => return Err(e),
1275 Ok(Ok(Err(_))) => return Err(self.dead_error().await),
1277 Err(_) => return Err(SessionError::ControlTimeout(subtype)),
1278 };
1279 match reply.subtype.as_str() {
1280 "success" => Ok(reply.response.unwrap_or(serde_json::Value::Null)),
1281 _ => Err(SessionError::ControlError {
1282 subtype,
1283 error: reply.error.unwrap_or_else(|| "unknown error".into()),
1284 }),
1285 }
1286 }
1287
1288 async fn dead_error(&self) -> SessionError {
1290 if self.0.state.load(Ordering::Acquire) == STATE_CLOSING {
1291 return SessionError::Closed;
1292 }
1293 match self.wait_exit(Duration::from_secs(1)).await {
1295 Some(ExitInfo { code, stderr }) => SessionError::ProcessExited { code, stderr },
1296 None => SessionError::Closed,
1297 }
1298 }
1299}
1300
1301struct PendingGuard<'a> {
1303 pending: &'a Pending,
1304 request_id: &'a str,
1305}
1306
1307impl Drop for PendingGuard<'_> {
1308 fn drop(&mut self) {
1309 self.pending.remove(self.request_id);
1310 }
1311}
1312
1313impl Drop for SessionInner {
1314 fn drop(&mut self) {
1321 #[cfg(unix)]
1322 if let Some(pgid) = self.pgid
1323 && !self.group_ended.load(Ordering::Acquire)
1324 {
1325 use nix::sys::signal::{killpg, Signal};
1326 let group = nix::unistd::Pid::from_raw(pgid);
1327 let running = self.state.load(Ordering::Acquire) != STATE_DEAD;
1328 let mut groups = if running { tool_groups(Some(pgid)) } else { vec![] };
1330 groups.push(pgid);
1331 for &g in &groups {
1332 let _ = killpg(nix::unistd::Pid::from_raw(g), Signal::SIGTERM);
1333 }
1334 let exit = self.exit.clone();
1335 let cleanup = move || {
1336 if running {
1337 let deadline = std::time::Instant::now() + CLOSE_GRACE;
1338 while exit.borrow().is_none()
1339 && killpg(group, None).is_ok()
1340 && std::time::Instant::now() < deadline
1341 {
1342 std::thread::sleep(Duration::from_millis(50));
1343 }
1344 }
1345 end_groups(&groups);
1346 };
1347 if let Err(e) = std::thread::Builder::new().name("claude-session-cleanup".into()).spawn(cleanup) {
1348 tracing::warn!(error = %e, "could not start the session cleanup thread");
1349 }
1350 }
1351 #[cfg(not(unix))]
1352 if !self.group_ended.load(Ordering::Acquire) && self.state.load(Ordering::Acquire) != STATE_DEAD {
1353 kill_tree(self.pgid);
1354 }
1355 }
1356}
1357
1358struct UnsentTurn<'a>(Option<&'a AtomicUsize>);
1360
1361impl Drop for UnsentTurn<'_> {
1362 fn drop(&mut self) {
1363 if let Some(n) = self.0 {
1364 decrement(n);
1365 }
1366 }
1367}
1368
1369async fn detached<T: Send + 'static>(work: impl Future<Output = Result<T>> + Send + 'static) -> Result<T> {
1372 tokio::spawn(work)
1373 .await
1374 .unwrap_or_else(|e| Err(SessionError::Io(std::io::Error::other(format!("control task failed: {e}")))))
1375}
1376
1377#[cfg(unix)]
1379async fn blocking<T: Default + Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
1380 tokio::task::spawn_blocking(work).await.unwrap_or_default()
1381}
1382
1383#[cfg(unix)]
1386fn tool_groups(pgid: Option<i32>) -> Vec<i32> {
1387 let Some(root) = pgid else { return vec![] };
1388 let host = nix::unistd::getpgrp().as_raw();
1389 crate::process_tree::descendant_groups(&crate::process_tree::snapshot(), root, host)
1390}
1391
1392#[cfg(unix)]
1398fn end_groups(groups: &[i32]) {
1399 use nix::sys::signal::{killpg, Signal};
1400 let pid = nix::unistd::Pid::from_raw;
1401 for &group in groups {
1402 let _ = killpg(pid(group), Signal::SIGTERM);
1403 }
1404 let still_there = |groups: &[i32]| -> Vec<i32> {
1405 groups.iter().copied().filter(|&g| killpg(pid(g), None).is_ok()).collect()
1406 };
1407 let deadline = std::time::Instant::now() + GROUP_GRACE;
1408 let mut left = still_there(groups);
1409 while !left.is_empty() && std::time::Instant::now() < deadline {
1410 std::thread::sleep(Duration::from_millis(50));
1411 left = still_there(&left);
1412 }
1413 for group in left {
1414 let _ = killpg(pid(group), Signal::SIGKILL);
1415 }
1416}
1417
1418async fn check_binary_version(binary: &std::path::Path) -> Result<()> {
1421 let run = Command::new(binary).arg("--version").kill_on_drop(true).output();
1422 let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(30), run).await else {
1423 return Ok(());
1424 };
1425 let stdout = String::from_utf8_lossy(&out.stdout);
1427 let found = stdout.split_whitespace().next().unwrap_or_default().to_owned();
1428 if out.status.success() && !found.is_empty() && version_lt(&found, MIN_CLI_VERSION) {
1429 return Err(SessionError::UnsupportedCliVersion { found, min: MIN_CLI_VERSION });
1430 }
1431 Ok(())
1432}
1433
1434async fn drain_stderr(
1437 stderr: tokio::process::ChildStderr,
1438 on_stderr: Option<OnStderr>,
1439 tail: Arc<std::sync::Mutex<VecDeque<String>>>,
1440) {
1441 let mut lines = BufReader::new(stderr).lines();
1442 while let Ok(Some(line)) = lines.next_line().await {
1443 if let Some(cb) = &on_stderr
1444 && std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (cb.0)(&line))).is_err()
1445 {
1446 tracing::warn!("on_stderr callback panicked");
1447 }
1448 let mut tail = lock(&tail);
1449 if tail.len() == STDERR_TAIL_LINES {
1450 tail.pop_front();
1451 }
1452 tail.push_back(line);
1453 }
1454}
1455
1456#[cfg(not(unix))]
1458fn kill_tree(pid: Option<i32>) {
1459 if let Some(pid) = pid {
1460 let _ = std::process::Command::new("taskkill")
1461 .args(["/PID", &pid.to_string(), "/T", "/F"])
1462 .stdout(Stdio::null())
1463 .stderr(Stdio::null())
1464 .status();
1465 }
1466}
1467
1468fn cli_args(opts: &SessionOptions) -> Vec<String> {
1470 let mut args: Vec<String> = vec![];
1471 let mut flag = |name: &str, value: Option<String>| {
1472 if let Some(v) = value {
1473 args.push(name.into());
1474 args.push(v);
1475 }
1476 };
1477 flag("--model", opts.model.clone());
1478 flag("--effort", opts.effort.map(|e| e.as_str().into()));
1479 flag("--permission-mode", opts.permission_mode.map(|m| m.as_str().into()));
1480 flag("--fallback-model", opts.fallback_model.clone());
1481 flag("--thinking", opts.thinking.map(|t| t.as_str().into()));
1482 flag("--thinking-display", opts.thinking_display.map(|d| d.as_str().into()));
1483 flag("--max-thinking-tokens", opts.max_thinking_tokens.map(|n| n.to_string()));
1484 flag("--max-turns", opts.max_turns.map(|n| n.to_string()));
1485 flag("--max-budget-usd", opts.max_budget_usd.map(|n| n.to_string()));
1486 flag("--task-budget", opts.task_budget.map(|n| n.to_string()));
1487 flag("--resume", opts.resume.clone());
1488 flag("--resume-session-at", opts.resume_session_at.clone());
1489 flag("--session-id", opts.session_id.clone());
1490 flag("--name", opts.name.clone());
1491 flag("--tools", opts.tools.as_ref().map(|t| t.join(",")));
1492 flag("--agent", opts.agent.clone());
1493 flag("--append-subagent-system-prompt", opts.append_subagent_system_prompt.clone());
1494 flag("--betas", (!opts.betas.is_empty()).then(|| opts.betas.join(",")));
1495 flag("--debug-file", opts.debug_file.as_ref().map(|p| p.display().to_string()));
1496 flag("--setting-sources", opts.setting_sources.as_ref().map(|s| s.join(",")));
1497 flag("--permission-prompt-tool", opts.can_use_tool.as_ref().map(|_| "stdio".into()));
1498 flag(
1499 "--mcp-config",
1500 (!opts.mcp_servers.is_empty())
1501 .then(|| serde_json::json!({ "mcpServers": server_map(&opts.mcp_servers, None) }).to_string()),
1502 );
1503 for dir in &opts.add_dirs {
1504 flag("--add-dir", Some(dir.display().to_string()));
1505 }
1506 for dir in &opts.plugin_dirs {
1507 flag("--plugin-dir", Some(dir.display().to_string()));
1508 }
1509 for url in &opts.plugin_urls {
1510 flag("--plugin-url", Some(url.clone()));
1511 }
1512 for spec in &opts.files {
1513 flag("--file", Some(spec.clone()));
1514 }
1515 flag("--autocompact", opts.autocompact.map(super::protocol::Autocompact::to_arg));
1516 flag("--permission-prompts", opts.permission_prompts.map(|p| p.as_str().into()));
1517 if let Some(Some(name)) = &opts.worktree {
1518 flag("--worktree", Some(name.clone()));
1519 }
1520 if let Some(None) = opts.worktree {
1521 args.push("--worktree".into());
1522 }
1523 for (on, name) in [
1524 (opts.bare, "--bare"),
1525 (opts.safe_mode, "--safe-mode"),
1526 (opts.restricted, "--restricted"),
1527 (opts.disable_slash_commands, "--disable-slash-commands"),
1528 (opts.brief, "--brief"),
1529 (opts.include_hook_events, "--include-hook-events"),
1530 ] {
1531 if on {
1532 args.push(name.into());
1533 }
1534 }
1535 if opts.continue_conversation {
1536 args.push("--continue".into());
1537 }
1538 if opts.fork_session {
1539 args.push("--fork-session".into());
1540 }
1541 if !opts.persist_session {
1542 args.push("--no-session-persistence".into());
1543 }
1544 if opts.strict_mcp_config {
1545 args.push("--strict-mcp-config".into());
1546 }
1547 args
1548}
1549
1550fn version_lt(a: &str, b: &str) -> bool {
1552 let parse = |v: &str| -> Vec<u64> {
1553 v.split(['.', '-', ' '])
1554 .map_while(|part| part.parse().ok())
1555 .collect()
1556 };
1557 parse(a) < parse(b)
1558}
1559
1560fn decrement(n: &AtomicUsize) {
1562 let mut current = n.load(Ordering::Acquire);
1563 while current > 0 {
1564 match n.compare_exchange_weak(current, current - 1, Ordering::AcqRel, Ordering::Acquire) {
1565 Ok(_) => break,
1566 Err(actual) => current = actual,
1567 }
1568 }
1569}
1570
1571pub(crate) async fn open_record(opts: &SessionOptions) -> Result<Option<tokio::fs::File>> {
1573 match &opts.record {
1574 Some(path) => Ok(Some(tokio::fs::File::create(path).await?)),
1575 None => Ok(None),
1576 }
1577}
1578
1579async fn read_settings_file(path: &str, cwd: Option<&std::path::Path>) -> Result<serde_json::Value> {
1582 let path = match cwd {
1583 Some(dir) => dir.join(path),
1584 None => PathBuf::from(path),
1585 };
1586 Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
1587}
1588
1589fn settings_arg(settings: Option<serde_json::Value>, code_mode: bool) -> Result<Option<serde_json::Value>> {
1592 if !code_mode {
1593 return Ok(settings);
1594 }
1595 let mut settings = settings.unwrap_or_else(|| serde_json::json!({}));
1596 let env = settings
1597 .as_object_mut()
1598 .map(|obj| obj.entry("env").or_insert_with(|| serde_json::json!({})))
1599 .and_then(serde_json::Value::as_object_mut)
1600 .ok_or(crate::code_mode::CodeModeError::Settings)?;
1601 env.insert("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE".into(), "1".into());
1602 Ok(Some(settings))
1603}
1604
1605fn with_subtype(mut body: serde_json::Value, subtype: &str) -> serde_json::Value {
1606 if let Some(obj) = body.as_object_mut() {
1607 obj.insert("subtype".into(), subtype.into());
1608 }
1609 body
1610}
1611
1612struct Reader {
1614 record: Option<tokio::fs::File>,
1615 exit: watch::Receiver<Option<ExitInfo>>,
1618 fanout: Arc<std::sync::Mutex<Fanout>>,
1619 session_id: Arc<RwLock<Option<String>>>,
1620 pending: Arc<Pending>,
1621 turns_in_flight: Arc<AtomicUsize>,
1622 responder: Arc<Responder>,
1623 done: watch::Sender<bool>,
1624}
1625
1626async fn read_loop(stdout: Box<dyn AsyncRead + Unpin + Send>, reader: Reader) {
1627 let Reader { record, mut exit, fanout, session_id, pending, turns_in_flight, responder, done } = reader;
1628 let cleanup = ReaderCleanup {
1630 fanout: fanout.clone(),
1631 pending,
1632 turns_in_flight: turns_in_flight.clone(),
1633 responder: responder.clone(),
1634 done,
1635 };
1636 let mut record = record.map(BufWriter::new);
1637 let mut lines = BufReader::new(stdout).lines();
1638 let mut exited = false;
1639 loop {
1640 let next = if exited {
1642 match tokio::time::timeout(STDOUT_LINGER, lines.next_line()).await {
1643 Ok(next) => next,
1644 Err(_) => {
1645 tracing::debug!("CLI exited but stdout is held open; stopping the reader");
1646 break;
1647 }
1648 }
1649 } else {
1650 tokio::select! {
1651 next = lines.next_line() => next,
1652 _ = exit.wait_for(Option::is_some) => {
1653 exited = true;
1654 continue;
1655 }
1656 }
1657 };
1658 let Ok(Some(line)) = next else { break };
1659 if line.trim().is_empty() {
1660 continue;
1661 }
1662 if let Some(file) = record.as_mut() {
1663 let flush = lines.get_ref().buffer().is_empty();
1666 if file.write_all(line.as_bytes()).await.is_err()
1667 || file.write_all(b"\n").await.is_err()
1668 || (flush && file.flush().await.is_err())
1669 {
1670 tracing::warn!("recording failed; continuing without it");
1671 record = None;
1672 }
1673 }
1674 match parse_frame(&line) {
1675 InboundMessage::ControlResponse(r) => {
1676 if let Some((_, tx)) = cleanup.pending.remove(&r.response.request_id) {
1677 let _ = tx.send(r.response);
1678 }
1679 }
1680 InboundMessage::ControlRequest(req) => {
1681 let request_id = req.request_id.clone();
1687 let handler = responder.clone();
1688 let task = tokio::spawn(async move { handler.respond(req).await });
1689 responder.in_flight.insert(request_id.clone(), task.abort_handle());
1690 let responder = responder.clone();
1691 tokio::spawn(async move {
1692 let outcome = task.await;
1693 responder.in_flight.remove(&request_id);
1694 let response = match outcome {
1695 Ok(response) => response,
1696 Err(e) if e.is_cancelled() => return,
1698 Err(e) => ControlResponse::error(&request_id, format!("handler failed: {e}")),
1699 };
1700 responder.write(&response).await;
1701 });
1702 }
1703 InboundMessage::ControlCancelRequest(cancel) => {
1704 if let Some((_, task)) = responder.in_flight.remove(&cancel.request_id) {
1705 task.abort();
1706 }
1707 }
1708 other => {
1709 if let InboundMessage::Result(ref r) = other
1710 && r.origin.is_none()
1711 {
1712 decrement(&turns_in_flight);
1713 }
1714 if let InboundMessage::System(ref s) = other {
1715 let mut id = session_id.write().unwrap_or_else(std::sync::PoisonError::into_inner);
1716 if id.as_deref() != Some(s.session_id.as_str()) {
1717 *id = Some(s.session_id.clone());
1718 }
1719 }
1720 let msg = Arc::new(other);
1721 lock(&fanout).subs.retain(|tx| tx.send(msg.clone()).is_ok());
1722 }
1723 }
1724 }
1725 if let Some(mut file) = record
1726 && file.flush().await.is_err()
1727 {
1728 tracing::warn!("recording failed to flush");
1729 }
1730}
1731
1732struct ReaderCleanup {
1734 fanout: Arc<std::sync::Mutex<Fanout>>,
1735 pending: Arc<Pending>,
1736 turns_in_flight: Arc<AtomicUsize>,
1737 responder: Arc<Responder>,
1738 done: watch::Sender<bool>,
1739}
1740
1741impl Drop for ReaderCleanup {
1742 fn drop(&mut self) {
1743 {
1744 let mut f = lock(&self.fanout);
1745 f.ended = true;
1746 f.subs.clear();
1747 }
1748 self.pending.clear();
1749 self.turns_in_flight.store(0, Ordering::Release);
1750 self.responder.in_flight.retain(|_, task| {
1753 task.abort();
1754 false
1755 });
1756 let _ = self.done.send(true);
1757 }
1758}
1759
1760fn parse_frame(line: &str) -> InboundMessage {
1764 match serde_json::from_str(line) {
1765 Ok(InboundMessage::Unknown) => match serde_json::from_str(line) {
1767 Ok(value) => InboundMessage::Other(value),
1768 Err(_) => InboundMessage::Unknown,
1769 },
1770 Ok(m) => m,
1771 Err(e) => {
1772 let value: Option<serde_json::Value> = serde_json::from_str(line).ok();
1773 let field = |k: &str| value.as_ref().and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(str::to_owned);
1774 if field("type").as_deref() == Some("result") {
1775 tracing::warn!(error = %e, "undecodable result frame; ending the turn with it");
1776 InboundMessage::Result(ResultMessage {
1777 subtype: field("subtype").unwrap_or_else(|| "error_unparsed_result".into()),
1778 is_error: value.as_ref().and_then(|v| v.get("is_error")).and_then(serde_json::Value::as_bool).unwrap_or(false),
1779 result: field("result"),
1780 session_id: field("session_id"),
1781 origin: value.as_ref().and_then(|v| v.get("origin")).cloned(),
1782 ..ResultMessage::default()
1783 })
1784 } 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())) {
1785 tracing::warn!(error = %e, "undecodable control_request; answering with an error");
1787 InboundMessage::ControlRequest(ControlRequest {
1788 request_id: request_id.to_owned(),
1789 request: ControlRequestBody::Unsupported,
1790 })
1791 } else if let Some(value) = value {
1792 tracing::warn!(error = %e, "undecodable frame; passing it on as Other");
1795 InboundMessage::Other(value)
1796 } else {
1797 tracing::debug!(error = %e, line = %line, "non-JSON stdout line");
1798 InboundMessage::Unknown
1799 }
1800 }
1801 }
1802}
1803
1804impl Responder {
1805 async fn respond(&self, req: ControlRequest) -> ControlResponse {
1806 match req.request {
1807 ControlRequestBody::HookCallback(hcb) => {
1808 let span = tracing::info_span!(
1809 "claude.hook",
1810 callback_id = %hcb.callback_id,
1811 event = ?hcb.input.hook_event_name,
1812 tool = hcb.input.tool_name.as_deref().unwrap_or(""),
1813 blocked = tracing::field::Empty,
1814 );
1815 let output = self.hooks.dispatch(&hcb.callback_id, hcb.input).instrument(span.clone()).await;
1816 if let Some(ref o) = output {
1817 span.record("blocked", o.is_block());
1818 }
1819 match output {
1820 Some(output) => match serde_json::to_value(output) {
1821 Ok(v) => ControlResponse::success(&req.request_id, v),
1822 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1823 },
1824 None => ControlResponse::error(
1825 &req.request_id,
1826 format!("no hook callback registered for id {}", hcb.callback_id),
1827 ),
1828 }
1829 }
1830 ControlRequestBody::CanUseTool(cut) => match &self.can_use_tool {
1831 Some(handler) => {
1832 let original = cut.input.clone();
1833 let decision = match (handler.0)(cut).await {
1834 ToolDecision::Allow { updated_input, updated_permissions } => ToolDecision::Allow {
1836 updated_input: Some(updated_input.unwrap_or(original)),
1837 updated_permissions,
1838 },
1839 deny @ ToolDecision::Deny { .. } => deny,
1840 };
1841 match serde_json::to_value(decision) {
1842 Ok(v) => ControlResponse::success(&req.request_id, v),
1843 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1844 }
1845 }
1846 None => ControlResponse::error(&req.request_id, "no can_use_tool handler"),
1847 },
1848 ControlRequestBody::McpMessage(m) => {
1849 let span = tracing::info_span!(
1850 "claude.tool",
1851 server = %m.server_name,
1852 method = m.message.get("method").and_then(|v| v.as_str()).unwrap_or(""),
1853 tool = m.message.pointer("/params/name").and_then(|v| v.as_str()).unwrap_or(""),
1854 );
1855 let server = self.mcp_servers.iter().find(|s| s.name == m.server_name).cloned().or_else(|| {
1856 let dynamic = self.dynamic_mcp_servers.read().unwrap_or_else(std::sync::PoisonError::into_inner);
1857 dynamic.iter().find(|s| s.name == m.server_name).cloned()
1858 });
1859 let reply = match server {
1860 Some(server) => {
1861 let session_id = self.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
1862 server.handle_in_session(&m.message, session_id).instrument(span).await
1863 }
1864 None => serde_json::json!({
1865 "jsonrpc": "2.0",
1866 "id": m.message.get("id"),
1867 "error": { "code": -32601, "message": format!("Server '{}' not found", m.server_name) },
1868 }),
1869 };
1870 ControlResponse::success(&req.request_id, serde_json::json!({ "mcp_response": reply }))
1871 }
1872 ControlRequestBody::Elicitation(e) => match &self.on_elicitation {
1873 Some(handler) => match serde_json::to_value((handler.0)(e).await) {
1874 Ok(v) => ControlResponse::success(&req.request_id, v),
1875 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1876 },
1877 None => ControlResponse::error(&req.request_id, "no on_elicitation handler"),
1878 },
1879 ControlRequestBody::RequestUserDialog(d) => match &self.on_user_dialog {
1880 Some(handler) => match serde_json::to_value((handler.0)(d).await) {
1881 Ok(v) => ControlResponse::success(&req.request_id, v),
1882 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1883 },
1884 None => ControlResponse::error(&req.request_id, "no on_user_dialog handler"),
1885 },
1886 ControlRequestBody::Unsupported => {
1887 ControlResponse::error(&req.request_id, "unsupported control request subtype")
1888 }
1889 }
1890 }
1891
1892 async fn write(&self, response: &ControlResponse) {
1893 match serde_json::to_vec(response) {
1894 Ok(bytes) => if let Some(tx) = self.stdin_tx.upgrade() {
1895 let _ = tx.send(bytes).await;
1896 } else { tracing::debug!("session closed; dropping control response") },
1897 Err(e) => tracing::warn!(error = %e, "failed to serialize control response"),
1898 }
1899 }
1900}