use std::collections::VecDeque;
use std::fmt;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock, RwLock};
use std::time::Duration;
use dashmap::DashMap;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
use tokio::process::Command;
use tokio::sync::{mpsc, oneshot, watch, Mutex};
use tokio::task::JoinHandle;
use tracing::Instrument;
use crate::hooks::HookRegistry;
use crate::mcp::{server_map, SdkMcpServer};
use crate::protocol::{
Autocompact, CanUseToolRequest, ControlRequest, ControlRequestBody, ControlResponse, Effort,
ElicitationRequest, ElicitationResponse, InboundControlResponseBody, InboundMessage, Initialize,
OutboundControlRequest, PermissionMode, PermissionPrompts, ResultMessage, Thinking, ThinkingDisplay,
ToolDecision,
UserDialogRequest, UserDialogResponse,
};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SessionError {
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("json: {0}")]
Json(#[from] serde_json::Error),
#[error("process exited (code: {code:?}); stderr tail:\n{stderr}")]
ProcessExited {
code: Option<i32>,
stderr: String,
},
#[error("session closed")]
Closed,
#[error("control request `{subtype}` failed: {error}")]
ControlError {
subtype: String,
error: String,
},
#[error("control request `{0}` timed out")]
ControlTimeout(String),
#[error("code mode: {0}")]
CodeMode(#[from] crate::code_mode::CodeModeError),
#[error("Claude Code {found} is older than {min}, the oldest version this SDK supports; run `claude update`")]
UnsupportedCliVersion {
found: String,
min: &'static str,
},
#[error("invalid recording: {0}")]
InvalidRecording(String),
}
pub type Result<T> = std::result::Result<T, SessionError>;
const STATE_RUNNING: u8 = 0;
const STATE_CLOSING: u8 = 1;
const STATE_DEAD: u8 = 2;
const STDERR_TAIL_LINES: usize = 40;
const STDERR_LINGER: Duration = Duration::from_millis(500);
const STDOUT_LINGER: Duration = Duration::from_millis(100);
#[cfg(unix)]
const GROUP_GRACE: Duration = Duration::from_secs(2);
const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(60);
pub const DEFAULT_CONTROL_TIMEOUT: Duration = Duration::from_secs(60);
pub const MIN_CLI_VERSION: &str = "2.1.329";
const CLOSE_GRACE: Duration = Duration::from_secs(5);
type PermFuture = Pin<Box<dyn Future<Output = ToolDecision> + Send + 'static>>;
#[derive(Clone)]
pub struct CanUseTool(Arc<dyn Fn(CanUseToolRequest) -> PermFuture + Send + Sync>);
impl CanUseTool {
pub fn new<F, Fut>(f: F) -> Self
where
F: Fn(CanUseToolRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ToolDecision> + Send + 'static,
{
Self(Arc::new(move |req| Box::pin(f(req))))
}
}
type ElicitFuture = Pin<Box<dyn Future<Output = ElicitationResponse> + Send + 'static>>;
#[derive(Clone)]
pub struct OnElicitation(Arc<dyn Fn(ElicitationRequest) -> ElicitFuture + Send + Sync>);
impl OnElicitation {
pub fn new<F, Fut>(f: F) -> Self
where
F: Fn(ElicitationRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ElicitationResponse> + Send + 'static,
{
Self(Arc::new(move |req| Box::pin(f(req))))
}
}
type DialogFuture = Pin<Box<dyn Future<Output = UserDialogResponse> + Send + 'static>>;
#[derive(Clone)]
pub struct OnUserDialog(Arc<dyn Fn(UserDialogRequest) -> DialogFuture + Send + Sync>);
impl OnUserDialog {
pub fn new<F, Fut>(f: F) -> Self
where
F: Fn(UserDialogRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = UserDialogResponse> + Send + 'static,
{
Self(Arc::new(move |req| Box::pin(f(req))))
}
}
#[derive(Clone)]
pub struct OnStderr(Arc<dyn Fn(&str) + Send + Sync>);
impl OnStderr {
pub fn new(f: impl Fn(&str) + Send + Sync + 'static) -> Self {
Self(Arc::new(f))
}
}
#[derive(Debug, Clone, Default)]
pub struct McpCall {
pub timeout: Option<Duration>,
pub result_not_for_model: bool,
pub check_permissions: bool,
}
#[derive(Debug, Clone, Default)]
pub struct ReloadPlugins {
pub add_plugins: Vec<serde_json::Value>,
pub hold_on_cache_impact: bool,
pub refuse_if_busy: bool,
}
macro_rules! opaque_debug {
($($t:ident),*) => {$(
impl fmt::Debug for $t {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(concat!(stringify!($t), "(..)"))
}
}
)*};
}
opaque_debug!(CanUseTool, OnElicitation, OnUserDialog, OnStderr);
#[derive(Debug, Clone)]
pub struct SessionOptions {
pub binary: PathBuf,
pub cwd: Option<PathBuf>,
pub model: Option<String>,
pub effort: Option<Effort>,
pub permission_mode: Option<PermissionMode>,
pub fallback_model: Option<String>,
pub thinking: Option<Thinking>,
pub thinking_display: Option<ThinkingDisplay>,
pub max_thinking_tokens: Option<u32>,
pub max_turns: Option<u32>,
pub max_budget_usd: Option<f64>,
pub task_budget: Option<u32>,
pub resume: Option<String>,
pub resume_session_at: Option<String>,
pub continue_conversation: bool,
pub fork_session: bool,
pub session_id: Option<String>,
pub persist_session: bool,
pub name: Option<String>,
pub code_mode: bool,
pub tool_search: bool,
pub include_partial: bool,
pub hooks: HookRegistry,
pub can_use_tool: Option<CanUseTool>,
pub mcp_servers: Vec<SdkMcpServer>,
pub allowed_tools: Vec<String>,
pub disallowed_tools: Vec<String>,
pub tools: Option<Vec<String>>,
pub add_dirs: Vec<PathBuf>,
pub strict_mcp_config: bool,
pub agent: Option<String>,
pub append_subagent_system_prompt: Option<String>,
pub plugin_dirs: Vec<PathBuf>,
pub betas: Vec<String>,
pub debug_file: Option<PathBuf>,
pub plugin_urls: Vec<String>,
pub files: Vec<String>,
pub autocompact: Option<Autocompact>,
pub permission_prompts: Option<PermissionPrompts>,
pub worktree: Option<Option<String>>,
pub bare: bool,
pub safe_mode: bool,
pub restricted: bool,
pub disable_slash_commands: bool,
pub brief: bool,
pub include_hook_events: bool,
pub extra_args: Vec<String>,
pub control_timeout: Duration,
pub on_elicitation: Option<OnElicitation>,
pub on_user_dialog: Option<OnUserDialog>,
pub on_stderr: Option<OnStderr>,
pub setting_sources: Option<Vec<String>>,
pub settings: Option<serde_json::Value>,
pub record: Option<PathBuf>,
pub clear_env: bool,
pub env: Vec<(String, String)>,
}
impl Default for SessionOptions {
fn default() -> Self {
Self {
binary: PathBuf::from("claude"),
cwd: None,
model: None,
effort: None,
permission_mode: None,
fallback_model: None,
thinking: None,
thinking_display: None,
max_thinking_tokens: None,
max_turns: None,
max_budget_usd: None,
task_budget: None,
resume: None,
resume_session_at: None,
continue_conversation: false,
fork_session: false,
session_id: None,
persist_session: true,
name: None,
code_mode: false,
tool_search: false,
include_partial: false,
hooks: HookRegistry::new(),
can_use_tool: None,
mcp_servers: vec![],
allowed_tools: vec![],
disallowed_tools: vec![],
tools: None,
add_dirs: vec![],
strict_mcp_config: false,
agent: None,
append_subagent_system_prompt: None,
plugin_dirs: vec![],
betas: vec![],
debug_file: None,
plugin_urls: vec![],
files: vec![],
autocompact: None,
permission_prompts: None,
worktree: None,
bare: false,
safe_mode: false,
restricted: false,
disable_slash_commands: false,
brief: false,
include_hook_events: false,
extra_args: vec![],
control_timeout: DEFAULT_CONTROL_TIMEOUT,
on_elicitation: None,
on_user_dialog: None,
on_stderr: None,
setting_sources: None,
settings: None,
record: None,
clear_env: false,
env: vec![],
}
}
}
pub type EventRx = mpsc::UnboundedReceiver<Arc<InboundMessage>>;
#[derive(Default)]
struct Fanout {
subs: Vec<mpsc::UnboundedSender<Arc<InboundMessage>>>,
ended: bool,
}
fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
type Pending = DashMap<String, oneshot::Sender<InboundControlResponseBody>>;
#[derive(Debug, Clone)]
pub(crate) struct ExitInfo {
pub(crate) code: Option<i32>,
pub(crate) stderr: String,
}
pub(crate) struct Transport {
pub(crate) stdin: Box<dyn AsyncWrite + Unpin + Send>,
pub(crate) stdout: Box<dyn AsyncRead + Unpin + Send>,
pub(crate) exit: Pin<Box<dyn Future<Output = Option<i32>> + Send>>,
pub(crate) stderr_tail: Pin<Box<dyn Future<Output = String> + Send>>,
pub(crate) pgid: Option<i32>,
}
#[derive(Clone)]
pub struct Session(Arc<SessionInner>);
#[derive(Clone)]
pub struct WeakSession(std::sync::Weak<SessionInner>);
impl WeakSession {
pub fn upgrade(&self) -> Option<Session> {
self.0.upgrade().map(Session)
}
}
impl fmt::Debug for WeakSession {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("WeakSession(..)")
}
}
struct SessionInner {
session_id: Arc<RwLock<Option<String>>>,
stdin_tx: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
fanout: Arc<std::sync::Mutex<Fanout>>,
pending: Arc<Pending>,
next_request_id: AtomicU64,
state: Arc<AtomicU8>,
exit: watch::Receiver<Option<ExitInfo>>,
pgid: Option<i32>,
include_partial: bool,
initialize_response: OnceLock<serde_json::Value>,
cli_version: OnceLock<String>,
control_timeout: Duration,
responder: Arc<Responder>,
turns_in_flight: Arc<AtomicUsize>,
reader_done: watch::Receiver<bool>,
group_ended: AtomicBool,
_tasks: [JoinHandle<()>; 3],
}
struct Responder {
stdin_tx: mpsc::WeakSender<Vec<u8>>,
hooks: HookRegistry,
can_use_tool: Option<CanUseTool>,
on_elicitation: Option<OnElicitation>,
on_user_dialog: Option<OnUserDialog>,
mcp_servers: Vec<SdkMcpServer>,
dynamic_mcp_servers: RwLock<Vec<SdkMcpServer>>,
in_flight: DashMap<String, tokio::task::AbortHandle>,
session_id: Arc<RwLock<Option<String>>>,
}
impl Session {
pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self> {
let binary = if opts.code_mode {
check_binary_version(&opts.binary).await?;
crate::code_mode::patched_binary(&opts.binary).await?
} else {
opts.binary.clone()
};
let mut cmd = Command::new(&binary);
if opts.clear_env {
cmd.env_clear();
}
cmd.args([
"--output-format", "stream-json",
"--verbose",
"--input-format", "stream-json",
"--await-initialize",
"--replay-user-messages",
]);
if opts.include_partial {
cmd.arg("--include-partial-messages");
}
if let Some(ref m) = opts.model {
cmd.args(["--model", m]);
}
cmd.args(cli_args(&opts));
let allowed: Vec<String> = opts.allowed_tools.iter().cloned()
.chain(opts.mcp_servers.iter().flat_map(SdkMcpServer::qualified_tool_names))
.collect();
if !allowed.is_empty() {
cmd.args(["--allowedTools", &allowed.join(",")]);
}
if !opts.disallowed_tools.is_empty() {
cmd.args(["--disallowedTools", &opts.disallowed_tools.join(",")]);
}
let settings = match (&opts.settings, opts.code_mode) {
(Some(serde_json::Value::String(path)), true) => {
Some(read_settings_file(path, opts.cwd.as_deref()).await?)
}
(settings, _) => settings.clone(),
};
match settings_arg(settings, opts.code_mode)? {
Some(serde_json::Value::String(path)) => {
cmd.args(["--settings", &path]);
}
Some(settings) => {
cmd.args(["--settings", &settings.to_string()]);
}
None => {}
}
cmd.args(&opts.extra_args);
if let Some(ref cwd) = opts.cwd {
cmd.current_dir(cwd);
}
cmd.env("CLAUDE_CODE_ENTRYPOINT", "sdk-cli");
if opts.code_mode {
cmd.env("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE", "1");
}
if opts.tool_search {
cmd.env("ENABLE_TOOL_SEARCH", "1");
}
for (k, v) in &opts.env {
cmd.env(k, v);
}
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(false); #[cfg(unix)]
cmd.process_group(0);
let record = open_record(&opts).await?;
let mut child = cmd.spawn()?;
let pgid = child.id().and_then(|id| i32::try_from(id).ok());
let (Some(stdin), Some(stdout), Some(stderr)) =
(child.stdin.take(), child.stdout.take(), child.stderr.take())
else {
return Err(SessionError::Io(std::io::Error::other("subprocess pipes missing")));
};
let tail = Arc::new(std::sync::Mutex::new(VecDeque::with_capacity(STDERR_TAIL_LINES)));
let mut drain = tokio::spawn(drain_stderr(stderr, opts.on_stderr.clone(), tail.clone()));
let exit = Box::pin(async move { child.wait().await.ok().and_then(|s| s.code()) });
let stderr_tail = Box::pin(async move {
if tokio::time::timeout(STDERR_LINGER, &mut drain).await.is_err() {
drain.abort();
}
Vec::from(std::mem::take(&mut *lock(&tail))).join("\n")
});
let transport =
Transport { stdin: Box::new(stdin), stdout: Box::new(stdout), exit, stderr_tail, pgid };
Self::connect(transport, opts, init, record).await
}
pub(crate) async fn connect(
transport: Transport,
opts: SessionOptions,
mut init: Initialize,
record: Option<tokio::fs::File>,
) -> Result<Self> {
let Transport { stdin, stdout, exit: exit_fut, stderr_tail, pgid } = transport;
let (stdin_tx, mut stdin_rx) = mpsc::channel::<Vec<u8>>(256);
let fanout = Arc::new(std::sync::Mutex::new(Fanout::default()));
let session_id = Arc::new(RwLock::new(None));
let pending: Arc<Pending> = Arc::new(DashMap::new());
let state = Arc::new(AtomicU8::new(STATE_RUNNING));
let (exit_tx, exit_rx) = watch::channel(None);
let (reader_done_tx, reader_done) = watch::channel(false);
let turns_in_flight = Arc::new(AtomicUsize::new(0));
let writer = tokio::spawn(async move {
let mut w = BufWriter::new(stdin);
while let Some(bytes) = stdin_rx.recv().await {
if w.write_all(&bytes).await.is_err()
|| w.write_all(b"\n").await.is_err()
|| w.flush().await.is_err()
{
break;
}
}
let _ = w.shutdown().await;
});
let state2 = state.clone();
let watchdog = tokio::spawn(async move {
let code = exit_fut.await;
state2.store(STATE_DEAD, Ordering::SeqCst);
let stderr = stderr_tail.await;
let _ = exit_tx.send(Some(ExitInfo { code, stderr }));
});
let responder = Arc::new(Responder {
stdin_tx: stdin_tx.downgrade(),
hooks: opts.hooks.clone(),
can_use_tool: opts.can_use_tool.clone(),
on_elicitation: opts.on_elicitation.clone(),
on_user_dialog: opts.on_user_dialog.clone(),
mcp_servers: opts.mcp_servers.iter().map(SdkMcpServer::for_session).collect(),
dynamic_mcp_servers: RwLock::new(vec![]),
in_flight: DashMap::new(),
session_id: session_id.clone(),
});
let reader = tokio::spawn(read_loop(stdout, Reader {
record,
exit: exit_rx.clone(),
fanout: fanout.clone(),
session_id: session_id.clone(),
pending: pending.clone(),
turns_in_flight: turns_in_flight.clone(),
responder: responder.clone(),
done: reader_done_tx,
}));
let session = Session(Arc::new(SessionInner {
session_id,
stdin_tx: Mutex::new(Some(stdin_tx)),
fanout,
pending,
next_request_id: AtomicU64::new(0),
state,
exit: exit_rx,
pgid,
include_partial: opts.include_partial,
initialize_response: OnceLock::new(),
cli_version: OnceLock::new(),
control_timeout: opts.control_timeout,
responder,
turns_in_flight,
reader_done,
group_ended: AtomicBool::new(false),
_tasks: [reader, writer, watchdog],
}));
init.hooks = opts.hooks.initialize_config();
let body = serde_json::to_value(&init)?;
let body = with_subtype(body, "initialize");
let response = session.request_with_timeout(&body, INITIALIZE_TIMEOUT).await?;
let _ = session.0.initialize_response.set(response);
session.check_cli_version().await?;
Ok(session)
}
async fn check_cli_version(&self) -> Result<()> {
let reply = self.control(&serde_json::json!({ "subtype": "get_binary_version" })).await;
let version = match reply {
Ok(v) => v.get("version").and_then(|v| v.as_str()).map(str::to_owned),
Err(e) => {
tracing::warn!(error = %e, "could not read the Claude Code version");
None
}
};
let Some(version) = version else { return Ok(()) };
if version_lt(&version, MIN_CLI_VERSION) {
self.close().await;
return Err(SessionError::UnsupportedCliVersion { found: version, min: MIN_CLI_VERSION });
}
let _ = self.0.cli_version.set(version);
Ok(())
}
pub async fn reconnect(previous_id: &str, mut opts: SessionOptions, init: Initialize) -> Result<Self> {
opts.resume = Some(previous_id.to_string());
Self::spawn(opts, init).await
}
pub async fn send<T: serde::Serialize>(&self, msg: &T) -> Result<()> {
if self.0.state.load(Ordering::Acquire) != STATE_RUNNING {
return Err(self.dead_error().await);
}
let bytes = serde_json::to_vec(msg)?;
let tx = self.0.stdin_tx.lock().await.clone().ok_or(SessionError::Closed)?;
tx.send(bytes).await.map_err(|_| SessionError::Closed)
}
pub async fn control<B: serde::Serialize>(&self, body: &B) -> Result<serde_json::Value> {
self.request_with_timeout(body, self.0.control_timeout).await
}
pub async fn interrupt(&self) -> Result<()> {
self.control(&serde_json::json!({ "subtype": "interrupt" })).await.map(|_| ())
}
pub async fn interrupt_all(&self) -> Result<()> {
let session = self.clone();
detached(async move {
let reply = session.control(&serde_json::json!({ "subtype": "interrupt", "cancel_queued": true })).await?;
let cancelled = reply.get("cancelled").and_then(|c| c.as_array()).map_or(0, Vec::len);
for _ in 0..cancelled {
decrement(&session.0.turns_in_flight);
}
Ok(())
})
.await
}
pub async fn set_model(&self, model: Option<&str>) -> Result<()> {
self.control(&serde_json::json!({ "subtype": "set_model", "model": model })).await.map(|_| ())
}
pub async fn set_model_and_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
self.control(&serde_json::json!({
"subtype": "set_model", "model": model, "system_prompt": system_prompt,
}))
.await
.map(|_| ())
}
pub async fn set_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
self.control(&serde_json::json!({
"subtype": "set_model", "model": model, "system_prompt": system_prompt,
"only_if_model_is_current": true,
}))
.await
.map(|_| ())
}
pub async fn set_max_thinking_tokens(&self, tokens: Option<u32>, display: Option<ThinkingDisplay>) -> Result<()> {
let mut body = serde_json::json!({ "subtype": "set_max_thinking_tokens", "max_thinking_tokens": tokens });
if let Some(d) = display {
body["thinking_display"] = d.as_str().into();
}
self.control(&body).await.map(|_| ())
}
pub async fn set_effort(&self, effort: Option<Effort>) -> Result<()> {
let settings = serde_json::json!({ "effortLevel": effort });
self.control(&serde_json::json!({ "subtype": "apply_flag_settings", "settings": settings }))
.await
.map(|_| ())
}
pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()> {
self.control(&serde_json::json!({ "subtype": "set_permission_mode", "mode": mode })).await.map(|_| ())
}
pub async fn stop_task(&self, task_id: &str) -> Result<()> {
self.control(&serde_json::json!({ "subtype": "stop_task", "task_id": task_id })).await.map(|_| ())
}
pub async fn context_usage(&self, exact: bool) -> Result<serde_json::Value> {
let detail = if exact { "full" } else { "summary" };
self.control(&serde_json::json!({ "subtype": "get_context_usage", "detail": detail })).await
}
pub async fn cancel_prompt(&self, uuid: &str) -> Result<()> {
let session = self.clone();
let message_uuid = uuid.to_owned();
let dropped = detached(async move {
let reply = session
.control(&serde_json::json!({ "subtype": "cancel_async_message", "message_uuid": message_uuid }))
.await?;
let dropped = reply.get("cancelled").and_then(serde_json::Value::as_bool) == Some(true);
if dropped {
decrement(&session.0.turns_in_flight);
}
Ok(dropped)
})
.await?;
if dropped {
return Ok(());
}
self.control(&serde_json::json!({ "subtype": "interrupt", "for_user_message_uuids": [uuid] }))
.await
.map(|_| ())
}
pub async fn rename_session(&self, title: &str) -> Result<()> {
self.control(&serde_json::json!({ "subtype": "rename_session", "title": title })).await.map(|_| ())
}
pub async fn rewind_files(&self, user_message_id: &str, dry_run: bool) -> Result<serde_json::Value> {
self.control(&serde_json::json!({
"subtype": "rewind_files", "user_message_id": user_message_id, "dry_run": dry_run,
}))
.await
}
pub async fn mcp_status(&self) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "mcp_status" })).await
}
pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()> {
self.control(&serde_json::json!({ "subtype": "mcp_toggle", "serverName": server, "enabled": enabled }))
.await
.map(|_| ())
}
pub async fn mcp_reconnect(&self, server: &str) -> Result<()> {
self.control(&serde_json::json!({ "subtype": "mcp_reconnect", "serverName": server })).await.map(|_| ())
}
pub async fn set_mcp_servers(
&self,
sdk: Vec<SdkMcpServer>,
external: serde_json::Map<String, serde_json::Value>,
) -> Result<serde_json::Value> {
let servers = server_map(&sdk, Some(&external));
*self.0.responder.dynamic_mcp_servers.write().unwrap_or_else(std::sync::PoisonError::into_inner) =
sdk.iter().map(SdkMcpServer::for_session).collect();
self.control(&serde_json::json!({ "subtype": "mcp_set_servers", "servers": servers })).await
}
pub async fn list_models(&self) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "list_models" })).await
}
pub async fn get_settings(&self) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "get_settings" })).await
}
pub async fn update_settings(&self, local: bool, settings: serde_json::Value) -> Result<serde_json::Value> {
let source = if local { "localSettings" } else { "userSettings" };
self.control(&serde_json::json!({ "subtype": "update_settings", "source": source, "settings": settings }))
.await
}
pub async fn get_usage(&self, skip_behaviors: bool) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "get_usage", "skip_behaviors": skip_behaviors })).await
}
pub async fn reload_skills(&self) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "reload_skills" })).await
}
pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<serde_json::Value> {
let mut body = serde_json::json!({
"subtype": "reload_plugins",
"hold_on_cache_impact": opts.hold_on_cache_impact,
"refuse_if_busy": opts.refuse_if_busy,
});
if !opts.add_plugins.is_empty() {
body["add_plugins"] = serde_json::json!(opts.add_plugins);
}
self.control(&body).await
}
pub async fn task_output(&self, task_id: &str) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "get_task_output", "task_id": task_id })).await
}
pub async fn register_repo_root(&self, directory: &str) -> Result<serde_json::Value> {
self.control(&serde_json::json!({
"subtype": "register_repo_root", "directory": directory,
"reload_claude_md": true, "reload_plugins": true, "reload_skills": true,
}))
.await
}
pub async fn mcp_call(&self, tool: &str, arguments: serde_json::Value, opts: McpCall) -> Result<serde_json::Value> {
let mut body = serde_json::json!({ "subtype": "mcp_call", "tool": tool, "arguments": arguments });
if let Some(t) = opts.timeout {
body["timeout_ms"] = serde_json::json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
}
if opts.result_not_for_model {
body["result_not_for_model"] = true.into();
}
if opts.check_permissions {
body["check_permissions"] = true.into();
}
self.control(&body).await
}
pub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "mcp_read_resource", "serverName": server, "uri": uri }))
.await
}
pub async fn read_file(&self, path: &str, max_bytes: Option<u64>, base64: bool) -> Result<serde_json::Value> {
let mut body = serde_json::json!({
"subtype": "read_file", "path": path,
"encoding": if base64 { "base64" } else { "utf-8" },
});
if let Some(n) = max_bytes {
body["max_bytes"] = n.into();
}
self.control(&body).await
}
pub async fn file_suggestions(&self, query: &str) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "file_suggestions", "query": query })).await
}
pub async fn hooks_listing(&self) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "get_hooks_listing" })).await
}
pub async fn permission_rules(&self) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "list_permission_rules" })).await
}
pub async fn session_cost(&self) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "get_session_cost" })).await
}
pub async fn reload_output_styles(&self) -> Result<serde_json::Value> {
self.control(&serde_json::json!({ "subtype": "reload_output_styles" })).await
}
pub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()> {
self.control(&serde_json::json!({ "subtype": "seed_read_state", "path": path, "mtime": mtime_ms }))
.await
.map(|_| ())
}
#[must_use]
pub fn downgrade(&self) -> WeakSession {
WeakSession(Arc::downgrade(&self.0))
}
#[must_use]
pub fn pid(&self) -> Option<u32> {
self.0.pgid.and_then(|p| u32::try_from(p).ok())
}
pub fn cli_version(&self) -> Option<&str> {
self.0.cli_version.get().map(String::as_str)
}
#[must_use = "frames buffer until the receiver is dropped"]
pub fn subscribe(&self) -> EventRx {
let (tx, rx) = mpsc::unbounded_channel();
let mut fanout = lock(&self.0.fanout);
if !fanout.ended {
fanout.subs.push(tx);
}
rx
}
pub fn session_id(&self) -> Option<String> {
self.0.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
}
#[must_use]
pub fn initialize_response(&self) -> Option<&serde_json::Value> {
self.0.initialize_response.get()
}
#[must_use]
pub fn include_partial(&self) -> bool {
self.0.include_partial
}
#[must_use]
pub fn is_busy(&self) -> bool {
self.0.turns_in_flight.load(Ordering::Acquire) > 0
}
pub(crate) async fn send_prompt(&self, message: &crate::protocol::UserMessage) -> Result<()> {
self.0.turns_in_flight.fetch_add(1, Ordering::AcqRel);
let mut counted = UnsentTurn(Some(&self.0.turns_in_flight));
self.send(message).await?;
counted.0 = None;
Ok(())
}
#[must_use]
pub fn is_alive(&self) -> bool {
self.0.state.load(Ordering::Acquire) == STATE_RUNNING
}
pub async fn close(&self) -> Option<i32> {
#[cfg(unix)]
let pgid = self.0.pgid;
let _ = self.0.state.compare_exchange(STATE_RUNNING, STATE_CLOSING, Ordering::SeqCst, Ordering::SeqCst);
#[cfg(unix)]
let mut groups = blocking(move || tool_groups(pgid)).await;
self.0.stdin_tx.lock().await.take();
let mut exit = self.wait_exit(CLOSE_GRACE).await;
#[cfg(unix)]
for signal in [nix::sys::signal::Signal::SIGTERM, nix::sys::signal::Signal::SIGKILL] {
if exit.is_some() {
break;
}
for group in blocking(move || tool_groups(pgid)).await {
if !groups.contains(&group) {
groups.push(group);
}
}
self.signal_group(signal);
exit = self.wait_exit(CLOSE_GRACE).await;
}
#[cfg(unix)]
{
groups.extend(pgid);
blocking(move || end_groups(&groups)).await;
}
#[cfg(not(unix))]
if exit.is_none() {
kill_tree(self.0.pgid);
exit = self.wait_exit(CLOSE_GRACE).await;
}
self.0.group_ended.store(true, Ordering::Release);
let mut done = self.0.reader_done.clone();
let _ = tokio::time::timeout(CLOSE_GRACE, done.wait_for(|d| *d)).await;
exit.and_then(|e| e.code)
}
async fn wait_exit(&self, timeout: Duration) -> Option<ExitInfo> {
let mut rx = self.0.exit.clone();
let waited = tokio::time::timeout(timeout, async {
rx.wait_for(Option::is_some).await.ok().and_then(|info| info.clone())
})
.await;
waited.ok().flatten()
}
#[cfg(unix)]
fn signal_group(&self, signal: nix::sys::signal::Signal) {
if let Some(pgid) = self.0.pgid {
let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), signal);
}
}
async fn request_with_timeout<B: serde::Serialize>(
&self,
body: &B,
timeout: Duration,
) -> Result<serde_json::Value> {
let n = self.0.next_request_id.fetch_add(1, Ordering::Relaxed);
let request_id = format!("req_{n}_{}", std::process::id());
let subtype = serde_json::to_value(body)?
.get("subtype")
.and_then(|s| s.as_str())
.unwrap_or("?")
.to_string();
let (tx, rx) = oneshot::channel();
self.0.pending.insert(request_id.clone(), tx);
let _registered = PendingGuard { pending: &self.0.pending, request_id: &request_id };
if lock(&self.0.fanout).ended {
return Err(self.dead_error().await);
}
let envelope = OutboundControlRequest { kind: "control_request", request_id: &request_id, request: body };
let exchange = async {
self.send(&envelope).await?;
Ok::<_, SessionError>(rx.await)
};
let reply = match tokio::time::timeout(timeout, exchange).await {
Ok(Ok(Ok(reply))) => reply,
Ok(Err(e)) => return Err(e),
Ok(Ok(Err(_))) => return Err(self.dead_error().await),
Err(_) => return Err(SessionError::ControlTimeout(subtype)),
};
match reply.subtype.as_str() {
"success" => Ok(reply.response.unwrap_or(serde_json::Value::Null)),
_ => Err(SessionError::ControlError {
subtype,
error: reply.error.unwrap_or_else(|| "unknown error".into()),
}),
}
}
async fn dead_error(&self) -> SessionError {
if self.0.state.load(Ordering::Acquire) == STATE_CLOSING {
return SessionError::Closed;
}
match self.wait_exit(Duration::from_secs(1)).await {
Some(ExitInfo { code, stderr }) => SessionError::ProcessExited { code, stderr },
None => SessionError::Closed,
}
}
}
struct PendingGuard<'a> {
pending: &'a Pending,
request_id: &'a str,
}
impl Drop for PendingGuard<'_> {
fn drop(&mut self) {
self.pending.remove(self.request_id);
}
}
impl Drop for SessionInner {
fn drop(&mut self) {
#[cfg(unix)]
if let Some(pgid) = self.pgid
&& !self.group_ended.load(Ordering::Acquire)
{
use nix::sys::signal::{killpg, Signal};
let group = nix::unistd::Pid::from_raw(pgid);
let running = self.state.load(Ordering::Acquire) != STATE_DEAD;
let mut groups = if running { tool_groups(Some(pgid)) } else { vec![] };
groups.push(pgid);
for &g in &groups {
let _ = killpg(nix::unistd::Pid::from_raw(g), Signal::SIGTERM);
}
let exit = self.exit.clone();
let cleanup = move || {
if running {
let deadline = std::time::Instant::now() + CLOSE_GRACE;
while exit.borrow().is_none()
&& killpg(group, None).is_ok()
&& std::time::Instant::now() < deadline
{
std::thread::sleep(Duration::from_millis(50));
}
}
end_groups(&groups);
};
if let Err(e) = std::thread::Builder::new().name("claude-session-cleanup".into()).spawn(cleanup) {
tracing::warn!(error = %e, "could not start the session cleanup thread");
}
}
#[cfg(not(unix))]
if !self.group_ended.load(Ordering::Acquire) && self.state.load(Ordering::Acquire) != STATE_DEAD {
kill_tree(self.pgid);
}
}
}
struct UnsentTurn<'a>(Option<&'a AtomicUsize>);
impl Drop for UnsentTurn<'_> {
fn drop(&mut self) {
if let Some(n) = self.0 {
decrement(n);
}
}
}
async fn detached<T: Send + 'static>(work: impl Future<Output = Result<T>> + Send + 'static) -> Result<T> {
tokio::spawn(work)
.await
.unwrap_or_else(|e| Err(SessionError::Io(std::io::Error::other(format!("control task failed: {e}")))))
}
#[cfg(unix)]
async fn blocking<T: Default + Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
tokio::task::spawn_blocking(work).await.unwrap_or_default()
}
#[cfg(unix)]
fn tool_groups(pgid: Option<i32>) -> Vec<i32> {
let Some(root) = pgid else { return vec![] };
let host = nix::unistd::getpgrp().as_raw();
crate::process_tree::descendant_groups(&crate::process_tree::snapshot(), root, host)
}
#[cfg(unix)]
fn end_groups(groups: &[i32]) {
use nix::sys::signal::{killpg, Signal};
let pid = nix::unistd::Pid::from_raw;
for &group in groups {
let _ = killpg(pid(group), Signal::SIGTERM);
}
let still_there = |groups: &[i32]| -> Vec<i32> {
groups.iter().copied().filter(|&g| killpg(pid(g), None).is_ok()).collect()
};
let deadline = std::time::Instant::now() + GROUP_GRACE;
let mut left = still_there(groups);
while !left.is_empty() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(50));
left = still_there(&left);
}
for group in left {
let _ = killpg(pid(group), Signal::SIGKILL);
}
}
async fn check_binary_version(binary: &std::path::Path) -> Result<()> {
let run = Command::new(binary).arg("--version").kill_on_drop(true).output();
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(30), run).await else {
return Ok(());
};
let stdout = String::from_utf8_lossy(&out.stdout);
let found = stdout.split_whitespace().next().unwrap_or_default().to_owned();
if out.status.success() && !found.is_empty() && version_lt(&found, MIN_CLI_VERSION) {
return Err(SessionError::UnsupportedCliVersion { found, min: MIN_CLI_VERSION });
}
Ok(())
}
async fn drain_stderr(
stderr: tokio::process::ChildStderr,
on_stderr: Option<OnStderr>,
tail: Arc<std::sync::Mutex<VecDeque<String>>>,
) {
let mut lines = BufReader::new(stderr).lines();
while let Ok(Some(line)) = lines.next_line().await {
if let Some(cb) = &on_stderr
&& std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (cb.0)(&line))).is_err()
{
tracing::warn!("on_stderr callback panicked");
}
let mut tail = lock(&tail);
if tail.len() == STDERR_TAIL_LINES {
tail.pop_front();
}
tail.push_back(line);
}
}
#[cfg(not(unix))]
fn kill_tree(pid: Option<i32>) {
if let Some(pid) = pid {
let _ = std::process::Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/T", "/F"])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
}
fn cli_args(opts: &SessionOptions) -> Vec<String> {
let mut args: Vec<String> = vec![];
let mut flag = |name: &str, value: Option<String>| {
if let Some(v) = value {
args.push(name.into());
args.push(v);
}
};
flag("--model", opts.model.clone());
flag("--effort", opts.effort.map(|e| e.as_str().into()));
flag("--permission-mode", opts.permission_mode.map(|m| m.as_str().into()));
flag("--fallback-model", opts.fallback_model.clone());
flag("--thinking", opts.thinking.map(|t| t.as_str().into()));
flag("--thinking-display", opts.thinking_display.map(|d| d.as_str().into()));
flag("--max-thinking-tokens", opts.max_thinking_tokens.map(|n| n.to_string()));
flag("--max-turns", opts.max_turns.map(|n| n.to_string()));
flag("--max-budget-usd", opts.max_budget_usd.map(|n| n.to_string()));
flag("--task-budget", opts.task_budget.map(|n| n.to_string()));
flag("--resume", opts.resume.clone());
flag("--resume-session-at", opts.resume_session_at.clone());
flag("--session-id", opts.session_id.clone());
flag("--name", opts.name.clone());
flag("--tools", opts.tools.as_ref().map(|t| t.join(",")));
flag("--agent", opts.agent.clone());
flag("--append-subagent-system-prompt", opts.append_subagent_system_prompt.clone());
flag("--betas", (!opts.betas.is_empty()).then(|| opts.betas.join(",")));
flag("--debug-file", opts.debug_file.as_ref().map(|p| p.display().to_string()));
flag("--setting-sources", opts.setting_sources.as_ref().map(|s| s.join(",")));
flag("--permission-prompt-tool", opts.can_use_tool.as_ref().map(|_| "stdio".into()));
flag(
"--mcp-config",
(!opts.mcp_servers.is_empty())
.then(|| serde_json::json!({ "mcpServers": server_map(&opts.mcp_servers, None) }).to_string()),
);
for dir in &opts.add_dirs {
flag("--add-dir", Some(dir.display().to_string()));
}
for dir in &opts.plugin_dirs {
flag("--plugin-dir", Some(dir.display().to_string()));
}
for url in &opts.plugin_urls {
flag("--plugin-url", Some(url.clone()));
}
for spec in &opts.files {
flag("--file", Some(spec.clone()));
}
flag("--autocompact", opts.autocompact.map(super::protocol::Autocompact::to_arg));
flag("--permission-prompts", opts.permission_prompts.map(|p| p.as_str().into()));
if let Some(Some(name)) = &opts.worktree {
flag("--worktree", Some(name.clone()));
}
if let Some(None) = opts.worktree {
args.push("--worktree".into());
}
for (on, name) in [
(opts.bare, "--bare"),
(opts.safe_mode, "--safe-mode"),
(opts.restricted, "--restricted"),
(opts.disable_slash_commands, "--disable-slash-commands"),
(opts.brief, "--brief"),
(opts.include_hook_events, "--include-hook-events"),
] {
if on {
args.push(name.into());
}
}
if opts.continue_conversation {
args.push("--continue".into());
}
if opts.fork_session {
args.push("--fork-session".into());
}
if !opts.persist_session {
args.push("--no-session-persistence".into());
}
if opts.strict_mcp_config {
args.push("--strict-mcp-config".into());
}
args
}
fn version_lt(a: &str, b: &str) -> bool {
let parse = |v: &str| -> Vec<u64> {
v.split(['.', '-', ' '])
.map_while(|part| part.parse().ok())
.collect()
};
parse(a) < parse(b)
}
fn decrement(n: &AtomicUsize) {
let mut current = n.load(Ordering::Acquire);
while current > 0 {
match n.compare_exchange_weak(current, current - 1, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => break,
Err(actual) => current = actual,
}
}
}
pub(crate) async fn open_record(opts: &SessionOptions) -> Result<Option<tokio::fs::File>> {
match &opts.record {
Some(path) => Ok(Some(tokio::fs::File::create(path).await?)),
None => Ok(None),
}
}
async fn read_settings_file(path: &str, cwd: Option<&std::path::Path>) -> Result<serde_json::Value> {
let path = match cwd {
Some(dir) => dir.join(path),
None => PathBuf::from(path),
};
Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
}
fn settings_arg(settings: Option<serde_json::Value>, code_mode: bool) -> Result<Option<serde_json::Value>> {
if !code_mode {
return Ok(settings);
}
let mut settings = settings.unwrap_or_else(|| serde_json::json!({}));
let env = settings
.as_object_mut()
.map(|obj| obj.entry("env").or_insert_with(|| serde_json::json!({})))
.and_then(serde_json::Value::as_object_mut)
.ok_or(crate::code_mode::CodeModeError::Settings)?;
env.insert("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE".into(), "1".into());
Ok(Some(settings))
}
fn with_subtype(mut body: serde_json::Value, subtype: &str) -> serde_json::Value {
if let Some(obj) = body.as_object_mut() {
obj.insert("subtype".into(), subtype.into());
}
body
}
struct Reader {
record: Option<tokio::fs::File>,
exit: watch::Receiver<Option<ExitInfo>>,
fanout: Arc<std::sync::Mutex<Fanout>>,
session_id: Arc<RwLock<Option<String>>>,
pending: Arc<Pending>,
turns_in_flight: Arc<AtomicUsize>,
responder: Arc<Responder>,
done: watch::Sender<bool>,
}
async fn read_loop(stdout: Box<dyn AsyncRead + Unpin + Send>, reader: Reader) {
let Reader { record, mut exit, fanout, session_id, pending, turns_in_flight, responder, done } = reader;
let cleanup = ReaderCleanup {
fanout: fanout.clone(),
pending,
turns_in_flight: turns_in_flight.clone(),
responder: responder.clone(),
done,
};
let mut record = record.map(BufWriter::new);
let mut lines = BufReader::new(stdout).lines();
let mut exited = false;
loop {
let next = if exited {
match tokio::time::timeout(STDOUT_LINGER, lines.next_line()).await {
Ok(next) => next,
Err(_) => {
tracing::debug!("CLI exited but stdout is held open; stopping the reader");
break;
}
}
} else {
tokio::select! {
next = lines.next_line() => next,
_ = exit.wait_for(Option::is_some) => {
exited = true;
continue;
}
}
};
let Ok(Some(line)) = next else { break };
if line.trim().is_empty() {
continue;
}
if let Some(file) = record.as_mut() {
let flush = lines.get_ref().buffer().is_empty();
if file.write_all(line.as_bytes()).await.is_err()
|| file.write_all(b"\n").await.is_err()
|| (flush && file.flush().await.is_err())
{
tracing::warn!("recording failed; continuing without it");
record = None;
}
}
match parse_frame(&line) {
InboundMessage::ControlResponse(r) => {
if let Some((_, tx)) = cleanup.pending.remove(&r.response.request_id) {
let _ = tx.send(r.response);
}
}
InboundMessage::ControlRequest(req) => {
let request_id = req.request_id.clone();
let handler = responder.clone();
let task = tokio::spawn(async move { handler.respond(req).await });
responder.in_flight.insert(request_id.clone(), task.abort_handle());
let responder = responder.clone();
tokio::spawn(async move {
let outcome = task.await;
responder.in_flight.remove(&request_id);
let response = match outcome {
Ok(response) => response,
Err(e) if e.is_cancelled() => return,
Err(e) => ControlResponse::error(&request_id, format!("handler failed: {e}")),
};
responder.write(&response).await;
});
}
InboundMessage::ControlCancelRequest(cancel) => {
if let Some((_, task)) = responder.in_flight.remove(&cancel.request_id) {
task.abort();
}
}
other => {
if let InboundMessage::Result(ref r) = other
&& r.origin.is_none()
{
decrement(&turns_in_flight);
}
if let InboundMessage::System(ref s) = other {
let mut id = session_id.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if id.as_deref() != Some(s.session_id.as_str()) {
*id = Some(s.session_id.clone());
}
}
let msg = Arc::new(other);
lock(&fanout).subs.retain(|tx| tx.send(msg.clone()).is_ok());
}
}
}
if let Some(mut file) = record
&& file.flush().await.is_err()
{
tracing::warn!("recording failed to flush");
}
}
struct ReaderCleanup {
fanout: Arc<std::sync::Mutex<Fanout>>,
pending: Arc<Pending>,
turns_in_flight: Arc<AtomicUsize>,
responder: Arc<Responder>,
done: watch::Sender<bool>,
}
impl Drop for ReaderCleanup {
fn drop(&mut self) {
{
let mut f = lock(&self.fanout);
f.ended = true;
f.subs.clear();
}
self.pending.clear();
self.turns_in_flight.store(0, Ordering::Release);
self.responder.in_flight.retain(|_, task| {
task.abort();
false
});
let _ = self.done.send(true);
}
}
fn parse_frame(line: &str) -> InboundMessage {
match serde_json::from_str(line) {
Ok(InboundMessage::Unknown) => match serde_json::from_str(line) {
Ok(value) => InboundMessage::Other(value),
Err(_) => InboundMessage::Unknown,
},
Ok(m) => m,
Err(e) => {
let value: Option<serde_json::Value> = serde_json::from_str(line).ok();
let field = |k: &str| value.as_ref().and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(str::to_owned);
if field("type").as_deref() == Some("result") {
tracing::warn!(error = %e, "undecodable result frame; ending the turn with it");
InboundMessage::Result(ResultMessage {
subtype: field("subtype").unwrap_or_else(|| "error_unparsed_result".into()),
is_error: value.as_ref().and_then(|v| v.get("is_error")).and_then(serde_json::Value::as_bool).unwrap_or(false),
result: field("result"),
session_id: field("session_id"),
origin: value.as_ref().and_then(|v| v.get("origin")).cloned(),
..ResultMessage::default()
})
} 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())) {
tracing::warn!(error = %e, "undecodable control_request; answering with an error");
InboundMessage::ControlRequest(ControlRequest {
request_id: request_id.to_owned(),
request: ControlRequestBody::Unsupported,
})
} else if let Some(value) = value {
tracing::warn!(error = %e, "undecodable frame; passing it on as Other");
InboundMessage::Other(value)
} else {
tracing::debug!(error = %e, line = %line, "non-JSON stdout line");
InboundMessage::Unknown
}
}
}
}
impl Responder {
async fn respond(&self, req: ControlRequest) -> ControlResponse {
match req.request {
ControlRequestBody::HookCallback(hcb) => {
let span = tracing::info_span!(
"claude.hook",
callback_id = %hcb.callback_id,
event = ?hcb.input.hook_event_name,
tool = hcb.input.tool_name.as_deref().unwrap_or(""),
blocked = tracing::field::Empty,
);
let output = self.hooks.dispatch(&hcb.callback_id, hcb.input).instrument(span.clone()).await;
if let Some(ref o) = output {
span.record("blocked", o.is_block());
}
match output {
Some(output) => match serde_json::to_value(output) {
Ok(v) => ControlResponse::success(&req.request_id, v),
Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
},
None => ControlResponse::error(
&req.request_id,
format!("no hook callback registered for id {}", hcb.callback_id),
),
}
}
ControlRequestBody::CanUseTool(cut) => match &self.can_use_tool {
Some(handler) => {
let original = cut.input.clone();
let decision = match (handler.0)(cut).await {
ToolDecision::Allow { updated_input, updated_permissions } => ToolDecision::Allow {
updated_input: Some(updated_input.unwrap_or(original)),
updated_permissions,
},
deny @ ToolDecision::Deny { .. } => deny,
};
match serde_json::to_value(decision) {
Ok(v) => ControlResponse::success(&req.request_id, v),
Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
}
}
None => ControlResponse::error(&req.request_id, "no can_use_tool handler"),
},
ControlRequestBody::McpMessage(m) => {
let span = tracing::info_span!(
"claude.tool",
server = %m.server_name,
method = m.message.get("method").and_then(|v| v.as_str()).unwrap_or(""),
tool = m.message.pointer("/params/name").and_then(|v| v.as_str()).unwrap_or(""),
);
let server = self.mcp_servers.iter().find(|s| s.name == m.server_name).cloned().or_else(|| {
let dynamic = self.dynamic_mcp_servers.read().unwrap_or_else(std::sync::PoisonError::into_inner);
dynamic.iter().find(|s| s.name == m.server_name).cloned()
});
let reply = match server {
Some(server) => {
let session_id = self.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
server.handle_in_session(&m.message, session_id).instrument(span).await
}
None => serde_json::json!({
"jsonrpc": "2.0",
"id": m.message.get("id"),
"error": { "code": -32601, "message": format!("Server '{}' not found", m.server_name) },
}),
};
ControlResponse::success(&req.request_id, serde_json::json!({ "mcp_response": reply }))
}
ControlRequestBody::Elicitation(e) => match &self.on_elicitation {
Some(handler) => match serde_json::to_value((handler.0)(e).await) {
Ok(v) => ControlResponse::success(&req.request_id, v),
Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
},
None => ControlResponse::error(&req.request_id, "no on_elicitation handler"),
},
ControlRequestBody::RequestUserDialog(d) => match &self.on_user_dialog {
Some(handler) => match serde_json::to_value((handler.0)(d).await) {
Ok(v) => ControlResponse::success(&req.request_id, v),
Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
},
None => ControlResponse::error(&req.request_id, "no on_user_dialog handler"),
},
ControlRequestBody::Unsupported => {
ControlResponse::error(&req.request_id, "unsupported control request subtype")
}
}
}
async fn write(&self, response: &ControlResponse) {
match serde_json::to_vec(response) {
Ok(bytes) => if let Some(tx) = self.stdin_tx.upgrade() {
let _ = tx.send(bytes).await;
} else { tracing::debug!("session closed; dropping control response") },
Err(e) => tracing::warn!(error = %e, "failed to serialize control response"),
}
}
}