Skip to main content

claude_code_agent/
session.rs

1//! Persistent subprocess session — 3-task architecture.
2//!
3//!   `reader_task`   — reads stdout; answers CLI control requests (hooks,
4//!                   `can_use_tool`, `mcp_message`), routes control responses to
5//!                   waiters, fans every other frame out to all subscribers
6//!                   (one unbounded channel each: no frame is ever dropped)
7//!   `writer_task`   — drains the stdin channel into the subprocess
8//!   `watchdog_task` — waits for exit, marks the session dead, keeps stderr tail
9//!
10//! Wire protocol verified against `claude_agent_sdk` 0.1.48
11//! (_internal/query.py, _`internal/transport/subprocess_cli.py`) and a live
12//! Claude Code 2.1.329 binary.
13use std::collections::VecDeque;
14use std::fmt;
15use std::future::Future;
16use std::path::PathBuf;
17use std::pin::Pin;
18use std::process::Stdio;
19use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering};
20use std::sync::{Arc, OnceLock, RwLock};
21use std::time::Duration;
22
23use dashmap::DashMap;
24use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
25use tokio::process::Command;
26use tokio::sync::{mpsc, oneshot, watch, Mutex};
27use tokio::task::JoinHandle;
28use tracing::Instrument;
29
30use crate::hooks::HookRegistry;
31use crate::mcp::{server_map, SdkMcpServer};
32use crate::protocol::{
33    Autocompact, CanUseToolRequest, ControlRequest, ControlRequestBody, ControlResponse, Effort,
34    ElicitationRequest, ElicitationResponse, InboundControlResponseBody, InboundMessage, Initialize,
35    OutboundControlRequest, PermissionMode, PermissionPrompts, ResultMessage, Thinking, ThinkingDisplay,
36    ToolDecision,
37    UserDialogRequest, UserDialogResponse,
38};
39
40// ─── Errors ──────────────────────────────────────────────────────────────────
41
42/// Error of a session operation.
43#[derive(Debug, thiserror::Error)]
44#[non_exhaustive]
45pub enum SessionError {
46    /// An I/O error, e.g. spawning the CLI or opening a recording file.
47    #[error("io: {0}")]
48    Io(#[from] std::io::Error),
49    /// A frame could not be serialized or parsed.
50    #[error("json: {0}")]
51    Json(#[from] serde_json::Error),
52    /// The CLI process exited.
53    #[error("process exited (code: {code:?}); stderr tail:\n{stderr}")]
54    ProcessExited {
55        /// Exit code; `None` when killed by a signal.
56        code: Option<i32>,
57        /// Last lines the CLI wrote to stderr.
58        stderr: String,
59    },
60    /// The session was closed, or stdin is gone.
61    #[error("session closed")]
62    Closed,
63    /// The CLI answered a control request with an error.
64    #[error("control request `{subtype}` failed: {error}")]
65    ControlError {
66        /// The request's `subtype`.
67        subtype: String,
68        /// The CLI's error message.
69        error: String,
70    },
71    /// No answer to the control request (named by its `subtype`) in time
72    /// (`SessionOptions::control_timeout` for requests after initialize).
73    #[error("control request `{0}` timed out")]
74    ControlTimeout(String),
75    /// Building the Code Mode binary failed.
76    #[error("code mode: {0}")]
77    CodeMode(#[from] crate::code_mode::CodeModeError),
78    /// The CLI is older than `MIN_CLI_VERSION`.
79    #[error("Claude Code {found} is older than {min}, the oldest version this SDK supports; run `claude update`")]
80    UnsupportedCliVersion {
81        /// Version the CLI reported.
82        found: String,
83        /// `MIN_CLI_VERSION`.
84        min: &'static str,
85    },
86    /// A recording passed to `replay` that cannot be replayed.
87    #[error("invalid recording: {0}")]
88    InvalidRecording(String),
89}
90
91/// `Result` with `SessionError`.
92pub 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;
99/// After the CLI exits, how long stderr may still deliver its last lines.
100const STDERR_LINGER: Duration = Duration::from_millis(500);
101const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(60);
102/// Default of `SessionOptions::control_timeout`.
103pub const DEFAULT_CONTROL_TIMEOUT: Duration = Duration::from_secs(60);
104/// Oldest Claude Code version the wire protocol here is verified against.
105pub const MIN_CLI_VERSION: &str = "2.1.329";
106/// How long `close()` waits after closing stdin, and after each signal.
107const CLOSE_GRACE: Duration = Duration::from_secs(5);
108
109// ─── Options ─────────────────────────────────────────────────────────────────
110
111type PermFuture = Pin<Box<dyn Future<Output = ToolDecision> + Send + 'static>>;
112
113/// Async tool-permission handler. Setting one makes the CLI ask the host
114/// (via `can_use_tool`) whenever its own permission rules would prompt.
115#[derive(Clone)]
116pub struct CanUseTool(Arc<dyn Fn(CanUseToolRequest) -> PermFuture + Send + Sync>);
117
118impl CanUseTool {
119    /// Wrap an async handler.
120    pub fn new<F, Fut>(f: F) -> Self
121    where
122        F: Fn(CanUseToolRequest) -> Fut + Send + Sync + 'static,
123        Fut: Future<Output = ToolDecision> + Send + 'static,
124    {
125        Self(Arc::new(move |req| Box::pin(f(req))))
126    }
127}
128
129type ElicitFuture = Pin<Box<dyn Future<Output = ElicitationResponse> + Send + 'static>>;
130
131/// Answers MCP elicitations (an MCP server asking the user for input).
132/// Without one, the CLI is told the request is unsupported.
133#[derive(Clone)]
134pub struct OnElicitation(Arc<dyn Fn(ElicitationRequest) -> ElicitFuture + Send + Sync>);
135
136impl OnElicitation {
137    /// Wrap an async handler.
138    pub fn new<F, Fut>(f: F) -> Self
139    where
140        F: Fn(ElicitationRequest) -> Fut + Send + Sync + 'static,
141        Fut: Future<Output = ElicitationResponse> + Send + 'static,
142    {
143        Self(Arc::new(move |req| Box::pin(f(req))))
144    }
145}
146
147type DialogFuture = Pin<Box<dyn Future<Output = UserDialogResponse> + Send + 'static>>;
148
149/// Renders `request_user_dialog` dialogs and returns the user's choice,
150/// e.g. `UserDialogResponse::completed("retry_fallback")` for a
151/// `refusal_fallback_prompt`. List the kinds it handles in
152/// `Initialize::supported_dialog_kinds`; the CLI sends no other kind.
153#[derive(Clone)]
154pub struct OnUserDialog(Arc<dyn Fn(UserDialogRequest) -> DialogFuture + Send + Sync>);
155
156impl OnUserDialog {
157    /// Wrap an async handler.
158    pub fn new<F, Fut>(f: F) -> Self
159    where
160        F: Fn(UserDialogRequest) -> Fut + Send + Sync + 'static,
161        Fut: Future<Output = UserDialogResponse> + Send + 'static,
162    {
163        Self(Arc::new(move |req| Box::pin(f(req))))
164    }
165}
166
167/// Receives every stderr line of the CLI as it is written.
168#[derive(Clone)]
169pub struct OnStderr(Arc<dyn Fn(&str) + Send + Sync>);
170
171impl OnStderr {
172    /// Wrap a callback.
173    pub fn new(f: impl Fn(&str) + Send + Sync + 'static) -> Self {
174        Self(Arc::new(f))
175    }
176}
177
178/// Options of `Session::mcp_call`.
179#[derive(Debug, Clone, Default)]
180pub struct McpCall {
181    /// Tool-execution timeout (the CLI clamps it to 1 s – 10 min; default 2 min).
182    pub timeout: Option<Duration>,
183    /// The result goes to a program, not a model: content comes back as
184    /// the server's own MCP blocks.
185    pub result_not_for_model: bool,
186    /// Decide the call as if the model made it (permission rules, hooks,
187    /// `can_use_tool`), instead of trusting the host.
188    pub check_permissions: bool,
189}
190
191/// Options of `Session::reload_plugins`.
192#[derive(Debug, Clone, Default)]
193pub struct ReloadPlugins {
194    /// Plugins to load as well, in the `Initialize::plugins` shape.
195    pub add_plugins: Vec<serde_json::Value>,
196    /// Skip the reload when it would change the tool list the prompt cache
197    /// depends on.
198    pub hold_on_cache_impact: bool,
199    /// Fail with `reload_plugins_busy` instead of reloading during a turn.
200    pub refuse_if_busy: bool,
201}
202
203macro_rules! opaque_debug {
204    ($($t:ident),*) => {$(
205        impl fmt::Debug for $t {
206            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207                f.write_str(concat!(stringify!($t), "(..)"))
208            }
209        }
210    )*};
211}
212opaque_debug!(CanUseTool, OnElicitation, OnUserDialog, OnStderr);
213
214/// How to spawn and configure the CLI process.
215#[derive(Debug, Clone)]
216pub struct SessionOptions {
217    /// Path of the `claude` executable. Default: `claude` (looked up on `PATH`).
218    pub binary: PathBuf,
219    /// Working directory of the CLI process. `None` = inherit.
220    pub cwd: Option<PathBuf>,
221    /// `--model`
222    pub model: Option<String>,
223    /// `--effort`. `None` = CLI default.
224    pub effort: Option<Effort>,
225    /// `--permission-mode`
226    pub permission_mode: Option<PermissionMode>,
227    /// `--fallback-model`: models to try, in order, when the main model is
228    /// busy or unavailable (`AgentEvent::ModelFallback` reports a switch).
229    pub fallback_model: Option<String>,
230    /// `--thinking`.
231    pub thinking: Option<Thinking>,
232    /// `--thinking-display`.
233    pub thinking_display: Option<ThinkingDisplay>,
234    /// `--max-thinking-tokens` (older models; newer ones use `thinking`/`effort`).
235    pub max_thinking_tokens: Option<u32>,
236    /// `--max-turns`: a turn stops with `TurnErrorKind::MaxTurns` after this
237    /// many agentic turns.
238    pub max_turns: Option<u32>,
239    /// `--max-budget-usd`: a turn stops with `TurnErrorKind::MaxBudget` once
240    /// the session has spent this much.
241    pub max_budget_usd: Option<f64>,
242    /// `--task-budget`: API-side task budget in tokens.
243    pub task_budget: Option<u32>,
244    /// `--resume <id>`: continue an existing session's transcript.
245    pub resume: Option<String>,
246    /// `--resume-session-at <message id>`: with `resume`, keep the transcript
247    /// only up to this message.
248    pub resume_session_at: Option<String>,
249    /// `--continue`: continue the most recent conversation in `cwd`.
250    pub continue_conversation: bool,
251    /// `--fork-session`: with `resume`/`continue_conversation`, continue in a
252    /// new session id instead of appending to the old transcript.
253    pub fork_session: bool,
254    /// `--session-id`: use this UUID as the session id.
255    pub session_id: Option<String>,
256    /// `false` adds `--no-session-persistence`: no transcript is written,
257    /// so the session cannot be resumed.
258    pub persist_session: bool,
259    /// `--name`: display name of the session.
260    pub name: Option<String>,
261    /// Force Code Mode on: Claude gets the `REPL` tool and works by writing
262    /// JavaScript that calls its tools. The stock CLI refuses Code Mode for
263    /// SDK sessions, so this runs a patched copy of `binary`, built once and
264    /// cached (see `code_mode` module); the installed CLI is not modified.
265    pub code_mode: bool,
266    /// Enable tool search: sets `ENABLE_TOOL_SEARCH=1`.
267    /// Source: chunk-dnmy4w56.js:189
268    pub tool_search: bool,
269    /// Stream partial chunks (`--include-partial-messages`).
270    pub include_partial: bool,
271    /// Hook handlers, sent to the CLI in the initialize request.
272    pub hooks: HookRegistry,
273    /// Tool-permission handler; adds `--permission-prompt-tool stdio`.
274    /// Source: `subprocess_cli.py:218`
275    pub can_use_tool: Option<CanUseTool>,
276    /// In-process tool servers. Their tools are added to `allowed_tools`
277    /// automatically: the host defined them, so asking permission is noise.
278    pub mcp_servers: Vec<SdkMcpServer>,
279    /// `--allowedTools`: tools that run without a permission prompt.
280    pub allowed_tools: Vec<String>,
281    /// `--disallowedTools`: tools removed from the model's toolset.
282    pub disallowed_tools: Vec<String>,
283    /// `--tools`: the built-in tools available. `Some(vec![])` = none,
284    /// `None` = all.
285    pub tools: Option<Vec<String>>,
286    /// `--add-dir`: extra directories tools may access.
287    pub add_dirs: Vec<PathBuf>,
288    /// `--strict-mcp-config`: ignore MCP servers from settings files.
289    pub strict_mcp_config: bool,
290    /// `--agent`: run the session as this agent.
291    pub agent: Option<String>,
292    /// `--append-subagent-system-prompt`: appended to every subagent's
293    /// system prompt.
294    pub append_subagent_system_prompt: Option<String>,
295    /// `--plugin-dir`: load plugins from these directories.
296    pub plugin_dirs: Vec<PathBuf>,
297    /// `--betas`: API beta headers.
298    pub betas: Vec<String>,
299    /// `--debug-file`: write the CLI's debug log here.
300    pub debug_file: Option<PathBuf>,
301    /// `--plugin-url`: fetch plugin .zip files for this session only.
302    pub plugin_urls: Vec<String>,
303    /// `--file`: files to download at startup, as `file_id:relative_path`.
304    pub files: Vec<String>,
305    /// `--autocompact`: auto-compact window.
306    pub autocompact: Option<Autocompact>,
307    /// `--permission-prompts`: who answers permission prompts.
308    pub permission_prompts: Option<PermissionPrompts>,
309    /// `--worktree`: run in a new git worktree; `Some(None)` names it
310    /// automatically.
311    pub worktree: Option<Option<String>>,
312    /// `--bare`: minimal mode (no settings/plugin hooks, LSP, plugin sync, …).
313    pub bare: bool,
314    /// `--safe-mode`: start with every customization off (CLAUDE.md,
315    /// skills, plugins, hooks, MCP servers, …).
316    pub safe_mode: bool,
317    /// `--restricted`: remove the built-in tools that run commands or code,
318    /// and `WebFetch`, unless `tools` names them.
319    pub restricted: bool,
320    /// `--disable-slash-commands`: no skills or commands.
321    pub disable_slash_commands: bool,
322    /// `--brief`: give Claude the `SendUserMessage` tool.
323    pub brief: bool,
324    /// `--include-hook-events`: emit hook lifecycle frames
325    /// (`AgentEvent::System`).
326    pub include_hook_events: bool,
327    /// Extra CLI arguments, appended verbatim — for flags this struct does
328    /// not name.
329    pub extra_args: Vec<String>,
330    /// How long `Session::control` waits for the CLI's answer.
331    pub control_timeout: Duration,
332    /// Answers MCP elicitations.
333    pub on_elicitation: Option<OnElicitation>,
334    /// Renders `request_user_dialog` dialogs.
335    pub on_user_dialog: Option<OnUserDialog>,
336    /// Receives CLI stderr lines live (the last lines are also kept for
337    /// `SessionError::ProcessExited`).
338    pub on_stderr: Option<OnStderr>,
339    /// `--setting-sources`: which settings files to load ("user", "project",
340    /// "local"). `Some(vec![])` loads none — the session ignores the user's
341    /// global CLAUDE.md, skills, permission rules and hooks, and turns get
342    /// much cheaper. `None` = CLI default (all).
343    /// Source: `subprocess_cli.py:275–280`
344    pub setting_sources: Option<Vec<String>>,
345    /// `--settings`: inline settings object (permissions, env, shell `hooks`, …),
346    /// or a string: path of a settings file (relative to `cwd`). With
347    /// `code_mode` the file is read and passed inline with the Code Mode env var.
348    pub settings: Option<serde_json::Value>,
349    /// Write every stdout line to this JSONL file, for `replay::replay`.
350    pub record: Option<PathBuf>,
351    /// Start the CLI with an empty environment plus `env` only. The CLI then
352    /// needs at least HOME and PATH (and credentials) passed through `env`.
353    /// `false` (default) inherits the parent environment, like the official SDKs.
354    pub clear_env: bool,
355    /// Extra env vars passed to the subprocess.
356    pub env: Vec<(String, String)>,
357}
358
359impl Default for SessionOptions {
360    fn default() -> Self {
361        Self {
362            binary: PathBuf::from("claude"),
363            cwd: None,
364            model: None,
365            effort: None,
366            permission_mode: None,
367            fallback_model: None,
368            thinking: None,
369            thinking_display: None,
370            max_thinking_tokens: None,
371            max_turns: None,
372            max_budget_usd: None,
373            task_budget: None,
374            resume: None,
375            resume_session_at: None,
376            continue_conversation: false,
377            fork_session: false,
378            session_id: None,
379            persist_session: true,
380            name: None,
381            code_mode: false,
382            tool_search: false,
383            include_partial: false,
384            hooks: HookRegistry::new(),
385            can_use_tool: None,
386            mcp_servers: vec![],
387            allowed_tools: vec![],
388            disallowed_tools: vec![],
389            tools: None,
390            add_dirs: vec![],
391            strict_mcp_config: false,
392            agent: None,
393            append_subagent_system_prompt: None,
394            plugin_dirs: vec![],
395            betas: vec![],
396            debug_file: None,
397            plugin_urls: vec![],
398            files: vec![],
399            autocompact: None,
400            permission_prompts: None,
401            worktree: None,
402            bare: false,
403            safe_mode: false,
404            restricted: false,
405            disable_slash_commands: false,
406            brief: false,
407            include_hook_events: false,
408            extra_args: vec![],
409            control_timeout: DEFAULT_CONTROL_TIMEOUT,
410            on_elicitation: None,
411            on_user_dialog: None,
412            on_stderr: None,
413            setting_sources: None,
414            settings: None,
415            record: None,
416            clear_env: false,
417            env: vec![],
418        }
419    }
420}
421
422// ─── Session ─────────────────────────────────────────────────────────────────
423
424/// Receives every frame the CLI emits after `subscribe()`; `None` once the
425/// CLI's stdout has ended.
426pub type EventRx = mpsc::UnboundedReceiver<Arc<InboundMessage>>;
427
428/// Subscribers of the reader task. `ended` turns new subscriptions into
429/// already-closed receivers once stdout is gone.
430#[derive(Default)]
431struct Fanout {
432    subs: Vec<mpsc::UnboundedSender<Arc<InboundMessage>>>,
433    ended: bool,
434}
435
436fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
437    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
438}
439
440type Pending = DashMap<String, oneshot::Sender<InboundControlResponseBody>>;
441
442/// How the CLI ended, recorded by the watchdog.
443#[derive(Debug, Clone)]
444pub(crate) struct ExitInfo {
445    pub(crate) code: Option<i32>,
446    pub(crate) stderr: String,
447}
448
449/// Byte streams of a running CLI — a real subprocess or a replay.
450pub(crate) struct Transport {
451    pub(crate) stdin: Box<dyn AsyncWrite + Unpin + Send>,
452    pub(crate) stdout: Box<dyn AsyncRead + Unpin + Send>,
453    /// Resolves when the CLI has exited.
454    pub(crate) exit: Pin<Box<dyn Future<Output = ExitInfo> + Send>>,
455    /// Unix: process group of the CLI and everything it started (Bash
456    /// tools, …). Windows: the CLI's pid, root of its process tree.
457    pub(crate) pgid: Option<i32>,
458}
459
460/// A live Claude Code session. Cheap to clone — backed by `Arc<SessionInner>`.
461///
462/// Handlers in `SessionOptions` (`can_use_tool`, hooks, …) are owned by the
463/// session; one that needs the session should capture `Session::downgrade()`,
464/// since a captured `Session` keeps it, and the CLI, alive forever.
465#[derive(Clone)]
466pub struct Session(Arc<SessionInner>);
467
468/// A `Session` handle that does not keep the session alive.
469#[derive(Clone)]
470pub struct WeakSession(std::sync::Weak<SessionInner>);
471
472impl WeakSession {
473    /// The session, unless every `Session` handle is gone.
474    pub fn upgrade(&self) -> Option<Session> {
475        self.0.upgrade().map(Session)
476    }
477}
478
479impl fmt::Debug for WeakSession {
480    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481        f.write_str("WeakSession(..)")
482    }
483}
484
485struct SessionInner {
486    /// Current session id; every `system` frame carries it and `/clear`
487    /// starts a new one.
488    session_id: Arc<RwLock<Option<String>>>,
489    /// `None` after `close()`; dropping the last sender ends the writer task,
490    /// which closes the CLI's stdin.
491    stdin_tx: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
492    fanout: Arc<std::sync::Mutex<Fanout>>,
493    /// Host-initiated control requests awaiting a `control_response`.
494    pending: Arc<Pending>,
495    next_request_id: AtomicU64,
496    state: Arc<AtomicU8>,
497    exit: watch::Receiver<Option<ExitInfo>>,
498    pgid: Option<i32>,
499    include_partial: bool,
500    initialize_response: OnceLock<serde_json::Value>,
501    cli_version: OnceLock<String>,
502    control_timeout: Duration,
503    responder: Arc<Responder>,
504    /// Prompts sent whose `result` has not arrived yet.
505    turns_in_flight: Arc<AtomicUsize>,
506    /// `true` once the reader has handled the last stdout line.
507    reader_done: watch::Receiver<bool>,
508    _tasks: [JoinHandle<()>; 3],
509}
510
511/// What the reader task needs to answer CLI control requests.
512struct Responder {
513    /// Weak: only the Session keeps stdin open, so dropping or closing the
514    /// Session ends the CLI even while the reader task is still running.
515    stdin_tx: mpsc::WeakSender<Vec<u8>>,
516    hooks: HookRegistry,
517    can_use_tool: Option<CanUseTool>,
518    on_elicitation: Option<OnElicitation>,
519    on_user_dialog: Option<OnUserDialog>,
520    /// Servers from `SessionOptions::mcp_servers`.
521    mcp_servers: Vec<SdkMcpServer>,
522    /// Servers set later with `Session::set_mcp_servers`.
523    dynamic_mcp_servers: RwLock<Vec<SdkMcpServer>>,
524    /// Running handlers of CLI control requests, by request id, so a
525    /// `control_cancel_request` can stop them.
526    in_flight: DashMap<String, tokio::task::AbortHandle>,
527}
528
529impl Session {
530    /// Spawn a Claude Code subprocess and complete the initialize handshake.
531    ///
532    ///   1. spawn `claude --output-format stream-json --verbose
533    ///      --input-format stream-json --await-initialize …`
534    ///   2. write the `initialize` control request (with `opts.hooks`)
535    ///   3. wait for its `control_response`
536    pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self> {
537        let binary = if opts.code_mode {
538            crate::code_mode::patched_binary(&opts.binary).await?
539        } else {
540            opts.binary.clone()
541        };
542        let mut cmd = Command::new(&binary);
543        // First, so the variables set below survive it.
544        if opts.clear_env {
545            cmd.env_clear();
546        }
547        cmd.args([
548            "--output-format", "stream-json",
549            "--verbose",
550            "--input-format", "stream-json",
551            "--await-initialize",
552            // Echo each prompt when its turn starts: Agent uses it as the
553            // turn boundary. Source: `claude --help`
554            "--replay-user-messages",
555        ]);
556        if opts.include_partial {
557            cmd.arg("--include-partial-messages");
558        }
559        if let Some(ref m) = opts.model {
560            cmd.args(["--model", m]);
561        }
562        cmd.args(cli_args(&opts));
563        let allowed: Vec<String> = opts.allowed_tools.iter().cloned()
564            .chain(opts.mcp_servers.iter().flat_map(SdkMcpServer::qualified_tool_names))
565            .collect();
566        if !allowed.is_empty() {
567            cmd.args(["--allowedTools", &allowed.join(",")]);
568        }
569        if !opts.disallowed_tools.is_empty() {
570            cmd.args(["--disallowedTools", &opts.disallowed_tools.join(",")]);
571        }
572        let settings = match (&opts.settings, opts.code_mode) {
573            // The Code Mode env var must be merged into the settings object.
574            (Some(serde_json::Value::String(path)), true) => {
575                Some(read_settings_file(path, opts.cwd.as_deref()).await?)
576            }
577            (settings, _) => settings.clone(),
578        };
579        match settings_arg(settings, opts.code_mode)? {
580            // A string is a settings file path; anything else is inline JSON.
581            Some(serde_json::Value::String(path)) => {
582                cmd.args(["--settings", &path]);
583            }
584            Some(settings) => {
585                cmd.args(["--settings", &settings.to_string()]);
586            }
587            None => {}
588        }
589        cmd.args(&opts.extra_args);
590        if let Some(ref cwd) = opts.cwd {
591            cmd.current_dir(cwd);
592        }
593        // An SDK entrypoint, also when the host itself runs under Claude
594        // Desktop or VS Code, whose values the CLI would otherwise inherit
595        // and act on. `opts.env` may override it.
596        cmd.env("CLAUDE_CODE_ENTRYPOINT", "sdk-cli");
597        if opts.code_mode {
598            cmd.env("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE", "1");
599        }
600        if opts.tool_search {
601            cmd.env("ENABLE_TOOL_SEARCH", "1");
602        }
603        for (k, v) in &opts.env {
604            cmd.env(k, v);
605        }
606        cmd.stdin(Stdio::piped())
607            .stdout(Stdio::piped())
608            .stderr(Stdio::piped())
609            .kill_on_drop(false); // close() / Drop end the whole process group instead
610        // Own process group: tools the CLI starts (Bash, background tasks)
611        // join it, so close() and Drop can end them too.
612        #[cfg(unix)]
613        cmd.process_group(0);
614
615        // Before spawning, so a bad path leaves no process behind.
616        let record = open_record(&opts).await?;
617        let mut child = cmd.spawn()?;
618        let pgid = child.id().and_then(|id| i32::try_from(id).ok());
619        let (Some(stdin), Some(stdout), Some(stderr)) =
620            (child.stdin.take(), child.stdout.take(), child.stderr.take())
621        else {
622            return Err(SessionError::Io(std::io::Error::other("subprocess pipes missing")));
623        };
624        let tail = Arc::new(std::sync::Mutex::new(VecDeque::with_capacity(STDERR_TAIL_LINES)));
625        let mut drain = tokio::spawn(drain_stderr(stderr, opts.on_stderr.clone(), tail.clone()));
626        let exit = Box::pin(async move {
627            // Exit is the child's, not stderr's EOF: a tool the CLI started
628            // can inherit stderr and hold it open after the CLI is gone.
629            let code = child.wait().await.ok().and_then(|s| s.code());
630            if tokio::time::timeout(STDERR_LINGER, &mut drain).await.is_err() {
631                drain.abort();
632            }
633            let stderr = Vec::from(std::mem::take(&mut *lock(&tail))).join("\n");
634            ExitInfo { code, stderr }
635        });
636        let transport = Transport { stdin: Box::new(stdin), stdout: Box::new(stdout), exit, pgid };
637        Self::connect(transport, opts, init, record).await
638    }
639
640    /// Run the session over an already-started CLI (process or replay) and
641    /// complete the initialize handshake.
642    pub(crate) async fn connect(
643        transport: Transport,
644        opts: SessionOptions,
645        mut init: Initialize,
646        record: Option<tokio::fs::File>,
647    ) -> Result<Self> {
648        let Transport { stdin, stdout, exit: exit_fut, pgid } = transport;
649        let (stdin_tx, mut stdin_rx) = mpsc::channel::<Vec<u8>>(256);
650        let fanout = Arc::new(std::sync::Mutex::new(Fanout::default()));
651        let session_id = Arc::new(RwLock::new(None));
652        let pending: Arc<Pending> = Arc::new(DashMap::new());
653        let state = Arc::new(AtomicU8::new(STATE_RUNNING));
654        let (exit_tx, exit_rx) = watch::channel(None);
655        let (reader_done_tx, reader_done) = watch::channel(false);
656        let turns_in_flight = Arc::new(AtomicUsize::new(0));
657
658        let writer = tokio::spawn(async move {
659            let mut w = BufWriter::new(stdin);
660            while let Some(bytes) = stdin_rx.recv().await {
661                if w.write_all(&bytes).await.is_err()
662                    || w.write_all(b"\n").await.is_err()
663                    || w.flush().await.is_err()
664                {
665                    break;
666                }
667            }
668            let _ = w.shutdown().await;
669        });
670
671        let state2 = state.clone();
672        let watchdog = tokio::spawn(async move {
673            let info = exit_fut.await;
674            state2.store(STATE_DEAD, Ordering::SeqCst);
675            let _ = exit_tx.send(Some(info));
676        });
677
678        let responder = Arc::new(Responder {
679            stdin_tx: stdin_tx.downgrade(),
680            hooks: opts.hooks.clone(),
681            can_use_tool: opts.can_use_tool.clone(),
682            on_elicitation: opts.on_elicitation.clone(),
683            on_user_dialog: opts.on_user_dialog.clone(),
684            mcp_servers: opts.mcp_servers.clone(),
685            dynamic_mcp_servers: RwLock::new(vec![]),
686            in_flight: DashMap::new(),
687        });
688        let reader = tokio::spawn(read_loop(stdout, Reader {
689            record,
690            fanout: fanout.clone(),
691            session_id: session_id.clone(),
692            pending: pending.clone(),
693            turns_in_flight: turns_in_flight.clone(),
694            responder: responder.clone(),
695            done: reader_done_tx,
696        }));
697
698        let session = Session(Arc::new(SessionInner {
699            session_id,
700            stdin_tx: Mutex::new(Some(stdin_tx)),
701            fanout,
702            pending,
703            next_request_id: AtomicU64::new(0),
704            state,
705            exit: exit_rx,
706            pgid,
707            include_partial: opts.include_partial,
708            initialize_response: OnceLock::new(),
709            cli_version: OnceLock::new(),
710            control_timeout: opts.control_timeout,
711            responder,
712            turns_in_flight,
713            reader_done,
714            _tasks: [reader, writer, watchdog],
715        }));
716
717        init.hooks = opts.hooks.initialize_config();
718        let body = serde_json::to_value(&init)?;
719        let body = with_subtype(body, "initialize");
720        let response = session.request_with_timeout(&body, INITIALIZE_TIMEOUT).await?;
721        let _ = session.0.initialize_response.set(response);
722        session.check_cli_version().await?;
723        Ok(session)
724    }
725
726    /// Ask the CLI its version and refuse one older than `MIN_CLI_VERSION`.
727    /// A CLI that cannot answer is let through with a warning.
728    async fn check_cli_version(&self) -> Result<()> {
729        let reply = self.control(&serde_json::json!({ "subtype": "get_binary_version" })).await;
730        let version = match reply {
731            Ok(v) => v.get("version").and_then(|v| v.as_str()).map(str::to_owned),
732            Err(e) => {
733                tracing::warn!(error = %e, "could not read the Claude Code version");
734                None
735            }
736        };
737        let Some(version) = version else { return Ok(()) };
738        if version_lt(&version, MIN_CLI_VERSION) {
739            self.close().await;
740            return Err(SessionError::UnsupportedCliVersion { found: version, min: MIN_CLI_VERSION });
741        }
742        let _ = self.0.cli_version.set(version);
743        Ok(())
744    }
745
746    /// Spawn with `--resume <previous_id>`; the CLI reloads its own transcript.
747    pub async fn reconnect(previous_id: &str, mut opts: SessionOptions, init: Initialize) -> Result<Self> {
748        opts.resume = Some(previous_id.to_string());
749        Self::spawn(opts, init).await
750    }
751
752    /// Send a raw JSON line to the subprocess stdin.
753    pub async fn send<T: serde::Serialize>(&self, msg: &T) -> Result<()> {
754        if self.0.state.load(Ordering::Acquire) != STATE_RUNNING {
755            return Err(self.dead_error().await);
756        }
757        let bytes = serde_json::to_vec(msg)?;
758        let tx = self.0.stdin_tx.lock().await.clone().ok_or(SessionError::Closed)?;
759        tx.send(bytes).await.map_err(|_| SessionError::Closed)
760    }
761
762    /// Send a host → CLI control request and wait for its response payload.
763    /// `body` must serialize to an object with a `subtype` field.
764    pub async fn control<B: serde::Serialize>(&self, body: &B) -> Result<serde_json::Value> {
765        self.request_with_timeout(body, self.0.control_timeout).await
766    }
767
768    /// Interrupt the running turn; its stream ends with an
769    /// `AgentEvent::Error` of kind `TurnErrorKind::Execution`. Queued prompts
770    /// still run.
771    pub async fn interrupt(&self) -> Result<()> {
772        self.control(&serde_json::json!({ "subtype": "interrupt" })).await.map(|_| ())
773    }
774
775    /// Interrupt the running turn and cancel every queued prompt.
776    /// Source: binary interrupt schema (`cancel_queued`)
777    pub async fn interrupt_all(&self) -> Result<()> {
778        let reply = self.control(&serde_json::json!({ "subtype": "interrupt", "cancel_queued": true })).await?;
779        // Cancelled prompts get no `result`.
780        let cancelled = reply.get("cancelled").and_then(|c| c.as_array()).map_or(0, Vec::len);
781        for _ in 0..cancelled {
782            decrement(&self.0.turns_in_flight);
783        }
784        Ok(())
785    }
786
787    /// Switch model for the following turns. `None` clears the override, so
788    /// the CLI falls back to its default model (not to `SessionOptions::model`).
789    /// Source: binary `set_model` schema
790    pub async fn set_model(&self, model: Option<&str>) -> Result<()> {
791        self.control(&serde_json::json!({ "subtype": "set_model", "model": model })).await.map(|_| ())
792    }
793
794    /// Switch model and replace the custom system prompt. The new prompt is
795    /// sent from the next compaction on (from the next turn with
796    /// `Initialize::system_prompt_snapshot: Some(false)`).
797    /// Source: binary `set_model` schema (`system_prompt`)
798    pub async fn set_model_and_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
799        self.control(&serde_json::json!({
800            "subtype": "set_model", "model": model, "system_prompt": system_prompt,
801        }))
802        .await
803        .map(|_| ())
804    }
805
806    /// Replace the custom system prompt without switching model. `model`
807    /// must name the session's current model, or the CLI refuses. CLI
808    /// 2.1.329 can confirm the model only while the session runs the
809    /// account's default model (no `SessionOptions::model`, no `set_model`);
810    /// otherwise use `set_model_and_system_prompt`. The new prompt is sent
811    /// from the next compaction on.
812    /// Source: binary `set_model` schema (`only_if_model_is_current`)
813    pub async fn set_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
814        self.control(&serde_json::json!({
815            "subtype": "set_model", "model": model, "system_prompt": system_prompt,
816            "only_if_model_is_current": true,
817        }))
818        .await
819        .map(|_| ())
820    }
821
822    /// Thinking-token budget for the following turns (older models);
823    /// `None` restores the session's setting.
824    /// Source: binary `set_max_thinking_tokens` schema
825    pub async fn set_max_thinking_tokens(&self, tokens: Option<u32>, display: Option<ThinkingDisplay>) -> Result<()> {
826        let mut body = serde_json::json!({ "subtype": "set_max_thinking_tokens", "max_thinking_tokens": tokens });
827        if let Some(d) = display {
828            body["thinking_display"] = d.as_str().into();
829        }
830        self.control(&body).await.map(|_| ())
831    }
832
833    /// Switch effort level for the following turns; `None` clears the
834    /// override, so the CLI falls back to its default level (not to
835    /// `SessionOptions::effort`).
836    /// Source: binary `apply_flag_settings` handler (`effortLevel`)
837    pub async fn set_effort(&self, effort: Option<Effort>) -> Result<()> {
838        let settings = serde_json::json!({ "effortLevel": effort });
839        self.control(&serde_json::json!({ "subtype": "apply_flag_settings", "settings": settings }))
840            .await
841            .map(|_| ())
842    }
843
844    /// Source: binary `set_permission_mode` schema
845    pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()> {
846        self.control(&serde_json::json!({ "subtype": "set_permission_mode", "mode": mode })).await.map(|_| ())
847    }
848
849    /// Stop a background task by its `task_id` (see `AgentEvent::BackgroundTasks`).
850    /// Source: binary `stop_task` schema
851    pub async fn stop_task(&self, task_id: &str) -> Result<()> {
852        self.control(&serde_json::json!({ "subtype": "stop_task", "task_id": task_id })).await.map(|_| ())
853    }
854
855    /// Context-window usage of the session, as reported by the CLI.
856    /// `exact: true` counts each category with the token-count API; `false`
857    /// estimates from the last response's usage, without those calls.
858    /// Source: binary `get_context_usage` schema
859    pub async fn context_usage(&self, exact: bool) -> Result<serde_json::Value> {
860        let detail = if exact { "full" } else { "summary" };
861        self.control(&serde_json::json!({ "subtype": "get_context_usage", "detail": detail })).await
862    }
863
864    /// Withdraw a prompt: drop it from the queue if it has not started,
865    /// else interrupt its turn. Another prompt's turn is never interrupted.
866    /// Source: binary `cancel_async_message` and interrupt
867    /// (`for_user_message_uuids`) schemas
868    pub async fn cancel_prompt(&self, uuid: &str) -> Result<()> {
869        let dropped = self
870            .control(&serde_json::json!({ "subtype": "cancel_async_message", "message_uuid": uuid }))
871            .await?;
872        if dropped.get("cancelled").and_then(serde_json::Value::as_bool) == Some(true) {
873            // No `result` will come for it.
874            decrement(&self.0.turns_in_flight);
875            return Ok(());
876        }
877        self.control(&serde_json::json!({ "subtype": "interrupt", "for_user_message_uuids": [uuid] }))
878            .await
879            .map(|_| ())
880    }
881
882    /// Set the session's display title. Source: binary `rename_session` schema
883    pub async fn rename_session(&self, title: &str) -> Result<()> {
884        self.control(&serde_json::json!({ "subtype": "rename_session", "title": title })).await.map(|_| ())
885    }
886
887    /// Restore files Claude changed to their state at `user_message_id`
888    /// (the `uuid` of a prompt). `dry_run` reports without changing files.
889    /// Source: binary `rewind_files` schema
890    pub async fn rewind_files(&self, user_message_id: &str, dry_run: bool) -> Result<serde_json::Value> {
891        self.control(&serde_json::json!({
892            "subtype": "rewind_files", "user_message_id": user_message_id, "dry_run": dry_run,
893        }))
894        .await
895    }
896
897    /// Connection status of every MCP server. Source: binary `mcp_status` schema
898    pub async fn mcp_status(&self) -> Result<serde_json::Value> {
899        self.control(&serde_json::json!({ "subtype": "mcp_status" })).await
900    }
901
902    /// Enable or disable an MCP server. Source: binary `mcp_toggle` schema
903    pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()> {
904        self.control(&serde_json::json!({ "subtype": "mcp_toggle", "serverName": server, "enabled": enabled }))
905            .await
906            .map(|_| ())
907    }
908
909    /// Reconnect a failed or disconnected MCP server. Source: binary `mcp_reconnect` schema
910    pub async fn mcp_reconnect(&self, server: &str) -> Result<()> {
911        self.control(&serde_json::json!({ "subtype": "mcp_reconnect", "serverName": server })).await.map(|_| ())
912    }
913
914    /// Replace the MCP servers added at runtime: in-process `sdk` servers
915    /// plus `external` configs (stdio/http/sse, keyed by name). Servers from
916    /// `SessionOptions` and settings stay. Their tools are not pre-allowed:
917    /// they go through the permission mode and `can_use_tool`.
918    /// Source: binary `mcp_set_servers` schema
919    pub async fn set_mcp_servers(
920        &self,
921        sdk: Vec<SdkMcpServer>,
922        external: serde_json::Map<String, serde_json::Value>,
923    ) -> Result<serde_json::Value> {
924        let servers = server_map(&sdk, Some(&external));
925        *self.0.responder.dynamic_mcp_servers.write().unwrap_or_else(std::sync::PoisonError::into_inner) = sdk;
926        self.control(&serde_json::json!({ "subtype": "mcp_set_servers", "servers": servers })).await
927    }
928
929    /// Models the session can switch to. Source: binary `list_models` schema
930    pub async fn list_models(&self) -> Result<serde_json::Value> {
931        self.control(&serde_json::json!({ "subtype": "list_models" })).await
932    }
933
934    /// Effective merged settings plus each source's raw settings.
935    /// Source: binary `get_settings` schema
936    pub async fn get_settings(&self) -> Result<serde_json::Value> {
937        self.control(&serde_json::json!({ "subtype": "get_settings" })).await
938    }
939
940    /// Write settings through the CLI's own writer. `local` = the project's
941    /// local settings (allowlist: `outputStyle`); otherwise the user's
942    /// settings (`effortLevel` only). Source: binary `update_settings` schema
943    pub async fn update_settings(&self, local: bool, settings: serde_json::Value) -> Result<serde_json::Value> {
944        let source = if local { "localSettings" } else { "userSettings" };
945        self.control(&serde_json::json!({ "subtype": "update_settings", "source": source, "settings": settings }))
946            .await
947    }
948
949    /// Session cost and usage, plus plan rate-limit use when available.
950    /// `skip_behaviors` skips the scan of local transcripts (its section is
951    /// then null) — enough for a rate-limit meter. Experimental in the CLI.
952    /// Source: binary `get_usage` schema
953    pub async fn get_usage(&self, skip_behaviors: bool) -> Result<serde_json::Value> {
954        self.control(&serde_json::json!({ "subtype": "get_usage", "skip_behaviors": skip_behaviors })).await
955    }
956
957    /// Re-read skills from disk. Source: binary `reload_skills` schema
958    pub async fn reload_skills(&self) -> Result<serde_json::Value> {
959        self.control(&serde_json::json!({ "subtype": "reload_skills" })).await
960    }
961
962    /// Re-read plugins from disk. Source: binary `reload_plugins` schema
963    pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<serde_json::Value> {
964        let mut body = serde_json::json!({
965            "subtype": "reload_plugins",
966            "hold_on_cache_impact": opts.hold_on_cache_impact,
967            "refuse_if_busy": opts.refuse_if_busy,
968        });
969        if !opts.add_plugins.is_empty() {
970            body["add_plugins"] = serde_json::json!(opts.add_plugins);
971        }
972        self.control(&body).await
973    }
974
975    /// The last output (≤ 8 KiB) of a background shell or Monitor task.
976    /// Source: binary `get_task_output` schema
977    pub async fn task_output(&self, task_id: &str) -> Result<serde_json::Value> {
978        self.control(&serde_json::json!({ "subtype": "get_task_output", "task_id": task_id })).await
979    }
980
981    /// Add a working-directory root (a subdirectory of `cwd` or of an
982    /// `add_dirs` entry) and reload CLAUDE.md, skills and plugins for it.
983    /// Source: binary `register_repo_root` schema
984    pub async fn register_repo_root(&self, directory: &str) -> Result<serde_json::Value> {
985        self.control(&serde_json::json!({
986            "subtype": "register_repo_root", "directory": directory,
987            "reload_claude_md": true, "reload_plugins": true, "reload_skills": true,
988        }))
989        .await
990    }
991
992    /// Call a tool of an external MCP server directly, without a model turn
993    /// and without a permission check. `tool` is fully qualified
994    /// (`mcp__server__tool`). In-process servers are refused: call their
995    /// Rust functions directly. Source: binary `mcp_call` schema
996    pub async fn mcp_call(&self, tool: &str, arguments: serde_json::Value, opts: McpCall) -> Result<serde_json::Value> {
997        let mut body = serde_json::json!({ "subtype": "mcp_call", "tool": tool, "arguments": arguments });
998        if let Some(t) = opts.timeout {
999            body["timeout_ms"] = serde_json::json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
1000        }
1001        if opts.result_not_for_model {
1002            body["result_not_for_model"] = true.into();
1003        }
1004        if opts.check_permissions {
1005            body["check_permissions"] = true.into();
1006        }
1007        self.control(&body).await
1008    }
1009
1010    /// Read a `ui://` resource from a connected external MCP server.
1011    /// Source: binary `mcp_read_resource` schema
1012    pub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<serde_json::Value> {
1013        self.control(&serde_json::json!({ "subtype": "mcp_read_resource", "serverName": server, "uri": uri }))
1014            .await
1015    }
1016
1017    /// Read a file through the CLI, under the session's read permissions
1018    /// (`path` relative to `cwd`). `base64` for binary files such as images;
1019    /// otherwise lossy UTF-8. Source: binary `read_file` schema
1020    pub async fn read_file(&self, path: &str, max_bytes: Option<u64>, base64: bool) -> Result<serde_json::Value> {
1021        let mut body = serde_json::json!({
1022            "subtype": "read_file", "path": path,
1023            "encoding": if base64 { "base64" } else { "utf-8" },
1024        });
1025        if let Some(n) = max_bytes {
1026            body["max_bytes"] = n.into();
1027        }
1028        self.control(&body).await
1029    }
1030
1031    /// @-mention file suggestions for a partial path, as the terminal shows.
1032    /// Source: binary `file_suggestions` schema
1033    pub async fn file_suggestions(&self, query: &str) -> Result<serde_json::Value> {
1034        self.control(&serde_json::json!({ "subtype": "file_suggestions", "query": query })).await
1035    }
1036
1037    /// Every hook (settings, session, plugin) grouped by event and matcher.
1038    /// Source: binary `get_hooks_listing` schema
1039    pub async fn hooks_listing(&self) -> Result<serde_json::Value> {
1040        self.control(&serde_json::json!({ "subtype": "get_hooks_listing" })).await
1041    }
1042
1043    /// The live permission rules and workspace directories.
1044    /// Source: binary `list_permission_rules` schema
1045    pub async fn permission_rules(&self) -> Result<serde_json::Value> {
1046        self.control(&serde_json::json!({ "subtype": "list_permission_rules" })).await
1047    }
1048
1049    /// The formatted session cost summary (`/usage` text).
1050    /// Source: binary `get_session_cost` schema
1051    pub async fn session_cost(&self) -> Result<serde_json::Value> {
1052        self.control(&serde_json::json!({ "subtype": "get_session_cost" })).await
1053    }
1054
1055    /// Re-read output styles from disk. Source: binary `reload_output_styles` schema
1056    pub async fn reload_output_styles(&self) -> Result<serde_json::Value> {
1057        self.control(&serde_json::json!({ "subtype": "reload_output_styles" })).await
1058    }
1059
1060    /// Tell the CLI the file at `path` was read at `mtime_ms`, so Edit works
1061    /// on it after the Read left the context. Source: binary `seed_read_state` schema
1062    pub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()> {
1063        self.control(&serde_json::json!({ "subtype": "seed_read_state", "path": path, "mtime": mtime_ms }))
1064            .await
1065            .map(|_| ())
1066    }
1067
1068    /// A handle that does not keep the session alive; see `WeakSession`.
1069    #[must_use]
1070    pub fn downgrade(&self) -> WeakSession {
1071        WeakSession(Arc::downgrade(&self.0))
1072    }
1073
1074    /// Process id of the CLI (`None` for a replay).
1075    #[must_use]
1076    pub fn pid(&self) -> Option<u32> {
1077        self.0.pgid.and_then(|p| u32::try_from(p).ok())
1078    }
1079
1080    /// The CLI's version, read when the session started.
1081    pub fn cli_version(&self) -> Option<&str> {
1082        self.0.cli_version.get().map(String::as_str)
1083    }
1084
1085    /// Receive every frame the CLI emits from now on. Lossless: a slow
1086    /// receiver buffers instead of dropping frames, so memory grows until
1087    /// it catches up. Poll the receiver, or drop it once done.
1088    #[must_use = "frames buffer until the receiver is dropped"]
1089    pub fn subscribe(&self) -> EventRx {
1090        let (tx, rx) = mpsc::unbounded_channel();
1091        let mut fanout = lock(&self.0.fanout);
1092        if !fanout.ended {
1093            fanout.subs.push(tx);
1094        }
1095        rx
1096    }
1097
1098    /// Current session id — known once the CLI emits its first `system`
1099    /// frame; changes after `/clear`.
1100    pub fn session_id(&self) -> Option<String> {
1101        self.0.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
1102    }
1103
1104    /// Payload of the initialize `control_response` (commands, models, account, …).
1105    #[must_use]
1106    pub fn initialize_response(&self) -> Option<&serde_json::Value> {
1107        self.0.initialize_response.get()
1108    }
1109
1110    /// Whether the session streams partial messages
1111    /// (`SessionOptions::include_partial`).
1112    #[must_use]
1113    pub fn include_partial(&self) -> bool {
1114        self.0.include_partial
1115    }
1116
1117    /// Whether a prompt sent with `Agent` is still waiting for its `result`.
1118    #[must_use]
1119    pub fn is_busy(&self) -> bool {
1120        self.0.turns_in_flight.load(Ordering::Acquire) > 0
1121    }
1122
1123    /// Send a prompt and count it as in flight until its `result`. Counted
1124    /// before the write, so a fast `result` cannot arrive first.
1125    pub(crate) async fn send_prompt(&self, message: &crate::protocol::UserMessage) -> Result<()> {
1126        self.0.turns_in_flight.fetch_add(1, Ordering::AcqRel);
1127        let sent = self.send(message).await;
1128        if sent.is_err() {
1129            decrement(&self.0.turns_in_flight);
1130        }
1131        sent
1132    }
1133
1134    /// Whether the subprocess is still running.
1135    #[must_use]
1136    pub fn is_alive(&self) -> bool {
1137        self.0.state.load(Ordering::Acquire) == STATE_RUNNING
1138    }
1139
1140    /// End the session: close stdin and give the CLI 5 s to exit, then
1141    /// SIGTERM, then SIGKILL its process group. Tools it started (background
1142    /// Bash commands keep the CLI alive past stdin EOF) end with it.
1143    /// Returns the CLI's exit code (`None` when it ended by a signal).
1144    pub async fn close(&self) -> Option<i32> {
1145        let _ = self.0.state.compare_exchange(STATE_RUNNING, STATE_CLOSING, Ordering::SeqCst, Ordering::SeqCst);
1146        self.0.stdin_tx.lock().await.take();
1147        let mut exit = self.wait_exit(CLOSE_GRACE).await;
1148        #[cfg(unix)]
1149        for signal in [nix::sys::signal::Signal::SIGTERM, nix::sys::signal::Signal::SIGKILL] {
1150            if exit.is_some() {
1151                break;
1152            }
1153            self.signal_group(signal);
1154            exit = self.wait_exit(CLOSE_GRACE).await;
1155        }
1156        // Children the CLI left running share its process group.
1157        #[cfg(unix)]
1158        self.signal_group(nix::sys::signal::Signal::SIGTERM);
1159        #[cfg(not(unix))]
1160        if exit.is_none() {
1161            kill_tree(self.0.pgid);
1162            exit = self.wait_exit(CLOSE_GRACE).await;
1163        }
1164        // Let the reader finish the last lines (and the recording).
1165        let mut done = self.0.reader_done.clone();
1166        let _ = tokio::time::timeout(CLOSE_GRACE, done.wait_for(|d| *d)).await;
1167        exit.and_then(|e| e.code)
1168    }
1169
1170    async fn wait_exit(&self, timeout: Duration) -> Option<ExitInfo> {
1171        let mut rx = self.0.exit.clone();
1172        let waited = tokio::time::timeout(timeout, async {
1173            rx.wait_for(Option::is_some).await.ok().and_then(|info| info.clone())
1174        })
1175        .await;
1176        waited.ok().flatten()
1177    }
1178
1179    #[cfg(unix)]
1180    fn signal_group(&self, signal: nix::sys::signal::Signal) {
1181        if let Some(pgid) = self.0.pgid {
1182            let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), signal);
1183        }
1184    }
1185
1186    // ── internals ────────────────────────────────────────────────────────────
1187
1188    async fn request_with_timeout<B: serde::Serialize>(
1189        &self,
1190        body: &B,
1191        timeout: Duration,
1192    ) -> Result<serde_json::Value> {
1193        let n = self.0.next_request_id.fetch_add(1, Ordering::Relaxed);
1194        let request_id = format!("req_{n}_{}", std::process::id());
1195        let subtype = serde_json::to_value(body)?
1196            .get("subtype")
1197            .and_then(|s| s.as_str())
1198            .unwrap_or("?")
1199            .to_string();
1200
1201        // Register before writing so a fast response cannot arrive unmatched.
1202        let (tx, rx) = oneshot::channel();
1203        self.0.pending.insert(request_id.clone(), tx);
1204        // Unregisters on every exit, including the caller dropping this future.
1205        let _registered = PendingGuard { pending: &self.0.pending, request_id: &request_id };
1206        // The reader marks `ended` before it drops all waiters; a request
1207        // registered after that would never be answered.
1208        if lock(&self.0.fanout).ended {
1209            return Err(self.dead_error().await);
1210        }
1211        let envelope = OutboundControlRequest { kind: "control_request", request_id: &request_id, request: body };
1212        self.send(&envelope).await?;
1213
1214        let reply = match tokio::time::timeout(timeout, rx).await {
1215            Ok(Ok(reply)) => reply,
1216            // Sender dropped: the reader hit EOF because the process exited.
1217            Ok(Err(_)) => return Err(self.dead_error().await),
1218            Err(_) => return Err(SessionError::ControlTimeout(subtype)),
1219        };
1220        match reply.subtype.as_str() {
1221            "success" => Ok(reply.response.unwrap_or(serde_json::Value::Null)),
1222            _ => Err(SessionError::ControlError {
1223                subtype,
1224                error: reply.error.unwrap_or_else(|| "unknown error".into()),
1225            }),
1226        }
1227    }
1228
1229    /// Error describing why the process is gone, with its stderr tail.
1230    async fn dead_error(&self) -> SessionError {
1231        if self.0.state.load(Ordering::Acquire) == STATE_CLOSING {
1232            return SessionError::Closed;
1233        }
1234        // The watchdog records the exit right after stdout/stderr close.
1235        match self.wait_exit(Duration::from_secs(1)).await {
1236            Some(ExitInfo { code, stderr }) => SessionError::ProcessExited { code, stderr },
1237            None => SessionError::Closed,
1238        }
1239    }
1240}
1241
1242/// Removes a control request's `pending` entry when dropped.
1243struct PendingGuard<'a> {
1244    pending: &'a Pending,
1245    request_id: &'a str,
1246}
1247
1248impl Drop for PendingGuard<'_> {
1249    fn drop(&mut self) {
1250        self.pending.remove(self.request_id);
1251    }
1252}
1253
1254impl Drop for SessionInner {
1255    /// Dropping the last handle ends the CLI and the tools it started:
1256    /// SIGTERM now, SIGKILL if the CLI is still running after `CLOSE_GRACE`.
1257    /// Without a Tokio runtime there is no escalation; `close().await` is
1258    /// the complete shutdown.
1259    fn drop(&mut self) {
1260        #[cfg(unix)]
1261        if let Some(pgid) = self.pgid
1262            && self.state.load(Ordering::Acquire) != STATE_DEAD
1263        {
1264            use nix::sys::signal::{killpg, Signal};
1265            let group = nix::unistd::Pid::from_raw(pgid);
1266            let _ = killpg(group, Signal::SIGTERM);
1267            if let Ok(runtime) = tokio::runtime::Handle::try_current() {
1268                let mut exit = self.exit.clone();
1269                runtime.spawn(async move {
1270                    let exited = tokio::time::timeout(CLOSE_GRACE, exit.wait_for(Option::is_some)).await;
1271                    if !matches!(exited, Ok(Ok(_))) {
1272                        let _ = killpg(group, Signal::SIGKILL);
1273                    }
1274                });
1275            }
1276        }
1277        #[cfg(not(unix))]
1278        if self.state.load(Ordering::Acquire) != STATE_DEAD {
1279            kill_tree(self.pgid);
1280        }
1281    }
1282}
1283
1284/// Feed every stderr line to `on_stderr` and keep the last ones in `tail`.
1285/// A panicking callback is logged, not fatal: the drain must keep running.
1286async fn drain_stderr(
1287    stderr: tokio::process::ChildStderr,
1288    on_stderr: Option<OnStderr>,
1289    tail: Arc<std::sync::Mutex<VecDeque<String>>>,
1290) {
1291    let mut lines = BufReader::new(stderr).lines();
1292    while let Ok(Some(line)) = lines.next_line().await {
1293        if let Some(cb) = &on_stderr
1294            && std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (cb.0)(&line))).is_err()
1295        {
1296            tracing::warn!("on_stderr callback panicked");
1297        }
1298        let mut tail = lock(&tail);
1299        if tail.len() == STDERR_TAIL_LINES {
1300            tail.pop_front();
1301        }
1302        tail.push_back(line);
1303    }
1304}
1305
1306/// End the CLI and every process it started (Windows has no process groups).
1307#[cfg(not(unix))]
1308fn kill_tree(pid: Option<i32>) {
1309    if let Some(pid) = pid {
1310        let _ = std::process::Command::new("taskkill")
1311            .args(["/PID", &pid.to_string(), "/T", "/F"])
1312            .stdout(Stdio::null())
1313            .stderr(Stdio::null())
1314            .status();
1315    }
1316}
1317
1318/// Every CLI flag `opts` asks for, besides the fixed stream-json ones.
1319fn cli_args(opts: &SessionOptions) -> Vec<String> {
1320    let mut args: Vec<String> = vec![];
1321    let mut flag = |name: &str, value: Option<String>| {
1322        if let Some(v) = value {
1323            args.push(name.into());
1324            args.push(v);
1325        }
1326    };
1327    flag("--model", opts.model.clone());
1328    flag("--effort", opts.effort.map(|e| e.as_str().into()));
1329    flag("--permission-mode", opts.permission_mode.map(|m| m.as_str().into()));
1330    flag("--fallback-model", opts.fallback_model.clone());
1331    flag("--thinking", opts.thinking.map(|t| t.as_str().into()));
1332    flag("--thinking-display", opts.thinking_display.map(|d| d.as_str().into()));
1333    flag("--max-thinking-tokens", opts.max_thinking_tokens.map(|n| n.to_string()));
1334    flag("--max-turns", opts.max_turns.map(|n| n.to_string()));
1335    flag("--max-budget-usd", opts.max_budget_usd.map(|n| n.to_string()));
1336    flag("--task-budget", opts.task_budget.map(|n| n.to_string()));
1337    flag("--resume", opts.resume.clone());
1338    flag("--resume-session-at", opts.resume_session_at.clone());
1339    flag("--session-id", opts.session_id.clone());
1340    flag("--name", opts.name.clone());
1341    flag("--tools", opts.tools.as_ref().map(|t| t.join(",")));
1342    flag("--agent", opts.agent.clone());
1343    flag("--append-subagent-system-prompt", opts.append_subagent_system_prompt.clone());
1344    flag("--betas", (!opts.betas.is_empty()).then(|| opts.betas.join(",")));
1345    flag("--debug-file", opts.debug_file.as_ref().map(|p| p.display().to_string()));
1346    flag("--setting-sources", opts.setting_sources.as_ref().map(|s| s.join(",")));
1347    flag("--permission-prompt-tool", opts.can_use_tool.as_ref().map(|_| "stdio".into()));
1348    flag(
1349        "--mcp-config",
1350        (!opts.mcp_servers.is_empty())
1351            .then(|| serde_json::json!({ "mcpServers": server_map(&opts.mcp_servers, None) }).to_string()),
1352    );
1353    for dir in &opts.add_dirs {
1354        flag("--add-dir", Some(dir.display().to_string()));
1355    }
1356    for dir in &opts.plugin_dirs {
1357        flag("--plugin-dir", Some(dir.display().to_string()));
1358    }
1359    for url in &opts.plugin_urls {
1360        flag("--plugin-url", Some(url.clone()));
1361    }
1362    for spec in &opts.files {
1363        flag("--file", Some(spec.clone()));
1364    }
1365    flag("--autocompact", opts.autocompact.map(super::protocol::Autocompact::to_arg));
1366    flag("--permission-prompts", opts.permission_prompts.map(|p| p.as_str().into()));
1367    if let Some(Some(name)) = &opts.worktree {
1368        flag("--worktree", Some(name.clone()));
1369    }
1370    if let Some(None) = opts.worktree {
1371        args.push("--worktree".into());
1372    }
1373    for (on, name) in [
1374        (opts.bare, "--bare"),
1375        (opts.safe_mode, "--safe-mode"),
1376        (opts.restricted, "--restricted"),
1377        (opts.disable_slash_commands, "--disable-slash-commands"),
1378        (opts.brief, "--brief"),
1379        (opts.include_hook_events, "--include-hook-events"),
1380    ] {
1381        if on {
1382            args.push(name.into());
1383        }
1384    }
1385    if opts.continue_conversation {
1386        args.push("--continue".into());
1387    }
1388    if opts.fork_session {
1389        args.push("--fork-session".into());
1390    }
1391    if !opts.persist_session {
1392        args.push("--no-session-persistence".into());
1393    }
1394    if opts.strict_mcp_config {
1395        args.push("--strict-mcp-config".into());
1396    }
1397    args
1398}
1399
1400/// `a < b` for dotted versions; a non-numeric suffix ("2.1.329-beta") is ignored.
1401fn version_lt(a: &str, b: &str) -> bool {
1402    let parse = |v: &str| -> Vec<u64> {
1403        v.split(['.', '-', ' '])
1404            .map_while(|part| part.parse().ok())
1405            .collect()
1406    };
1407    parse(a) < parse(b)
1408}
1409
1410/// Decrement, stopping at zero.
1411fn decrement(n: &AtomicUsize) {
1412    let mut current = n.load(Ordering::Acquire);
1413    while current > 0 {
1414        match n.compare_exchange_weak(current, current - 1, Ordering::AcqRel, Ordering::Acquire) {
1415            Ok(_) => break,
1416            Err(actual) => current = actual,
1417        }
1418    }
1419}
1420
1421/// The file `SessionOptions::record` names, created (truncated) for writing.
1422pub(crate) async fn open_record(opts: &SessionOptions) -> Result<Option<tokio::fs::File>> {
1423    match &opts.record {
1424        Some(path) => Ok(Some(tokio::fs::File::create(path).await?)),
1425        None => Ok(None),
1426    }
1427}
1428
1429/// Settings file contents; a relative path is resolved against `cwd`, as
1430/// the CLI started in `cwd` would.
1431async fn read_settings_file(path: &str, cwd: Option<&std::path::Path>) -> Result<serde_json::Value> {
1432    let path = match cwd {
1433        Some(dir) => dir.join(path),
1434        None => PathBuf::from(path),
1435    };
1436    Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
1437}
1438
1439/// `--settings` value: the caller's settings, plus the Code Mode env var,
1440/// which the CLI honours only when it comes from settings, not the shell.
1441fn settings_arg(settings: Option<serde_json::Value>, code_mode: bool) -> Result<Option<serde_json::Value>> {
1442    if !code_mode {
1443        return Ok(settings);
1444    }
1445    let mut settings = settings.unwrap_or_else(|| serde_json::json!({}));
1446    let env = settings
1447        .as_object_mut()
1448        .map(|obj| obj.entry("env").or_insert_with(|| serde_json::json!({})))
1449        .and_then(serde_json::Value::as_object_mut)
1450        .ok_or(crate::code_mode::CodeModeError::Settings)?;
1451    env.insert("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE".into(), "1".into());
1452    Ok(Some(settings))
1453}
1454
1455fn with_subtype(mut body: serde_json::Value, subtype: &str) -> serde_json::Value {
1456    if let Some(obj) = body.as_object_mut() {
1457        obj.insert("subtype".into(), subtype.into());
1458    }
1459    body
1460}
1461
1462/// State the reader task shares with the Session.
1463struct Reader {
1464    record: Option<tokio::fs::File>,
1465    fanout: Arc<std::sync::Mutex<Fanout>>,
1466    session_id: Arc<RwLock<Option<String>>>,
1467    pending: Arc<Pending>,
1468    turns_in_flight: Arc<AtomicUsize>,
1469    responder: Arc<Responder>,
1470    done: watch::Sender<bool>,
1471}
1472
1473async fn read_loop(stdout: Box<dyn AsyncRead + Unpin + Send>, reader: Reader) {
1474    let Reader { record, fanout, session_id, pending, turns_in_flight, responder, done } = reader;
1475    // Runs on EOF and on a panic alike, so streams and waiters never hang.
1476    let cleanup = ReaderCleanup {
1477        fanout: fanout.clone(),
1478        pending,
1479        turns_in_flight: turns_in_flight.clone(),
1480        responder: responder.clone(),
1481        done,
1482    };
1483    let mut record = record.map(BufWriter::new);
1484    let mut lines = BufReader::new(stdout).lines();
1485    while let Ok(Some(line)) = lines.next_line().await {
1486        if line.trim().is_empty() {
1487            continue;
1488        }
1489        if let Some(file) = record.as_mut() {
1490            // Flush once a burst is drained, not per line: a slow disk must
1491            // not hold up stdout, and the file stays current while idle.
1492            let flush = lines.get_ref().buffer().is_empty();
1493            if file.write_all(line.as_bytes()).await.is_err()
1494                || file.write_all(b"\n").await.is_err()
1495                || (flush && file.flush().await.is_err())
1496            {
1497                tracing::warn!("recording failed; continuing without it");
1498                record = None;
1499            }
1500        }
1501        match parse_frame(&line) {
1502            InboundMessage::ControlResponse(r) => {
1503                if let Some((_, tx)) = cleanup.pending.remove(&r.response.request_id) {
1504                    let _ = tx.send(r.response);
1505                }
1506            }
1507            InboundMessage::ControlRequest(req) => {
1508                // Answer without blocking the reader: hooks may run long.
1509                // The handler runs in its own task, so a panic in user code
1510                // still sends an error response instead of leaving the CLI
1511                // waiting. Its abort handle is registered before the next
1512                // line is read, so a `control_cancel_request` always finds it.
1513                let request_id = req.request_id.clone();
1514                let handler = responder.clone();
1515                let task = tokio::spawn(async move { handler.respond(req).await });
1516                responder.in_flight.insert(request_id.clone(), task.abort_handle());
1517                let responder = responder.clone();
1518                tokio::spawn(async move {
1519                    let outcome = task.await;
1520                    responder.in_flight.remove(&request_id);
1521                    let response = match outcome {
1522                        Ok(response) => response,
1523                        // Withdrawn by the CLI, or the CLI is gone: no answer.
1524                        Err(e) if e.is_cancelled() => return,
1525                        Err(e) => ControlResponse::error(&request_id, format!("handler failed: {e}")),
1526                    };
1527                    responder.write(&response).await;
1528                });
1529            }
1530            InboundMessage::ControlCancelRequest(cancel) => {
1531                if let Some((_, task)) = responder.in_flight.remove(&cancel.request_id) {
1532                    task.abort();
1533                }
1534            }
1535            other => {
1536                if let InboundMessage::Result(ref r) = other
1537                    && r.origin.is_none()
1538                {
1539                    decrement(&turns_in_flight);
1540                }
1541                if let InboundMessage::System(ref s) = other {
1542                    let mut id = session_id.write().unwrap_or_else(std::sync::PoisonError::into_inner);
1543                    if id.as_deref() != Some(s.session_id.as_str()) {
1544                        *id = Some(s.session_id.clone());
1545                    }
1546                }
1547                let msg = Arc::new(other);
1548                lock(&fanout).subs.retain(|tx| tx.send(msg.clone()).is_ok());
1549            }
1550        }
1551    }
1552    if let Some(mut file) = record
1553        && file.flush().await.is_err()
1554    {
1555        tracing::warn!("recording failed to flush");
1556    }
1557}
1558
1559/// End-of-stdout teardown of the reader, run from `Drop`.
1560struct ReaderCleanup {
1561    fanout: Arc<std::sync::Mutex<Fanout>>,
1562    pending: Arc<Pending>,
1563    turns_in_flight: Arc<AtomicUsize>,
1564    responder: Arc<Responder>,
1565    done: watch::Sender<bool>,
1566}
1567
1568impl Drop for ReaderCleanup {
1569    fn drop(&mut self) {
1570        {
1571            let mut f = lock(&self.fanout);
1572            f.ended = true;
1573            f.subs.clear();
1574        }
1575        self.pending.clear();
1576        self.turns_in_flight.store(0, Ordering::Release);
1577        // Handlers still waiting (a permission prompt, an elicitation) have
1578        // no CLI left to answer.
1579        self.responder.in_flight.retain(|_, task| {
1580            task.abort();
1581            false
1582        });
1583        let _ = self.done.send(true);
1584    }
1585}
1586
1587/// Decode one stdout line. A `result` the typed model cannot decode still
1588/// ends its turn, as a minimal result, so no stream waits forever; any other
1589/// undecodable JSON frame becomes `Other`.
1590fn parse_frame(line: &str) -> InboundMessage {
1591    match serde_json::from_str(line) {
1592        // A frame type this SDK does not model: keep it verbatim.
1593        Ok(InboundMessage::Unknown) => match serde_json::from_str(line) {
1594            Ok(value) => InboundMessage::Other(value),
1595            Err(_) => InboundMessage::Unknown,
1596        },
1597        Ok(m) => m,
1598        Err(e) => {
1599            let value: Option<serde_json::Value> = serde_json::from_str(line).ok();
1600            let field = |k: &str| value.as_ref().and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(str::to_owned);
1601            if field("type").as_deref() == Some("result") {
1602                tracing::warn!(error = %e, "undecodable result frame; ending the turn with it");
1603                InboundMessage::Result(ResultMessage {
1604                    subtype: field("subtype").unwrap_or_else(|| "error_unparsed_result".into()),
1605                    is_error: value.as_ref().and_then(|v| v.get("is_error")).and_then(serde_json::Value::as_bool).unwrap_or(false),
1606                    result: field("result"),
1607                    session_id: field("session_id"),
1608                    origin: value.as_ref().and_then(|v| v.get("origin")).cloned(),
1609                    ..ResultMessage::default()
1610                })
1611            } else if let (Some("control_request"), Some(request_id)) = (field("type").as_deref(), value.as_ref().and_then(|v| v.get("request_id")).and_then(|v| v.as_str())) {
1612                // The CLI waits for an answer; an error reply beats a hang.
1613                tracing::warn!(error = %e, "undecodable control_request; answering with an error");
1614                InboundMessage::ControlRequest(ControlRequest {
1615                    request_id: request_id.to_owned(),
1616                    request: ControlRequestBody::Unsupported,
1617                })
1618            } else if let Some(value) = value {
1619                // A known type in a shape this SDK cannot decode: hand it on
1620                // verbatim rather than losing it.
1621                tracing::warn!(error = %e, "undecodable frame; passing it on as Other");
1622                InboundMessage::Other(value)
1623            } else {
1624                tracing::debug!(error = %e, line = %line, "non-JSON stdout line");
1625                InboundMessage::Unknown
1626            }
1627        }
1628    }
1629}
1630
1631impl Responder {
1632    async fn respond(&self, req: ControlRequest) -> ControlResponse {
1633        match req.request {
1634            ControlRequestBody::HookCallback(hcb) => {
1635                let span = tracing::info_span!(
1636                    "claude.hook",
1637                    callback_id = %hcb.callback_id,
1638                    event = ?hcb.input.hook_event_name,
1639                    tool = hcb.input.tool_name.as_deref().unwrap_or(""),
1640                    blocked = tracing::field::Empty,
1641                );
1642                let output = self.hooks.dispatch(&hcb.callback_id, hcb.input).instrument(span.clone()).await;
1643                if let Some(ref o) = output {
1644                    span.record("blocked", o.is_block());
1645                }
1646                match output {
1647                    Some(output) => match serde_json::to_value(output) {
1648                        Ok(v) => ControlResponse::success(&req.request_id, v),
1649                        Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1650                    },
1651                    None => ControlResponse::error(
1652                        &req.request_id,
1653                        format!("no hook callback registered for id {}", hcb.callback_id),
1654                    ),
1655                }
1656            }
1657            ControlRequestBody::CanUseTool(cut) => match &self.can_use_tool {
1658                Some(handler) => {
1659                    let original = cut.input.clone();
1660                    let decision = match (handler.0)(cut).await {
1661                        // The CLI expects updatedInput on allow; echo the original.
1662                        ToolDecision::Allow { updated_input, updated_permissions } => ToolDecision::Allow {
1663                            updated_input: Some(updated_input.unwrap_or(original)),
1664                            updated_permissions,
1665                        },
1666                        deny @ ToolDecision::Deny { .. } => deny,
1667                    };
1668                    match serde_json::to_value(decision) {
1669                        Ok(v) => ControlResponse::success(&req.request_id, v),
1670                        Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1671                    }
1672                }
1673                None => ControlResponse::error(&req.request_id, "no can_use_tool handler"),
1674            },
1675            ControlRequestBody::McpMessage(m) => {
1676                let span = tracing::info_span!(
1677                    "claude.tool",
1678                    server = %m.server_name,
1679                    method = m.message.get("method").and_then(|v| v.as_str()).unwrap_or(""),
1680                    tool = m.message.pointer("/params/name").and_then(|v| v.as_str()).unwrap_or(""),
1681                );
1682                let server = self.mcp_servers.iter().find(|s| s.name == m.server_name).cloned().or_else(|| {
1683                    let dynamic = self.dynamic_mcp_servers.read().unwrap_or_else(std::sync::PoisonError::into_inner);
1684                    dynamic.iter().find(|s| s.name == m.server_name).cloned()
1685                });
1686                let reply = match server {
1687                    Some(server) => server.handle(&m.message).instrument(span).await,
1688                    None => serde_json::json!({
1689                        "jsonrpc": "2.0",
1690                        "id": m.message.get("id"),
1691                        "error": { "code": -32601, "message": format!("Server '{}' not found", m.server_name) },
1692                    }),
1693                };
1694                ControlResponse::success(&req.request_id, serde_json::json!({ "mcp_response": reply }))
1695            }
1696            ControlRequestBody::Elicitation(e) => match &self.on_elicitation {
1697                Some(handler) => match serde_json::to_value((handler.0)(e).await) {
1698                    Ok(v) => ControlResponse::success(&req.request_id, v),
1699                    Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1700                },
1701                None => ControlResponse::error(&req.request_id, "no on_elicitation handler"),
1702            },
1703            ControlRequestBody::RequestUserDialog(d) => match &self.on_user_dialog {
1704                Some(handler) => match serde_json::to_value((handler.0)(d).await) {
1705                    Ok(v) => ControlResponse::success(&req.request_id, v),
1706                    Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1707                },
1708                None => ControlResponse::error(&req.request_id, "no on_user_dialog handler"),
1709            },
1710            ControlRequestBody::Unsupported => {
1711                ControlResponse::error(&req.request_id, "unsupported control request subtype")
1712            }
1713        }
1714    }
1715
1716    async fn write(&self, response: &ControlResponse) {
1717        match serde_json::to_vec(response) {
1718            Ok(bytes) => if let Some(tx) = self.stdin_tx.upgrade() {
1719                let _ = tx.send(bytes).await;
1720            } else { tracing::debug!("session closed; dropping control response") },
1721            Err(e) => tracing::warn!(error = %e, "failed to serialize control response"),
1722        }
1723    }
1724}