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