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, AtomicUsize, Ordering};
20use std::sync::{Arc, OnceLock, RwLock};
21use std::time::Duration;
22
23use dashmap::DashMap;
24use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
25use tokio::process::Command;
26use tokio::sync::{mpsc, oneshot, watch, Mutex};
27use tokio::task::JoinHandle;
28use tracing::Instrument;
29
30use crate::hooks::HookRegistry;
31use crate::mcp::{server_map, SdkMcpServer};
32use crate::protocol::{
33    Autocompact, CanUseToolRequest, ControlRequest, ControlRequestBody, ControlResponse, Effort,
34    ElicitationRequest, ElicitationResponse, InboundControlResponseBody, InboundMessage, Initialize,
35    OutboundControlRequest, PermissionMode, PermissionPrompts, ResultMessage, Thinking, ThinkingDisplay,
36    ToolDecision,
37    UserDialogRequest, UserDialogResponse,
38};
39
40// ─── Errors ──────────────────────────────────────────────────────────────────
41
42/// Error of a session operation.
43#[derive(Debug, thiserror::Error)]
44#[non_exhaustive]
45pub enum SessionError {
46    /// An I/O error, e.g. spawning the CLI or opening a recording file.
47    #[error("io: {0}")]
48    Io(#[from] std::io::Error),
49    /// A frame could not be serialized or parsed.
50    #[error("json: {0}")]
51    Json(#[from] serde_json::Error),
52    /// The CLI process exited.
53    #[error("process exited (code: {code:?}); stderr tail:\n{stderr}")]
54    ProcessExited {
55        /// Exit code; `None` when killed by a signal.
56        code: Option<i32>,
57        /// Last lines the CLI wrote to stderr.
58        stderr: String,
59    },
60    /// The session was closed, or stdin is gone.
61    #[error("session closed")]
62    Closed,
63    /// The CLI answered a control request with an error.
64    #[error("control request `{subtype}` failed: {error}")]
65    ControlError {
66        /// The request's `subtype`.
67        subtype: String,
68        /// The CLI's error message.
69        error: String,
70    },
71    /// No answer to the control request (named by its `subtype`) in time
72    /// (`SessionOptions::control_timeout` for requests after initialize).
73    #[error("control request `{0}` timed out")]
74    ControlTimeout(String),
75    /// Building the Code Mode binary failed.
76    #[error("code mode: {0}")]
77    CodeMode(#[from] crate::code_mode::CodeModeError),
78    /// The CLI is older than `MIN_CLI_VERSION`.
79    #[error("Claude Code {found} is older than {min}, the oldest version this SDK supports; run `claude update`")]
80    UnsupportedCliVersion {
81        /// Version the CLI reported.
82        found: String,
83        /// `MIN_CLI_VERSION`.
84        min: &'static str,
85    },
86    /// A recording passed to `replay` that cannot be replayed.
87    #[error("invalid recording: {0}")]
88    InvalidRecording(String),
89}
90
91/// `Result` with `SessionError`.
92pub type Result<T> = std::result::Result<T, SessionError>;
93
94const STATE_RUNNING: u8 = 0;
95const STATE_CLOSING: u8 = 1;
96const STATE_DEAD: u8 = 2;
97
98const STDERR_TAIL_LINES: usize = 40;
99/// After the CLI exits, how long stderr may still deliver its last lines.
100const STDERR_LINGER: Duration = Duration::from_millis(500);
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}
467
468/// A live Claude Code session. Cheap to clone — backed by `Arc<SessionInner>`.
469///
470/// Handlers in `SessionOptions` (`can_use_tool`, hooks, …) are owned by the
471/// session; one that needs the session should capture `Session::downgrade()`,
472/// since a captured `Session` keeps it, and the CLI, alive forever.
473#[derive(Clone)]
474pub struct Session(Arc<SessionInner>);
475
476/// A `Session` handle that does not keep the session alive.
477#[derive(Clone)]
478pub struct WeakSession(std::sync::Weak<SessionInner>);
479
480impl WeakSession {
481    /// The session, unless every `Session` handle is gone.
482    pub fn upgrade(&self) -> Option<Session> {
483        self.0.upgrade().map(Session)
484    }
485}
486
487impl fmt::Debug for WeakSession {
488    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489        f.write_str("WeakSession(..)")
490    }
491}
492
493struct SessionInner {
494    /// Current session id; every `system` frame carries it and `/clear`
495    /// starts a new one.
496    session_id: Arc<RwLock<Option<String>>>,
497    /// `None` after `close()`; dropping the last sender ends the writer task,
498    /// which closes the CLI's stdin.
499    stdin_tx: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
500    fanout: Arc<std::sync::Mutex<Fanout>>,
501    /// Host-initiated control requests awaiting a `control_response`.
502    pending: Arc<Pending>,
503    next_request_id: AtomicU64,
504    state: Arc<AtomicU8>,
505    exit: watch::Receiver<Option<ExitInfo>>,
506    pgid: Option<i32>,
507    include_partial: bool,
508    initialize_response: OnceLock<serde_json::Value>,
509    cli_version: OnceLock<String>,
510    control_timeout: Duration,
511    responder: Arc<Responder>,
512    /// Prompts sent whose `result` has not arrived yet.
513    turns_in_flight: Arc<AtomicUsize>,
514    /// `true` once the reader has handled the last stdout line.
515    reader_done: watch::Receiver<bool>,
516    /// `close()` has ended the CLI and what it started; `Drop` skips it.
517    group_ended: AtomicBool,
518    _tasks: [JoinHandle<()>; 3],
519}
520
521/// What the reader task needs to answer CLI control requests.
522struct Responder {
523    /// Weak: only the Session keeps stdin open, so dropping or closing the
524    /// Session ends the CLI even while the reader task is still running.
525    stdin_tx: mpsc::WeakSender<Vec<u8>>,
526    hooks: HookRegistry,
527    can_use_tool: Option<CanUseTool>,
528    on_elicitation: Option<OnElicitation>,
529    on_user_dialog: Option<OnUserDialog>,
530    /// Servers from `SessionOptions::mcp_servers`.
531    mcp_servers: Vec<SdkMcpServer>,
532    /// Servers set later with `Session::set_mcp_servers`.
533    dynamic_mcp_servers: RwLock<Vec<SdkMcpServer>>,
534    /// Running handlers of CLI control requests, by request id, so a
535    /// `control_cancel_request` can stop them.
536    in_flight: DashMap<String, tokio::task::AbortHandle>,
537    /// The session's id, for `ToolContext::session_id`.
538    session_id: Arc<RwLock<Option<String>>>,
539}
540
541impl Session {
542    /// Spawn a Claude Code subprocess and complete the initialize handshake.
543    ///
544    ///   1. spawn `claude --output-format stream-json --verbose
545    ///      --input-format stream-json --await-initialize …`
546    ///   2. write the `initialize` control request (with `opts.hooks`)
547    ///   3. wait for its `control_response`
548    pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self> {
549        let binary = if opts.code_mode {
550            // Patching an old CLI fails on its anchors; name the real cause.
551            check_binary_version(&opts.binary).await?;
552            crate::code_mode::patched_binary(&opts.binary).await?
553        } else {
554            opts.binary.clone()
555        };
556        let mut cmd = Command::new(&binary);
557        // First, so the variables set below survive it.
558        if opts.clear_env {
559            cmd.env_clear();
560        }
561        cmd.args([
562            "--output-format", "stream-json",
563            "--verbose",
564            "--input-format", "stream-json",
565            "--await-initialize",
566            // Echo each prompt when its turn starts: Agent uses it as the
567            // turn boundary. Source: `claude --help`
568            "--replay-user-messages",
569        ]);
570        if opts.include_partial {
571            cmd.arg("--include-partial-messages");
572        }
573        if let Some(ref m) = opts.model {
574            cmd.args(["--model", m]);
575        }
576        cmd.args(cli_args(&opts));
577        let allowed: Vec<String> = opts.allowed_tools.iter().cloned()
578            .chain(opts.mcp_servers.iter().flat_map(SdkMcpServer::qualified_tool_names))
579            .collect();
580        if !allowed.is_empty() {
581            cmd.args(["--allowedTools", &allowed.join(",")]);
582        }
583        if !opts.disallowed_tools.is_empty() {
584            cmd.args(["--disallowedTools", &opts.disallowed_tools.join(",")]);
585        }
586        let settings = match (&opts.settings, opts.code_mode) {
587            // The Code Mode env var must be merged into the settings object.
588            (Some(serde_json::Value::String(path)), true) => {
589                Some(read_settings_file(path, opts.cwd.as_deref()).await?)
590            }
591            (settings, _) => settings.clone(),
592        };
593        match settings_arg(settings, opts.code_mode)? {
594            // A string is a settings file path; anything else is inline JSON.
595            Some(serde_json::Value::String(path)) => {
596                cmd.args(["--settings", &path]);
597            }
598            Some(settings) => {
599                cmd.args(["--settings", &settings.to_string()]);
600            }
601            None => {}
602        }
603        cmd.args(&opts.extra_args);
604        if let Some(ref cwd) = opts.cwd {
605            cmd.current_dir(cwd);
606        }
607        // An SDK entrypoint, also when the host itself runs under Claude
608        // Desktop or VS Code, whose values the CLI would otherwise inherit
609        // and act on. `opts.env` may override it.
610        cmd.env("CLAUDE_CODE_ENTRYPOINT", "sdk-cli");
611        if opts.code_mode {
612            cmd.env("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE", "1");
613        }
614        if opts.tool_search {
615            cmd.env("ENABLE_TOOL_SEARCH", "1");
616        }
617        for (k, v) in &opts.env {
618            cmd.env(k, v);
619        }
620        cmd.stdin(Stdio::piped())
621            .stdout(Stdio::piped())
622            .stderr(Stdio::piped())
623            .kill_on_drop(false); // close() / Drop end the whole process group instead
624        // Own process group: tools the CLI starts (Bash, background tasks)
625        // join it, so close() and Drop can end them too.
626        #[cfg(unix)]
627        cmd.process_group(0);
628
629        // Before spawning, so a bad path leaves no process behind.
630        let record = open_record(&opts).await?;
631        let mut child = cmd.spawn()?;
632        let pgid = child.id().and_then(|id| i32::try_from(id).ok());
633        let (Some(stdin), Some(stdout), Some(stderr)) =
634            (child.stdin.take(), child.stdout.take(), child.stderr.take())
635        else {
636            return Err(SessionError::Io(std::io::Error::other("subprocess pipes missing")));
637        };
638        let tail = Arc::new(std::sync::Mutex::new(VecDeque::with_capacity(STDERR_TAIL_LINES)));
639        let mut drain = tokio::spawn(drain_stderr(stderr, opts.on_stderr.clone(), tail.clone()));
640        // Exit is the child's, not stderr's EOF: a tool the CLI started can
641        // inherit stderr and hold it open after the CLI is gone.
642        let exit = Box::pin(async move { child.wait().await.ok().and_then(|s| s.code()) });
643        let stderr_tail = Box::pin(async move {
644            if tokio::time::timeout(STDERR_LINGER, &mut drain).await.is_err() {
645                drain.abort();
646            }
647            Vec::from(std::mem::take(&mut *lock(&tail))).join("\n")
648        });
649        let transport =
650            Transport { stdin: Box::new(stdin), stdout: Box::new(stdout), exit, stderr_tail, pgid };
651        Self::connect(transport, opts, init, record).await
652    }
653
654    /// Run the session over an already-started CLI (process or replay) and
655    /// complete the initialize handshake.
656    pub(crate) async fn connect(
657        transport: Transport,
658        opts: SessionOptions,
659        mut init: Initialize,
660        record: Option<tokio::fs::File>,
661    ) -> Result<Self> {
662        let Transport { stdin, stdout, exit: exit_fut, stderr_tail, pgid } = transport;
663        let (stdin_tx, mut stdin_rx) = mpsc::channel::<Vec<u8>>(256);
664        let fanout = Arc::new(std::sync::Mutex::new(Fanout::default()));
665        let session_id = Arc::new(RwLock::new(None));
666        let pending: Arc<Pending> = Arc::new(DashMap::new());
667        let state = Arc::new(AtomicU8::new(STATE_RUNNING));
668        let (exit_tx, exit_rx) = watch::channel(None);
669        let (reader_done_tx, reader_done) = watch::channel(false);
670        let turns_in_flight = Arc::new(AtomicUsize::new(0));
671
672        let writer = tokio::spawn(async move {
673            let mut w = BufWriter::new(stdin);
674            while let Some(bytes) = stdin_rx.recv().await {
675                if w.write_all(&bytes).await.is_err()
676                    || w.write_all(b"\n").await.is_err()
677                    || w.flush().await.is_err()
678                {
679                    break;
680                }
681            }
682            let _ = w.shutdown().await;
683        });
684
685        let state2 = state.clone();
686        let watchdog = tokio::spawn(async move {
687            let code = exit_fut.await;
688            state2.store(STATE_DEAD, Ordering::SeqCst);
689            let stderr = stderr_tail.await;
690            let _ = exit_tx.send(Some(ExitInfo { code, stderr }));
691        });
692
693        let responder = Arc::new(Responder {
694            stdin_tx: stdin_tx.downgrade(),
695            hooks: opts.hooks.clone(),
696            can_use_tool: opts.can_use_tool.clone(),
697            on_elicitation: opts.on_elicitation.clone(),
698            on_user_dialog: opts.on_user_dialog.clone(),
699            mcp_servers: opts.mcp_servers.iter().map(SdkMcpServer::for_session).collect(),
700            dynamic_mcp_servers: RwLock::new(vec![]),
701            in_flight: DashMap::new(),
702            session_id: session_id.clone(),
703        });
704        let reader = tokio::spawn(read_loop(stdout, Reader {
705            record,
706            exit: exit_rx.clone(),
707            fanout: fanout.clone(),
708            session_id: session_id.clone(),
709            pending: pending.clone(),
710            turns_in_flight: turns_in_flight.clone(),
711            responder: responder.clone(),
712            done: reader_done_tx,
713        }));
714
715        let session = Session(Arc::new(SessionInner {
716            session_id,
717            stdin_tx: Mutex::new(Some(stdin_tx)),
718            fanout,
719            pending,
720            next_request_id: AtomicU64::new(0),
721            state,
722            exit: exit_rx,
723            pgid,
724            include_partial: opts.include_partial,
725            initialize_response: OnceLock::new(),
726            cli_version: OnceLock::new(),
727            control_timeout: opts.control_timeout,
728            responder,
729            turns_in_flight,
730            reader_done,
731            group_ended: AtomicBool::new(false),
732            _tasks: [reader, writer, watchdog],
733        }));
734
735        init.hooks = opts.hooks.initialize_config();
736        let body = serde_json::to_value(&init)?;
737        let body = with_subtype(body, "initialize");
738        let response = session.request_with_timeout(&body, INITIALIZE_TIMEOUT).await?;
739        let _ = session.0.initialize_response.set(response);
740        session.check_cli_version().await?;
741        Ok(session)
742    }
743
744    /// Ask the CLI its version and refuse one older than `MIN_CLI_VERSION`.
745    /// A CLI that cannot answer is let through with a warning.
746    async fn check_cli_version(&self) -> Result<()> {
747        let reply = self.control(&serde_json::json!({ "subtype": "get_binary_version" })).await;
748        let version = match reply {
749            Ok(v) => v.get("version").and_then(|v| v.as_str()).map(str::to_owned),
750            Err(e) => {
751                tracing::warn!(error = %e, "could not read the Claude Code version");
752                None
753            }
754        };
755        let Some(version) = version else { return Ok(()) };
756        if version_lt(&version, MIN_CLI_VERSION) {
757            self.close().await;
758            return Err(SessionError::UnsupportedCliVersion { found: version, min: MIN_CLI_VERSION });
759        }
760        let _ = self.0.cli_version.set(version);
761        Ok(())
762    }
763
764    /// Spawn with `--resume <previous_id>`; the CLI reloads its own transcript.
765    pub async fn reconnect(previous_id: &str, mut opts: SessionOptions, init: Initialize) -> Result<Self> {
766        opts.resume = Some(previous_id.to_string());
767        Self::spawn(opts, init).await
768    }
769
770    /// Send a raw JSON line to the subprocess stdin.
771    pub async fn send<T: serde::Serialize>(&self, msg: &T) -> Result<()> {
772        if self.0.state.load(Ordering::Acquire) != STATE_RUNNING {
773            return Err(self.dead_error().await);
774        }
775        let bytes = serde_json::to_vec(msg)?;
776        let tx = self.0.stdin_tx.lock().await.clone().ok_or(SessionError::Closed)?;
777        tx.send(bytes).await.map_err(|_| SessionError::Closed)
778    }
779
780    /// Send a host → CLI control request and wait for its response payload.
781    /// `body` must serialize to an object with a `subtype` field.
782    pub async fn control<B: serde::Serialize>(&self, body: &B) -> Result<serde_json::Value> {
783        self.request_with_timeout(body, self.0.control_timeout).await
784    }
785
786    /// Interrupt the running turn; its stream ends with an
787    /// `AgentEvent::Error` of kind `TurnErrorKind::Execution`. Queued prompts
788    /// still run.
789    pub async fn interrupt(&self) -> Result<()> {
790        self.control(&serde_json::json!({ "subtype": "interrupt" })).await.map(|_| ())
791    }
792
793    /// Interrupt the running turn and cancel every queued prompt.
794    /// Source: binary interrupt schema (`cancel_queued`)
795    pub async fn interrupt_all(&self) -> Result<()> {
796        // In its own task: the count fix-up must run even if the caller
797        // drops this future after the CLI cancelled the prompts.
798        let session = self.clone();
799        detached(async move {
800            let reply = session.control(&serde_json::json!({ "subtype": "interrupt", "cancel_queued": true })).await?;
801            // Cancelled prompts get no `result`.
802            let cancelled = reply.get("cancelled").and_then(|c| c.as_array()).map_or(0, Vec::len);
803            for _ in 0..cancelled {
804                decrement(&session.0.turns_in_flight);
805            }
806            Ok(())
807        })
808        .await
809    }
810
811    /// Switch model for the following turns. `None` clears the override, so
812    /// the CLI falls back to its default model (not to `SessionOptions::model`).
813    /// Source: binary `set_model` schema
814    pub async fn set_model(&self, model: Option<&str>) -> Result<()> {
815        self.control(&serde_json::json!({ "subtype": "set_model", "model": model })).await.map(|_| ())
816    }
817
818    /// Switch model and replace the custom system prompt. The new prompt is
819    /// sent from the next compaction on (from the next turn with
820    /// `Initialize::system_prompt_snapshot: Some(false)`).
821    /// Source: binary `set_model` schema (`system_prompt`)
822    pub async fn set_model_and_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
823        self.control(&serde_json::json!({
824            "subtype": "set_model", "model": model, "system_prompt": system_prompt,
825        }))
826        .await
827        .map(|_| ())
828    }
829
830    /// Replace the custom system prompt without switching model. `model`
831    /// must name the session's current model, or the CLI refuses. CLI
832    /// 2.1.329 can confirm the model only while the session runs the
833    /// account's default model (no `SessionOptions::model`, no `set_model`);
834    /// otherwise use `set_model_and_system_prompt`. The new prompt is sent
835    /// from the next compaction on.
836    /// Source: binary `set_model` schema (`only_if_model_is_current`)
837    pub async fn set_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
838        self.control(&serde_json::json!({
839            "subtype": "set_model", "model": model, "system_prompt": system_prompt,
840            "only_if_model_is_current": true,
841        }))
842        .await
843        .map(|_| ())
844    }
845
846    /// Thinking-token budget for the following turns (older models);
847    /// `None` restores the session's setting.
848    /// Source: binary `set_max_thinking_tokens` schema
849    pub async fn set_max_thinking_tokens(&self, tokens: Option<u32>, display: Option<ThinkingDisplay>) -> Result<()> {
850        let mut body = serde_json::json!({ "subtype": "set_max_thinking_tokens", "max_thinking_tokens": tokens });
851        if let Some(d) = display {
852            body["thinking_display"] = d.as_str().into();
853        }
854        self.control(&body).await.map(|_| ())
855    }
856
857    /// Switch effort level for the following turns; `None` clears the
858    /// override, so the CLI falls back to its default level (not to
859    /// `SessionOptions::effort`).
860    /// Source: binary `apply_flag_settings` handler (`effortLevel`)
861    pub async fn set_effort(&self, effort: Option<Effort>) -> Result<()> {
862        let settings = serde_json::json!({ "effortLevel": effort });
863        self.control(&serde_json::json!({ "subtype": "apply_flag_settings", "settings": settings }))
864            .await
865            .map(|_| ())
866    }
867
868    /// Source: binary `set_permission_mode` schema
869    pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()> {
870        self.control(&serde_json::json!({ "subtype": "set_permission_mode", "mode": mode })).await.map(|_| ())
871    }
872
873    /// Stop a background task by its `task_id` (see `AgentEvent::BackgroundTasks`).
874    /// Source: binary `stop_task` schema
875    pub async fn stop_task(&self, task_id: &str) -> Result<()> {
876        self.control(&serde_json::json!({ "subtype": "stop_task", "task_id": task_id })).await.map(|_| ())
877    }
878
879    /// Context-window usage of the session, as reported by the CLI.
880    /// `exact: true` counts each category with the token-count API; `false`
881    /// estimates from the last response's usage, without those calls.
882    /// Source: binary `get_context_usage` schema
883    pub async fn context_usage(&self, exact: bool) -> Result<serde_json::Value> {
884        let detail = if exact { "full" } else { "summary" };
885        self.control(&serde_json::json!({ "subtype": "get_context_usage", "detail": detail })).await
886    }
887
888    /// Withdraw a prompt: drop it from the queue if it has not started,
889    /// else interrupt its turn. Another prompt's turn is never interrupted.
890    /// Source: binary `cancel_async_message` and interrupt
891    /// (`for_user_message_uuids`) schemas
892    pub async fn cancel_prompt(&self, uuid: &str) -> Result<()> {
893        // In its own task, as in `interrupt_all`.
894        let session = self.clone();
895        let message_uuid = uuid.to_owned();
896        let dropped = detached(async move {
897            let reply = session
898                .control(&serde_json::json!({ "subtype": "cancel_async_message", "message_uuid": message_uuid }))
899                .await?;
900            let dropped = reply.get("cancelled").and_then(serde_json::Value::as_bool) == Some(true);
901            if dropped {
902                // No `result` will come for it.
903                decrement(&session.0.turns_in_flight);
904            }
905            Ok(dropped)
906        })
907        .await?;
908        if dropped {
909            return Ok(());
910        }
911        self.control(&serde_json::json!({ "subtype": "interrupt", "for_user_message_uuids": [uuid] }))
912            .await
913            .map(|_| ())
914    }
915
916    /// Set the session's display title. Source: binary `rename_session` schema
917    pub async fn rename_session(&self, title: &str) -> Result<()> {
918        self.control(&serde_json::json!({ "subtype": "rename_session", "title": title })).await.map(|_| ())
919    }
920
921    /// Restore files Claude changed to their state at `user_message_id`
922    /// (the `uuid` of a prompt). `dry_run` reports without changing files.
923    /// Source: binary `rewind_files` schema
924    pub async fn rewind_files(&self, user_message_id: &str, dry_run: bool) -> Result<serde_json::Value> {
925        self.control(&serde_json::json!({
926            "subtype": "rewind_files", "user_message_id": user_message_id, "dry_run": dry_run,
927        }))
928        .await
929    }
930
931    /// Connection status of every MCP server. Source: binary `mcp_status` schema
932    pub async fn mcp_status(&self) -> Result<serde_json::Value> {
933        self.control(&serde_json::json!({ "subtype": "mcp_status" })).await
934    }
935
936    /// Enable or disable an MCP server. Source: binary `mcp_toggle` schema
937    pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()> {
938        self.control(&serde_json::json!({ "subtype": "mcp_toggle", "serverName": server, "enabled": enabled }))
939            .await
940            .map(|_| ())
941    }
942
943    /// Reconnect a failed or disconnected MCP server. Source: binary `mcp_reconnect` schema
944    pub async fn mcp_reconnect(&self, server: &str) -> Result<()> {
945        self.control(&serde_json::json!({ "subtype": "mcp_reconnect", "serverName": server })).await.map(|_| ())
946    }
947
948    /// Replace the MCP servers added at runtime: in-process `sdk` servers
949    /// plus `external` configs (stdio/http/sse, keyed by name). Servers from
950    /// `SessionOptions` and settings stay. Their tools are not pre-allowed:
951    /// they go through the permission mode and `can_use_tool`.
952    /// Source: binary `mcp_set_servers` schema
953    pub async fn set_mcp_servers(
954        &self,
955        sdk: Vec<SdkMcpServer>,
956        external: serde_json::Map<String, serde_json::Value>,
957    ) -> Result<serde_json::Value> {
958        let servers = server_map(&sdk, Some(&external));
959        *self.0.responder.dynamic_mcp_servers.write().unwrap_or_else(std::sync::PoisonError::into_inner) =
960            sdk.iter().map(SdkMcpServer::for_session).collect();
961        self.control(&serde_json::json!({ "subtype": "mcp_set_servers", "servers": servers })).await
962    }
963
964    /// Models the session can switch to. Source: binary `list_models` schema
965    pub async fn list_models(&self) -> Result<serde_json::Value> {
966        self.control(&serde_json::json!({ "subtype": "list_models" })).await
967    }
968
969    /// Effective merged settings plus each source's raw settings.
970    /// Source: binary `get_settings` schema
971    pub async fn get_settings(&self) -> Result<serde_json::Value> {
972        self.control(&serde_json::json!({ "subtype": "get_settings" })).await
973    }
974
975    /// Write settings through the CLI's own writer. `local` = the project's
976    /// local settings (allowlist: `outputStyle`); otherwise the user's
977    /// settings (`effortLevel` only). Source: binary `update_settings` schema
978    pub async fn update_settings(&self, local: bool, settings: serde_json::Value) -> Result<serde_json::Value> {
979        let source = if local { "localSettings" } else { "userSettings" };
980        self.control(&serde_json::json!({ "subtype": "update_settings", "source": source, "settings": settings }))
981            .await
982    }
983
984    /// Session cost and usage, plus plan rate-limit use when available.
985    /// `skip_behaviors` skips the scan of local transcripts (its section is
986    /// then null) — enough for a rate-limit meter. Experimental in the CLI.
987    /// Source: binary `get_usage` schema
988    pub async fn get_usage(&self, skip_behaviors: bool) -> Result<serde_json::Value> {
989        self.control(&serde_json::json!({ "subtype": "get_usage", "skip_behaviors": skip_behaviors })).await
990    }
991
992    /// Re-read skills from disk. Source: binary `reload_skills` schema
993    pub async fn reload_skills(&self) -> Result<serde_json::Value> {
994        self.control(&serde_json::json!({ "subtype": "reload_skills" })).await
995    }
996
997    /// Re-read plugins from disk. Source: binary `reload_plugins` schema
998    pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<serde_json::Value> {
999        let mut body = serde_json::json!({
1000            "subtype": "reload_plugins",
1001            "hold_on_cache_impact": opts.hold_on_cache_impact,
1002            "refuse_if_busy": opts.refuse_if_busy,
1003        });
1004        if !opts.add_plugins.is_empty() {
1005            body["add_plugins"] = serde_json::json!(opts.add_plugins);
1006        }
1007        self.control(&body).await
1008    }
1009
1010    /// The last output (≤ 8 KiB) of a background shell or Monitor task.
1011    /// Source: binary `get_task_output` schema
1012    pub async fn task_output(&self, task_id: &str) -> Result<serde_json::Value> {
1013        self.control(&serde_json::json!({ "subtype": "get_task_output", "task_id": task_id })).await
1014    }
1015
1016    /// Add a working-directory root (a subdirectory of `cwd` or of an
1017    /// `add_dirs` entry) and reload CLAUDE.md, skills and plugins for it.
1018    /// Source: binary `register_repo_root` schema
1019    pub async fn register_repo_root(&self, directory: &str) -> Result<serde_json::Value> {
1020        self.control(&serde_json::json!({
1021            "subtype": "register_repo_root", "directory": directory,
1022            "reload_claude_md": true, "reload_plugins": true, "reload_skills": true,
1023        }))
1024        .await
1025    }
1026
1027    /// Call a tool of an external MCP server directly, without a model turn
1028    /// and without a permission check. `tool` is fully qualified
1029    /// (`mcp__server__tool`). In-process servers are refused: call their
1030    /// Rust functions directly. Source: binary `mcp_call` schema
1031    pub async fn mcp_call(&self, tool: &str, arguments: serde_json::Value, opts: McpCall) -> Result<serde_json::Value> {
1032        let mut body = serde_json::json!({ "subtype": "mcp_call", "tool": tool, "arguments": arguments });
1033        if let Some(t) = opts.timeout {
1034            body["timeout_ms"] = serde_json::json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
1035        }
1036        if opts.result_not_for_model {
1037            body["result_not_for_model"] = true.into();
1038        }
1039        if opts.check_permissions {
1040            body["check_permissions"] = true.into();
1041        }
1042        self.control(&body).await
1043    }
1044
1045    /// Read a `ui://` resource from a connected external MCP server.
1046    /// Source: binary `mcp_read_resource` schema
1047    pub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<serde_json::Value> {
1048        self.control(&serde_json::json!({ "subtype": "mcp_read_resource", "serverName": server, "uri": uri }))
1049            .await
1050    }
1051
1052    /// Read a file through the CLI, under the session's read permissions
1053    /// (`path` relative to `cwd`). `base64` for binary files such as images;
1054    /// otherwise lossy UTF-8. Source: binary `read_file` schema
1055    pub async fn read_file(&self, path: &str, max_bytes: Option<u64>, base64: bool) -> Result<serde_json::Value> {
1056        let mut body = serde_json::json!({
1057            "subtype": "read_file", "path": path,
1058            "encoding": if base64 { "base64" } else { "utf-8" },
1059        });
1060        if let Some(n) = max_bytes {
1061            body["max_bytes"] = n.into();
1062        }
1063        self.control(&body).await
1064    }
1065
1066    /// @-mention file suggestions for a partial path, as the terminal shows.
1067    /// Source: binary `file_suggestions` schema
1068    pub async fn file_suggestions(&self, query: &str) -> Result<serde_json::Value> {
1069        self.control(&serde_json::json!({ "subtype": "file_suggestions", "query": query })).await
1070    }
1071
1072    /// Every hook (settings, session, plugin) grouped by event and matcher.
1073    /// Source: binary `get_hooks_listing` schema
1074    pub async fn hooks_listing(&self) -> Result<serde_json::Value> {
1075        self.control(&serde_json::json!({ "subtype": "get_hooks_listing" })).await
1076    }
1077
1078    /// The live permission rules and workspace directories.
1079    /// Source: binary `list_permission_rules` schema
1080    pub async fn permission_rules(&self) -> Result<serde_json::Value> {
1081        self.control(&serde_json::json!({ "subtype": "list_permission_rules" })).await
1082    }
1083
1084    /// The formatted session cost summary (`/usage` text).
1085    /// Source: binary `get_session_cost` schema
1086    pub async fn session_cost(&self) -> Result<serde_json::Value> {
1087        self.control(&serde_json::json!({ "subtype": "get_session_cost" })).await
1088    }
1089
1090    /// Re-read output styles from disk. Source: binary `reload_output_styles` schema
1091    pub async fn reload_output_styles(&self) -> Result<serde_json::Value> {
1092        self.control(&serde_json::json!({ "subtype": "reload_output_styles" })).await
1093    }
1094
1095    /// Tell the CLI the file at `path` was read at `mtime_ms`, so Edit works
1096    /// on it after the Read left the context. Source: binary `seed_read_state` schema
1097    pub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()> {
1098        self.control(&serde_json::json!({ "subtype": "seed_read_state", "path": path, "mtime": mtime_ms }))
1099            .await
1100            .map(|_| ())
1101    }
1102
1103    /// A handle that does not keep the session alive; see `WeakSession`.
1104    #[must_use]
1105    pub fn downgrade(&self) -> WeakSession {
1106        WeakSession(Arc::downgrade(&self.0))
1107    }
1108
1109    /// Process id of the CLI (`None` for a replay).
1110    #[must_use]
1111    pub fn pid(&self) -> Option<u32> {
1112        self.0.pgid.and_then(|p| u32::try_from(p).ok())
1113    }
1114
1115    /// The CLI's version, read when the session started.
1116    pub fn cli_version(&self) -> Option<&str> {
1117        self.0.cli_version.get().map(String::as_str)
1118    }
1119
1120    /// Receive every frame the CLI emits from now on. Lossless: a slow
1121    /// receiver buffers instead of dropping frames, so memory grows until
1122    /// it catches up. Poll the receiver, or drop it once done.
1123    #[must_use = "frames buffer until the receiver is dropped"]
1124    pub fn subscribe(&self) -> EventRx {
1125        let (tx, rx) = mpsc::unbounded_channel();
1126        let mut fanout = lock(&self.0.fanout);
1127        if !fanout.ended {
1128            fanout.subs.push(tx);
1129        }
1130        rx
1131    }
1132
1133    /// Current session id — known once the CLI emits its first `system`
1134    /// frame; changes after `/clear`.
1135    pub fn session_id(&self) -> Option<String> {
1136        self.0.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
1137    }
1138
1139    /// Payload of the initialize `control_response` (commands, models, account, …).
1140    #[must_use]
1141    pub fn initialize_response(&self) -> Option<&serde_json::Value> {
1142        self.0.initialize_response.get()
1143    }
1144
1145    /// Whether the session streams partial messages
1146    /// (`SessionOptions::include_partial`).
1147    #[must_use]
1148    pub fn include_partial(&self) -> bool {
1149        self.0.include_partial
1150    }
1151
1152    /// Whether a prompt sent with `Agent` is still waiting for its `result`.
1153    #[must_use]
1154    pub fn is_busy(&self) -> bool {
1155        self.0.turns_in_flight.load(Ordering::Acquire) > 0
1156    }
1157
1158    /// Send a prompt and count it as in flight until its `result`. Counted
1159    /// before the write, so a fast `result` cannot arrive first.
1160    pub(crate) async fn send_prompt(&self, message: &crate::protocol::UserMessage) -> Result<()> {
1161        self.0.turns_in_flight.fetch_add(1, Ordering::AcqRel);
1162        // Uncounts on error and when the caller drops this future before
1163        // the prompt is queued (a dropped channel send sends nothing).
1164        let mut counted = UnsentTurn(Some(&self.0.turns_in_flight));
1165        self.send(message).await?;
1166        counted.0 = None;
1167        Ok(())
1168    }
1169
1170    /// Whether the subprocess is still running.
1171    #[must_use]
1172    pub fn is_alive(&self) -> bool {
1173        self.0.state.load(Ordering::Acquire) == STATE_RUNNING
1174    }
1175
1176    /// End the session: close stdin and give the CLI 5 s to exit, then
1177    /// SIGTERM, then SIGKILL its process group. Hooks and Bash tools still
1178    /// running (the CLI starts each in a process group of its own) end with
1179    /// it: SIGTERM, then SIGKILL after 2 s. A process a hook or tool detached
1180    /// that outlived it (`(cmd &)`, `nohup cmd &`) is out of reach.
1181    /// Returns the CLI's exit code (`None` when it ended by a signal).
1182    pub async fn close(&self) -> Option<i32> {
1183        #[cfg(unix)]
1184        let pgid = self.0.pgid;
1185        let _ = self.0.state.compare_exchange(STATE_RUNNING, STATE_CLOSING, Ordering::SeqCst, Ordering::SeqCst);
1186        // Before stdin closes: once the CLI exits, its tools lose the parent
1187        // link that finds them.
1188        #[cfg(unix)]
1189        let mut groups = blocking(move || tool_groups(pgid)).await;
1190        self.0.stdin_tx.lock().await.take();
1191        let mut exit = self.wait_exit(CLOSE_GRACE).await;
1192        #[cfg(unix)]
1193        for signal in [nix::sys::signal::Signal::SIGTERM, nix::sys::signal::Signal::SIGKILL] {
1194            if exit.is_some() {
1195                break;
1196            }
1197            for group in blocking(move || tool_groups(pgid)).await {
1198                if !groups.contains(&group) {
1199                    groups.push(group);
1200                }
1201            }
1202            self.signal_group(signal);
1203            exit = self.wait_exit(CLOSE_GRACE).await;
1204        }
1205        // The CLI's own group holds the children it left running (MCP
1206        // servers, background tasks).
1207        #[cfg(unix)]
1208        {
1209            groups.extend(pgid);
1210            blocking(move || end_groups(&groups)).await;
1211        }
1212        #[cfg(not(unix))]
1213        if exit.is_none() {
1214            kill_tree(self.0.pgid);
1215            exit = self.wait_exit(CLOSE_GRACE).await;
1216        }
1217        self.0.group_ended.store(true, Ordering::Release);
1218        // Let the reader finish the last lines (and the recording).
1219        let mut done = self.0.reader_done.clone();
1220        let _ = tokio::time::timeout(CLOSE_GRACE, done.wait_for(|d| *d)).await;
1221        exit.and_then(|e| e.code)
1222    }
1223
1224    async fn wait_exit(&self, timeout: Duration) -> Option<ExitInfo> {
1225        let mut rx = self.0.exit.clone();
1226        let waited = tokio::time::timeout(timeout, async {
1227            rx.wait_for(Option::is_some).await.ok().and_then(|info| info.clone())
1228        })
1229        .await;
1230        waited.ok().flatten()
1231    }
1232
1233    #[cfg(unix)]
1234    fn signal_group(&self, signal: nix::sys::signal::Signal) {
1235        if let Some(pgid) = self.0.pgid {
1236            let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), signal);
1237        }
1238    }
1239
1240    // ── internals ────────────────────────────────────────────────────────────
1241
1242    async fn request_with_timeout<B: serde::Serialize>(
1243        &self,
1244        body: &B,
1245        timeout: Duration,
1246    ) -> Result<serde_json::Value> {
1247        let n = self.0.next_request_id.fetch_add(1, Ordering::Relaxed);
1248        let request_id = format!("req_{n}_{}", std::process::id());
1249        let subtype = serde_json::to_value(body)?
1250            .get("subtype")
1251            .and_then(|s| s.as_str())
1252            .unwrap_or("?")
1253            .to_string();
1254
1255        // Register before writing so a fast response cannot arrive unmatched.
1256        let (tx, rx) = oneshot::channel();
1257        self.0.pending.insert(request_id.clone(), tx);
1258        // Unregisters on every exit, including the caller dropping this future.
1259        let _registered = PendingGuard { pending: &self.0.pending, request_id: &request_id };
1260        // The reader marks `ended` before it drops all waiters; a request
1261        // registered after that would never be answered.
1262        if lock(&self.0.fanout).ended {
1263            return Err(self.dead_error().await);
1264        }
1265        let envelope = OutboundControlRequest { kind: "control_request", request_id: &request_id, request: body };
1266        // The write counts against the timeout too: a hung CLI stops
1267        // reading stdin, and the pipe fills.
1268        let exchange = async {
1269            self.send(&envelope).await?;
1270            Ok::<_, SessionError>(rx.await)
1271        };
1272        let reply = match tokio::time::timeout(timeout, exchange).await {
1273            Ok(Ok(Ok(reply))) => reply,
1274            Ok(Err(e)) => return Err(e),
1275            // Sender dropped: the reader ended because the process exited.
1276            Ok(Ok(Err(_))) => return Err(self.dead_error().await),
1277            Err(_) => return Err(SessionError::ControlTimeout(subtype)),
1278        };
1279        match reply.subtype.as_str() {
1280            "success" => Ok(reply.response.unwrap_or(serde_json::Value::Null)),
1281            _ => Err(SessionError::ControlError {
1282                subtype,
1283                error: reply.error.unwrap_or_else(|| "unknown error".into()),
1284            }),
1285        }
1286    }
1287
1288    /// Error describing why the process is gone, with its stderr tail.
1289    async fn dead_error(&self) -> SessionError {
1290        if self.0.state.load(Ordering::Acquire) == STATE_CLOSING {
1291            return SessionError::Closed;
1292        }
1293        // The watchdog records the exit right after stdout/stderr close.
1294        match self.wait_exit(Duration::from_secs(1)).await {
1295            Some(ExitInfo { code, stderr }) => SessionError::ProcessExited { code, stderr },
1296            None => SessionError::Closed,
1297        }
1298    }
1299}
1300
1301/// Removes a control request's `pending` entry when dropped.
1302struct PendingGuard<'a> {
1303    pending: &'a Pending,
1304    request_id: &'a str,
1305}
1306
1307impl Drop for PendingGuard<'_> {
1308    fn drop(&mut self) {
1309        self.pending.remove(self.request_id);
1310    }
1311}
1312
1313impl Drop for SessionInner {
1314    /// Dropping the last handle ends the CLI and what it started, as
1315    /// `close()` does: SIGTERM now to the CLI's group and its tools'
1316    /// groups, then from a cleanup thread SIGKILL to whatever is left after
1317    /// the grace periods. The thread needs no Tokio runtime. The CLI's group
1318    /// is signalled even when the CLI already died, for the children it left
1319    /// (MCP servers).
1320    fn drop(&mut self) {
1321        #[cfg(unix)]
1322        if let Some(pgid) = self.pgid
1323            && !self.group_ended.load(Ordering::Acquire)
1324        {
1325            use nix::sys::signal::{killpg, Signal};
1326            let group = nix::unistd::Pid::from_raw(pgid);
1327            let running = self.state.load(Ordering::Acquire) != STATE_DEAD;
1328            // Read before signalling: a dead CLI's tools lose their parent link.
1329            let mut groups = if running { tool_groups(Some(pgid)) } else { vec![] };
1330            groups.push(pgid);
1331            for &g in &groups {
1332                let _ = killpg(nix::unistd::Pid::from_raw(g), Signal::SIGTERM);
1333            }
1334            let exit = self.exit.clone();
1335            let cleanup = move || {
1336                if running {
1337                    let deadline = std::time::Instant::now() + CLOSE_GRACE;
1338                    while exit.borrow().is_none()
1339                        && killpg(group, None).is_ok()
1340                        && std::time::Instant::now() < deadline
1341                    {
1342                        std::thread::sleep(Duration::from_millis(50));
1343                    }
1344                }
1345                end_groups(&groups);
1346            };
1347            if let Err(e) = std::thread::Builder::new().name("claude-session-cleanup".into()).spawn(cleanup) {
1348                tracing::warn!(error = %e, "could not start the session cleanup thread");
1349            }
1350        }
1351        #[cfg(not(unix))]
1352        if !self.group_ended.load(Ordering::Acquire) && self.state.load(Ordering::Acquire) != STATE_DEAD {
1353            kill_tree(self.pgid);
1354        }
1355    }
1356}
1357
1358/// Decrements the in-flight turn count when dropped while still holding it.
1359struct UnsentTurn<'a>(Option<&'a AtomicUsize>);
1360
1361impl Drop for UnsentTurn<'_> {
1362    fn drop(&mut self) {
1363        if let Some(n) = self.0 {
1364            decrement(n);
1365        }
1366    }
1367}
1368
1369/// Run `work` in its own task, so it completes even when the caller drops
1370/// the returned future.
1371async fn detached<T: Send + 'static>(work: impl Future<Output = Result<T>> + Send + 'static) -> Result<T> {
1372    tokio::spawn(work)
1373        .await
1374        .unwrap_or_else(|e| Err(SessionError::Io(std::io::Error::other(format!("control task failed: {e}")))))
1375}
1376
1377/// Run blocking `work` off the async threads.
1378#[cfg(unix)]
1379async fn blocking<T: Default + Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
1380    tokio::task::spawn_blocking(work).await.unwrap_or_default()
1381}
1382
1383/// Process groups of the hooks and tools the CLI `pgid` leads is running.
1384/// Blocking: reads the process table.
1385#[cfg(unix)]
1386fn tool_groups(pgid: Option<i32>) -> Vec<i32> {
1387    let Some(root) = pgid else { return vec![] };
1388    let host = nix::unistd::getpgrp().as_raw();
1389    crate::process_tree::descendant_groups(&crate::process_tree::snapshot(), root, host)
1390}
1391
1392/// SIGTERM every group, then SIGKILL the ones still there after
1393/// `GROUP_GRACE`. Blocking. A group id is not reused while any process
1394/// is in the group, so signalling a remembered id reaches either that
1395/// group or, once it is empty, nobody (barring a pid wrap-around to that
1396/// exact id within the grace period).
1397#[cfg(unix)]
1398fn end_groups(groups: &[i32]) {
1399    use nix::sys::signal::{killpg, Signal};
1400    let pid = nix::unistd::Pid::from_raw;
1401    for &group in groups {
1402        let _ = killpg(pid(group), Signal::SIGTERM);
1403    }
1404    let still_there = |groups: &[i32]| -> Vec<i32> {
1405        groups.iter().copied().filter(|&g| killpg(pid(g), None).is_ok()).collect()
1406    };
1407    let deadline = std::time::Instant::now() + GROUP_GRACE;
1408    let mut left = still_there(groups);
1409    while !left.is_empty() && std::time::Instant::now() < deadline {
1410        std::thread::sleep(Duration::from_millis(50));
1411        left = still_there(&left);
1412    }
1413    for group in left {
1414        let _ = killpg(pid(group), Signal::SIGKILL);
1415    }
1416}
1417
1418/// Refuse a CLI older than `MIN_CLI_VERSION` from its `--version` output.
1419/// A CLI that cannot answer is let through; the handshake checks again.
1420async fn check_binary_version(binary: &std::path::Path) -> Result<()> {
1421    let run = Command::new(binary).arg("--version").kill_on_drop(true).output();
1422    let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(30), run).await else {
1423        return Ok(());
1424    };
1425    // "2.1.329 (Claude Code)"
1426    let stdout = String::from_utf8_lossy(&out.stdout);
1427    let found = stdout.split_whitespace().next().unwrap_or_default().to_owned();
1428    if out.status.success() && !found.is_empty() && version_lt(&found, MIN_CLI_VERSION) {
1429        return Err(SessionError::UnsupportedCliVersion { found, min: MIN_CLI_VERSION });
1430    }
1431    Ok(())
1432}
1433
1434/// Feed every stderr line to `on_stderr` and keep the last ones in `tail`.
1435/// A panicking callback is logged, not fatal: the drain must keep running.
1436async fn drain_stderr(
1437    stderr: tokio::process::ChildStderr,
1438    on_stderr: Option<OnStderr>,
1439    tail: Arc<std::sync::Mutex<VecDeque<String>>>,
1440) {
1441    let mut lines = BufReader::new(stderr).lines();
1442    while let Ok(Some(line)) = lines.next_line().await {
1443        if let Some(cb) = &on_stderr
1444            && std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (cb.0)(&line))).is_err()
1445        {
1446            tracing::warn!("on_stderr callback panicked");
1447        }
1448        let mut tail = lock(&tail);
1449        if tail.len() == STDERR_TAIL_LINES {
1450            tail.pop_front();
1451        }
1452        tail.push_back(line);
1453    }
1454}
1455
1456/// End the CLI and every process it started (Windows has no process groups).
1457#[cfg(not(unix))]
1458fn kill_tree(pid: Option<i32>) {
1459    if let Some(pid) = pid {
1460        let _ = std::process::Command::new("taskkill")
1461            .args(["/PID", &pid.to_string(), "/T", "/F"])
1462            .stdout(Stdio::null())
1463            .stderr(Stdio::null())
1464            .status();
1465    }
1466}
1467
1468/// Every CLI flag `opts` asks for, besides the fixed stream-json ones.
1469fn cli_args(opts: &SessionOptions) -> Vec<String> {
1470    let mut args: Vec<String> = vec![];
1471    let mut flag = |name: &str, value: Option<String>| {
1472        if let Some(v) = value {
1473            args.push(name.into());
1474            args.push(v);
1475        }
1476    };
1477    flag("--model", opts.model.clone());
1478    flag("--effort", opts.effort.map(|e| e.as_str().into()));
1479    flag("--permission-mode", opts.permission_mode.map(|m| m.as_str().into()));
1480    flag("--fallback-model", opts.fallback_model.clone());
1481    flag("--thinking", opts.thinking.map(|t| t.as_str().into()));
1482    flag("--thinking-display", opts.thinking_display.map(|d| d.as_str().into()));
1483    flag("--max-thinking-tokens", opts.max_thinking_tokens.map(|n| n.to_string()));
1484    flag("--max-turns", opts.max_turns.map(|n| n.to_string()));
1485    flag("--max-budget-usd", opts.max_budget_usd.map(|n| n.to_string()));
1486    flag("--task-budget", opts.task_budget.map(|n| n.to_string()));
1487    flag("--resume", opts.resume.clone());
1488    flag("--resume-session-at", opts.resume_session_at.clone());
1489    flag("--session-id", opts.session_id.clone());
1490    flag("--name", opts.name.clone());
1491    flag("--tools", opts.tools.as_ref().map(|t| t.join(",")));
1492    flag("--agent", opts.agent.clone());
1493    flag("--append-subagent-system-prompt", opts.append_subagent_system_prompt.clone());
1494    flag("--betas", (!opts.betas.is_empty()).then(|| opts.betas.join(",")));
1495    flag("--debug-file", opts.debug_file.as_ref().map(|p| p.display().to_string()));
1496    flag("--setting-sources", opts.setting_sources.as_ref().map(|s| s.join(",")));
1497    flag("--permission-prompt-tool", opts.can_use_tool.as_ref().map(|_| "stdio".into()));
1498    flag(
1499        "--mcp-config",
1500        (!opts.mcp_servers.is_empty())
1501            .then(|| serde_json::json!({ "mcpServers": server_map(&opts.mcp_servers, None) }).to_string()),
1502    );
1503    for dir in &opts.add_dirs {
1504        flag("--add-dir", Some(dir.display().to_string()));
1505    }
1506    for dir in &opts.plugin_dirs {
1507        flag("--plugin-dir", Some(dir.display().to_string()));
1508    }
1509    for url in &opts.plugin_urls {
1510        flag("--plugin-url", Some(url.clone()));
1511    }
1512    for spec in &opts.files {
1513        flag("--file", Some(spec.clone()));
1514    }
1515    flag("--autocompact", opts.autocompact.map(super::protocol::Autocompact::to_arg));
1516    flag("--permission-prompts", opts.permission_prompts.map(|p| p.as_str().into()));
1517    if let Some(Some(name)) = &opts.worktree {
1518        flag("--worktree", Some(name.clone()));
1519    }
1520    if let Some(None) = opts.worktree {
1521        args.push("--worktree".into());
1522    }
1523    for (on, name) in [
1524        (opts.bare, "--bare"),
1525        (opts.safe_mode, "--safe-mode"),
1526        (opts.restricted, "--restricted"),
1527        (opts.disable_slash_commands, "--disable-slash-commands"),
1528        (opts.brief, "--brief"),
1529        (opts.include_hook_events, "--include-hook-events"),
1530    ] {
1531        if on {
1532            args.push(name.into());
1533        }
1534    }
1535    if opts.continue_conversation {
1536        args.push("--continue".into());
1537    }
1538    if opts.fork_session {
1539        args.push("--fork-session".into());
1540    }
1541    if !opts.persist_session {
1542        args.push("--no-session-persistence".into());
1543    }
1544    if opts.strict_mcp_config {
1545        args.push("--strict-mcp-config".into());
1546    }
1547    args
1548}
1549
1550/// `a < b` for dotted versions; a non-numeric suffix ("2.1.329-beta") is ignored.
1551fn version_lt(a: &str, b: &str) -> bool {
1552    let parse = |v: &str| -> Vec<u64> {
1553        v.split(['.', '-', ' '])
1554            .map_while(|part| part.parse().ok())
1555            .collect()
1556    };
1557    parse(a) < parse(b)
1558}
1559
1560/// Decrement, stopping at zero.
1561fn decrement(n: &AtomicUsize) {
1562    let mut current = n.load(Ordering::Acquire);
1563    while current > 0 {
1564        match n.compare_exchange_weak(current, current - 1, Ordering::AcqRel, Ordering::Acquire) {
1565            Ok(_) => break,
1566            Err(actual) => current = actual,
1567        }
1568    }
1569}
1570
1571/// The file `SessionOptions::record` names, created (truncated) for writing.
1572pub(crate) async fn open_record(opts: &SessionOptions) -> Result<Option<tokio::fs::File>> {
1573    match &opts.record {
1574        Some(path) => Ok(Some(tokio::fs::File::create(path).await?)),
1575        None => Ok(None),
1576    }
1577}
1578
1579/// Settings file contents; a relative path is resolved against `cwd`, as
1580/// the CLI started in `cwd` would.
1581async fn read_settings_file(path: &str, cwd: Option<&std::path::Path>) -> Result<serde_json::Value> {
1582    let path = match cwd {
1583        Some(dir) => dir.join(path),
1584        None => PathBuf::from(path),
1585    };
1586    Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
1587}
1588
1589/// `--settings` value: the caller's settings, plus the Code Mode env var,
1590/// which the CLI honours only when it comes from settings, not the shell.
1591fn settings_arg(settings: Option<serde_json::Value>, code_mode: bool) -> Result<Option<serde_json::Value>> {
1592    if !code_mode {
1593        return Ok(settings);
1594    }
1595    let mut settings = settings.unwrap_or_else(|| serde_json::json!({}));
1596    let env = settings
1597        .as_object_mut()
1598        .map(|obj| obj.entry("env").or_insert_with(|| serde_json::json!({})))
1599        .and_then(serde_json::Value::as_object_mut)
1600        .ok_or(crate::code_mode::CodeModeError::Settings)?;
1601    env.insert("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE".into(), "1".into());
1602    Ok(Some(settings))
1603}
1604
1605fn with_subtype(mut body: serde_json::Value, subtype: &str) -> serde_json::Value {
1606    if let Some(obj) = body.as_object_mut() {
1607        obj.insert("subtype".into(), subtype.into());
1608    }
1609    body
1610}
1611
1612/// State the reader task shares with the Session.
1613struct Reader {
1614    record: Option<tokio::fs::File>,
1615    /// The CLI's recorded exit, after which stdout is read only while data
1616    /// keeps coming.
1617    exit: watch::Receiver<Option<ExitInfo>>,
1618    fanout: Arc<std::sync::Mutex<Fanout>>,
1619    session_id: Arc<RwLock<Option<String>>>,
1620    pending: Arc<Pending>,
1621    turns_in_flight: Arc<AtomicUsize>,
1622    responder: Arc<Responder>,
1623    done: watch::Sender<bool>,
1624}
1625
1626async fn read_loop(stdout: Box<dyn AsyncRead + Unpin + Send>, reader: Reader) {
1627    let Reader { record, mut exit, fanout, session_id, pending, turns_in_flight, responder, done } = reader;
1628    // Runs on EOF and on a panic alike, so streams and waiters never hang.
1629    let cleanup = ReaderCleanup {
1630        fanout: fanout.clone(),
1631        pending,
1632        turns_in_flight: turns_in_flight.clone(),
1633        responder: responder.clone(),
1634        done,
1635    };
1636    let mut record = record.map(BufWriter::new);
1637    let mut lines = BufReader::new(stdout).lines();
1638    let mut exited = false;
1639    loop {
1640        // `next_line` is cancel safe: a partly read line stays buffered.
1641        let next = if exited {
1642            match tokio::time::timeout(STDOUT_LINGER, lines.next_line()).await {
1643                Ok(next) => next,
1644                Err(_) => {
1645                    tracing::debug!("CLI exited but stdout is held open; stopping the reader");
1646                    break;
1647                }
1648            }
1649        } else {
1650            tokio::select! {
1651                next = lines.next_line() => next,
1652                _ = exit.wait_for(Option::is_some) => {
1653                    exited = true;
1654                    continue;
1655                }
1656            }
1657        };
1658        let Ok(Some(line)) = next else { break };
1659        if line.trim().is_empty() {
1660            continue;
1661        }
1662        if let Some(file) = record.as_mut() {
1663            // Flush once a burst is drained, not per line: a slow disk must
1664            // not hold up stdout, and the file stays current while idle.
1665            let flush = lines.get_ref().buffer().is_empty();
1666            if file.write_all(line.as_bytes()).await.is_err()
1667                || file.write_all(b"\n").await.is_err()
1668                || (flush && file.flush().await.is_err())
1669            {
1670                tracing::warn!("recording failed; continuing without it");
1671                record = None;
1672            }
1673        }
1674        match parse_frame(&line) {
1675            InboundMessage::ControlResponse(r) => {
1676                if let Some((_, tx)) = cleanup.pending.remove(&r.response.request_id) {
1677                    let _ = tx.send(r.response);
1678                }
1679            }
1680            InboundMessage::ControlRequest(req) => {
1681                // Answer without blocking the reader: hooks may run long.
1682                // The handler runs in its own task, so a panic in user code
1683                // still sends an error response instead of leaving the CLI
1684                // waiting. Its abort handle is registered before the next
1685                // line is read, so a `control_cancel_request` always finds it.
1686                let request_id = req.request_id.clone();
1687                let handler = responder.clone();
1688                let task = tokio::spawn(async move { handler.respond(req).await });
1689                responder.in_flight.insert(request_id.clone(), task.abort_handle());
1690                let responder = responder.clone();
1691                tokio::spawn(async move {
1692                    let outcome = task.await;
1693                    responder.in_flight.remove(&request_id);
1694                    let response = match outcome {
1695                        Ok(response) => response,
1696                        // Withdrawn by the CLI, or the CLI is gone: no answer.
1697                        Err(e) if e.is_cancelled() => return,
1698                        Err(e) => ControlResponse::error(&request_id, format!("handler failed: {e}")),
1699                    };
1700                    responder.write(&response).await;
1701                });
1702            }
1703            InboundMessage::ControlCancelRequest(cancel) => {
1704                if let Some((_, task)) = responder.in_flight.remove(&cancel.request_id) {
1705                    task.abort();
1706                }
1707            }
1708            other => {
1709                if let InboundMessage::Result(ref r) = other
1710                    && r.origin.is_none()
1711                {
1712                    decrement(&turns_in_flight);
1713                }
1714                if let InboundMessage::System(ref s) = other {
1715                    let mut id = session_id.write().unwrap_or_else(std::sync::PoisonError::into_inner);
1716                    if id.as_deref() != Some(s.session_id.as_str()) {
1717                        *id = Some(s.session_id.clone());
1718                    }
1719                }
1720                let msg = Arc::new(other);
1721                lock(&fanout).subs.retain(|tx| tx.send(msg.clone()).is_ok());
1722            }
1723        }
1724    }
1725    if let Some(mut file) = record
1726        && file.flush().await.is_err()
1727    {
1728        tracing::warn!("recording failed to flush");
1729    }
1730}
1731
1732/// End-of-stdout teardown of the reader, run from `Drop`.
1733struct ReaderCleanup {
1734    fanout: Arc<std::sync::Mutex<Fanout>>,
1735    pending: Arc<Pending>,
1736    turns_in_flight: Arc<AtomicUsize>,
1737    responder: Arc<Responder>,
1738    done: watch::Sender<bool>,
1739}
1740
1741impl Drop for ReaderCleanup {
1742    fn drop(&mut self) {
1743        {
1744            let mut f = lock(&self.fanout);
1745            f.ended = true;
1746            f.subs.clear();
1747        }
1748        self.pending.clear();
1749        self.turns_in_flight.store(0, Ordering::Release);
1750        // Handlers still waiting (a permission prompt, an elicitation) have
1751        // no CLI left to answer.
1752        self.responder.in_flight.retain(|_, task| {
1753            task.abort();
1754            false
1755        });
1756        let _ = self.done.send(true);
1757    }
1758}
1759
1760/// Decode one stdout line. A `result` the typed model cannot decode still
1761/// ends its turn, as a minimal result, so no stream waits forever; any other
1762/// undecodable JSON frame becomes `Other`.
1763fn parse_frame(line: &str) -> InboundMessage {
1764    match serde_json::from_str(line) {
1765        // A frame type this SDK does not model: keep it verbatim.
1766        Ok(InboundMessage::Unknown) => match serde_json::from_str(line) {
1767            Ok(value) => InboundMessage::Other(value),
1768            Err(_) => InboundMessage::Unknown,
1769        },
1770        Ok(m) => m,
1771        Err(e) => {
1772            let value: Option<serde_json::Value> = serde_json::from_str(line).ok();
1773            let field = |k: &str| value.as_ref().and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(str::to_owned);
1774            if field("type").as_deref() == Some("result") {
1775                tracing::warn!(error = %e, "undecodable result frame; ending the turn with it");
1776                InboundMessage::Result(ResultMessage {
1777                    subtype: field("subtype").unwrap_or_else(|| "error_unparsed_result".into()),
1778                    is_error: value.as_ref().and_then(|v| v.get("is_error")).and_then(serde_json::Value::as_bool).unwrap_or(false),
1779                    result: field("result"),
1780                    session_id: field("session_id"),
1781                    origin: value.as_ref().and_then(|v| v.get("origin")).cloned(),
1782                    ..ResultMessage::default()
1783                })
1784            } else if let (Some("control_request"), Some(request_id)) = (field("type").as_deref(), value.as_ref().and_then(|v| v.get("request_id")).and_then(|v| v.as_str())) {
1785                // The CLI waits for an answer; an error reply beats a hang.
1786                tracing::warn!(error = %e, "undecodable control_request; answering with an error");
1787                InboundMessage::ControlRequest(ControlRequest {
1788                    request_id: request_id.to_owned(),
1789                    request: ControlRequestBody::Unsupported,
1790                })
1791            } else if let Some(value) = value {
1792                // A known type in a shape this SDK cannot decode: hand it on
1793                // verbatim rather than losing it.
1794                tracing::warn!(error = %e, "undecodable frame; passing it on as Other");
1795                InboundMessage::Other(value)
1796            } else {
1797                tracing::debug!(error = %e, line = %line, "non-JSON stdout line");
1798                InboundMessage::Unknown
1799            }
1800        }
1801    }
1802}
1803
1804impl Responder {
1805    async fn respond(&self, req: ControlRequest) -> ControlResponse {
1806        match req.request {
1807            ControlRequestBody::HookCallback(hcb) => {
1808                let span = tracing::info_span!(
1809                    "claude.hook",
1810                    callback_id = %hcb.callback_id,
1811                    event = ?hcb.input.hook_event_name,
1812                    tool = hcb.input.tool_name.as_deref().unwrap_or(""),
1813                    blocked = tracing::field::Empty,
1814                );
1815                let output = self.hooks.dispatch(&hcb.callback_id, hcb.input).instrument(span.clone()).await;
1816                if let Some(ref o) = output {
1817                    span.record("blocked", o.is_block());
1818                }
1819                match output {
1820                    Some(output) => match serde_json::to_value(output) {
1821                        Ok(v) => ControlResponse::success(&req.request_id, v),
1822                        Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1823                    },
1824                    None => ControlResponse::error(
1825                        &req.request_id,
1826                        format!("no hook callback registered for id {}", hcb.callback_id),
1827                    ),
1828                }
1829            }
1830            ControlRequestBody::CanUseTool(cut) => match &self.can_use_tool {
1831                Some(handler) => {
1832                    let original = cut.input.clone();
1833                    let decision = match (handler.0)(cut).await {
1834                        // The CLI expects updatedInput on allow; echo the original.
1835                        ToolDecision::Allow { updated_input, updated_permissions } => ToolDecision::Allow {
1836                            updated_input: Some(updated_input.unwrap_or(original)),
1837                            updated_permissions,
1838                        },
1839                        deny @ ToolDecision::Deny { .. } => deny,
1840                    };
1841                    match serde_json::to_value(decision) {
1842                        Ok(v) => ControlResponse::success(&req.request_id, v),
1843                        Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1844                    }
1845                }
1846                None => ControlResponse::error(&req.request_id, "no can_use_tool handler"),
1847            },
1848            ControlRequestBody::McpMessage(m) => {
1849                let span = tracing::info_span!(
1850                    "claude.tool",
1851                    server = %m.server_name,
1852                    method = m.message.get("method").and_then(|v| v.as_str()).unwrap_or(""),
1853                    tool = m.message.pointer("/params/name").and_then(|v| v.as_str()).unwrap_or(""),
1854                );
1855                let server = self.mcp_servers.iter().find(|s| s.name == m.server_name).cloned().or_else(|| {
1856                    let dynamic = self.dynamic_mcp_servers.read().unwrap_or_else(std::sync::PoisonError::into_inner);
1857                    dynamic.iter().find(|s| s.name == m.server_name).cloned()
1858                });
1859                let reply = match server {
1860                    Some(server) => {
1861                        let session_id = self.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
1862                        server.handle_in_session(&m.message, session_id).instrument(span).await
1863                    }
1864                    None => serde_json::json!({
1865                        "jsonrpc": "2.0",
1866                        "id": m.message.get("id"),
1867                        "error": { "code": -32601, "message": format!("Server '{}' not found", m.server_name) },
1868                    }),
1869                };
1870                ControlResponse::success(&req.request_id, serde_json::json!({ "mcp_response": reply }))
1871            }
1872            ControlRequestBody::Elicitation(e) => match &self.on_elicitation {
1873                Some(handler) => match serde_json::to_value((handler.0)(e).await) {
1874                    Ok(v) => ControlResponse::success(&req.request_id, v),
1875                    Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1876                },
1877                None => ControlResponse::error(&req.request_id, "no on_elicitation handler"),
1878            },
1879            ControlRequestBody::RequestUserDialog(d) => match &self.on_user_dialog {
1880                Some(handler) => match serde_json::to_value((handler.0)(d).await) {
1881                    Ok(v) => ControlResponse::success(&req.request_id, v),
1882                    Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1883                },
1884                None => ControlResponse::error(&req.request_id, "no on_user_dialog handler"),
1885            },
1886            ControlRequestBody::Unsupported => {
1887                ControlResponse::error(&req.request_id, "unsupported control request subtype")
1888            }
1889        }
1890    }
1891
1892    async fn write(&self, response: &ControlResponse) {
1893        match serde_json::to_vec(response) {
1894            Ok(bytes) => if let Some(tx) = self.stdin_tx.upgrade() {
1895                let _ = tx.send(bytes).await;
1896            } else { tracing::debug!("session closed; dropping control response") },
1897            Err(e) => tracing::warn!(error = %e, "failed to serialize control response"),
1898        }
1899    }
1900}