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