Skip to main content

claude_wrapper/
lib.rs

1//! A type-safe Claude Code CLI wrapper for Rust.
2//!
3//! `claude-wrapper` provides a builder-pattern interface for invoking the
4//! `claude` CLI programmatically. Each subcommand is a typed builder that
5//! produces typed output. The design follows the same shape as
6//! [`docker-wrapper`](https://crates.io/crates/docker-wrapper) and
7//! [`terraform-wrapper`](https://crates.io/crates/terraform-wrapper).
8//!
9//! # Feature flags
10//!
11//! | Feature | Default | Purpose |
12//! |---|---|---|
13//! | `async` | yes | tokio-backed async API. Disabling drops tokio from the runtime dep tree. |
14//! | `json` | yes | JSON output parsing and the JSON-backed surface ([`QueryCommand::execute_json`], [`streaming`], [`session::Session`], [`duplex`], [`conversation`], and the [`history`] / [`jobs`] / [`settings`] introspection modules). |
15//! | `tempfile` | yes | [`TempMcpConfig`] for one-shot MCP config files. |
16//! | `sync` | no | Blocking API: `*_sync` methods on [`exec`], [`retry`], every command builder, and [`Claude`]. |
17//!
18//! Sync-only (tokio-free) build:
19//!
20//! ```toml
21//! claude-wrapper = { version = "0.13", default-features = false, features = ["json", "sync"] }
22//! ```
23//!
24//! # Quick start (async)
25//!
26//! ```no_run
27//! # #[cfg(feature = "async")] {
28//! use claude_wrapper::{Claude, ClaudeCommand, QueryCommand};
29//!
30//! # async fn example() -> claude_wrapper::Result<()> {
31//! let claude = Claude::builder().build()?;
32//! let output = QueryCommand::new("explain this error: file not found")
33//!     .model("sonnet")
34//!     .execute(&claude)
35//!     .await?;
36//! println!("{}", output.stdout);
37//! # Ok(()) }
38//! # }
39//! ```
40//!
41//! # Quick start (sync)
42//!
43//! Enable the `sync` feature and bring [`ClaudeCommandSyncExt`] into scope:
44//!
45//! ```no_run
46//! # #[cfg(feature = "sync")] {
47//! use claude_wrapper::{Claude, ClaudeCommandSyncExt, QueryCommand};
48//!
49//! # fn example() -> claude_wrapper::Result<()> {
50//! let claude = Claude::builder().build()?;
51//! let output = QueryCommand::new("explain this error")
52//!     .execute_sync(&claude)?;
53//! println!("{}", output.stdout);
54//! # Ok(()) }
55//! # }
56//! ```
57//!
58//! # Two-layer builder
59//!
60//! The [`Claude`] client holds shared config (binary path, env, timeout,
61//! default retry policy). Command builders hold per-invocation options
62//! and call `execute(&claude)` (or `execute_sync`).
63//!
64//! ```no_run
65//! # #[cfg(feature = "async")] {
66//! use claude_wrapper::{Claude, ClaudeCommand, Effort, PermissionMode, QueryCommand};
67//!
68//! # async fn example() -> claude_wrapper::Result<()> {
69//! let claude = Claude::builder()
70//!     .env("AWS_REGION", "us-west-2")
71//!     .timeout_secs(300)
72//!     .build()?;
73//!
74//! let output = QueryCommand::new("review src/main.rs")
75//!     .model("opus")
76//!     .system_prompt("You are a senior Rust developer")
77//!     .permission_mode(PermissionMode::Plan)
78//!     .effort(Effort::High)
79//!     .max_turns(5)
80//!     .no_session_persistence()
81//!     .execute(&claude)
82//!     .await?;
83//! # Ok(()) }
84//! # }
85//! ```
86//!
87//! # JSON output
88//!
89//! ```no_run
90//! # #[cfg(all(feature = "async", feature = "json"))] {
91//! use claude_wrapper::{Claude, QueryCommand};
92//!
93//! # async fn example() -> claude_wrapper::Result<()> {
94//! let claude = Claude::builder().build()?;
95//! let result = QueryCommand::new("what is 2+2?")
96//!     .execute_json(&claude)
97//!     .await?;
98//! println!("answer: {}", result.result);
99//! println!("cost: ${:.4}", result.cost_usd.unwrap_or(0.0));
100//! # Ok(()) }
101//! # }
102//! ```
103//!
104//! # Multi-turn conversations
105//!
106//! Two shapes for multi-turn work, each suited to a different
107//! process model. [`DuplexSession`] is the recommended choice for
108//! long-running hosts; [`Session`] is the right fit for short-lived
109//! processes.
110//!
111//! | | [`DuplexSession`] | [`Session`] |
112//! |---|---|---|
113//! | Process model | one child held open across turns | new subprocess per turn, `--resume` continuity |
114//! | Mid-turn interrupt | yes ([`DuplexSession::interrupt`](duplex::DuplexSession::interrupt)) | no (only `child.kill()` via SIGKILL) |
115//! | Mid-turn permission prompts | yes ([`PermissionHandler`]) | no |
116//! | Broadcast event subscribers | yes ([`DuplexSession::subscribe`](duplex::DuplexSession::subscribe)) | no (per-turn `stream_query`) |
117//! | Built-in cost / history tracking | no ([`TurnResult`] is per-turn) | yes ([`Session::total_cost_usd`], [`Session::history`], [`BudgetTracker`]) |
118//! | Right for | long-running hosts (IDE backends, daemons, agent servers, chat UIs) | short-lived processes (CLIs, build scripts, batch jobs, lambdas) |
119//!
120//! ## `DuplexSession` (recommended for long-running hosts)
121//!
122//! ```no_run
123//! # #[cfg(all(feature = "async", feature = "json"))] {
124//! use claude_wrapper::Claude;
125//! use claude_wrapper::duplex::{DuplexOptions, DuplexSession};
126//!
127//! # async fn example() -> claude_wrapper::Result<()> {
128//! let claude = Claude::builder().build()?;
129//! let session = DuplexSession::spawn(
130//!     &claude,
131//!     DuplexOptions::default().model("haiku"),
132//! ).await?;
133//!
134//! let turn = session.send("what's 2 + 2?").await?;
135//! println!("answer: {}", turn.result_text().unwrap_or(""));
136//!
137//! session.close().await?;
138//! # Ok(()) }
139//! # }
140//! ```
141//!
142//! See the [duplex module docs](duplex) for the full API including
143//! `subscribe`, `interrupt`, and `respond_to_permission`.
144//!
145//! For host-side bookkeeping (history, cumulative cost, optional
146//! [`BudgetTracker`] hard stop) on top of a [`DuplexSession`], wrap
147//! it in a [`Conversation`]. See the
148//! [conversation module docs](conversation).
149//!
150//! ## `Session` (for short-lived processes)
151//!
152//! ```no_run
153//! # #[cfg(all(feature = "async", feature = "json"))] {
154//! use std::sync::Arc;
155//! use claude_wrapper::Claude;
156//! use claude_wrapper::session::Session;
157//!
158//! # async fn example() -> claude_wrapper::Result<()> {
159//! let claude = Arc::new(Claude::builder().build()?);
160//! let mut session = Session::new(claude);
161//! let _first = session.send("what's 2 + 2?").await?;
162//! let _second = session.send("and squared?").await?;
163//! println!("cost: ${:.4}", session.total_cost_usd());
164//! # Ok(()) }
165//! # }
166//! ```
167//!
168//! See the [session module docs](session) for the full API.
169//!
170//! # Budget tracking
171//!
172//! Attach a [`BudgetTracker`] to a session (or share one across several
173//! sessions) to enforce a cumulative USD ceiling. Callbacks fire
174//! exactly once when thresholds are crossed; pre-turn checks
175//! short-circuit with [`Error::BudgetExceeded`]
176//! once the ceiling is hit.
177//!
178//! ```no_run
179//! # #[cfg(all(feature = "async", feature = "json"))] {
180//! use std::sync::Arc;
181//! use claude_wrapper::{BudgetTracker, Claude};
182//! use claude_wrapper::session::Session;
183//!
184//! # async fn example() -> claude_wrapper::Result<()> {
185//! let budget = BudgetTracker::builder()
186//!     .max_usd(5.00)
187//!     .warn_at_usd(4.00)
188//!     .on_warning(|t| eprintln!("warning: ${t:.2}"))
189//!     .on_exceeded(|t| eprintln!("budget hit: ${t:.2}"))
190//!     .build();
191//!
192//! let claude = Arc::new(Claude::builder().build()?);
193//! let mut session = Session::new(claude).with_budget(budget.clone());
194//! session.send("hello").await?;
195//! println!("spent: ${:.4}", budget.total_usd());
196//! # Ok(()) }
197//! # }
198//! ```
199//!
200//! # Tool permissions
201//!
202//! Use [`ToolPattern`] for typed `--allowed-tools` / `--disallowed-tools`
203//! entries. Typed constructors always produce valid patterns; loose
204//! `From<&str>` keeps bare strings working for back-compat.
205//!
206//! ```
207//! use claude_wrapper::{QueryCommand, ToolPattern};
208//!
209//! let cmd = QueryCommand::new("review")
210//!     .allowed_tool(ToolPattern::tool("Read"))
211//!     .allowed_tool(ToolPattern::tool_with_args("Bash", "git log:*"))
212//!     .allowed_tool(ToolPattern::all("Write"))
213//!     .allowed_tool(ToolPattern::mcp("my-server", "*"))
214//!     .disallowed_tool(ToolPattern::tool_with_args("Bash", "rm*"));
215//! ```
216//!
217//! # Streaming
218//!
219//! Process NDJSON events in real time with [`streaming::stream_query`]
220//! (async) or [`streaming::stream_query_sync`] (blocking; non-`Send`
221//! handler supported).
222//!
223//! ```no_run
224//! # #[cfg(all(feature = "async", feature = "json"))] {
225//! use claude_wrapper::{Claude, OutputFormat, QueryCommand};
226//! use claude_wrapper::streaming::{StreamEvent, stream_query};
227//!
228//! # async fn example() -> claude_wrapper::Result<()> {
229//! let claude = Claude::builder().build()?;
230//! let cmd = QueryCommand::new("explain quicksort")
231//!     .output_format(OutputFormat::StreamJson);
232//!
233//! stream_query(&claude, &cmd, |event: StreamEvent| {
234//!     if event.is_result() {
235//!         println!("result: {}", event.result_text().unwrap_or(""));
236//!     }
237//! }).await?;
238//! # Ok(()) }
239//! # }
240//! ```
241//!
242//! # MCP config generation
243//!
244//! Generate `.mcp.json` files for `--mcp-config`:
245//!
246//! ```no_run
247//! # #[cfg(feature = "async")] {
248//! use claude_wrapper::{Claude, ClaudeCommand, McpConfigBuilder, QueryCommand};
249//!
250//! # async fn example() -> claude_wrapper::Result<()> {
251//! McpConfigBuilder::new()
252//!     .http_server("hub", "http://127.0.0.1:9090")
253//!     .stdio_server("tool", "npx", ["my-server"])
254//!     .write_to("/tmp/my-project/.mcp.json")?;
255//!
256//! let claude = Claude::builder().build()?;
257//! QueryCommand::new("list tools")
258//!     .mcp_config("/tmp/my-project/.mcp.json")
259//!     .execute(&claude)
260//!     .await?;
261//! # Ok(()) }
262//! # }
263//! ```
264//!
265//! # On-disk introspection
266//!
267//! A family of read-only modules parses Claude Code's on-disk state
268//! under `~/.claude` directly, without spawning the CLI. Each exposes a
269//! root/loader with `list` / `get` accessors and degrades to an empty
270//! result when the directory is absent: [`history`] (sessions and
271//! transcripts), [`artifacts`] (agents), [`skills`], [`commands`]
272//! (custom slash commands), [`settings`] (the four merged layers),
273//! [`jobs`] (background-agent state), and [`worktrees`]. See the
274//! `inspect_state` example for an end-to-end tour.
275//!
276//! ```no_run
277//! # #[cfg(feature = "json")] {
278//! use claude_wrapper::history::HistoryRoot;
279//!
280//! # fn example() -> claude_wrapper::Result<()> {
281//! let history = HistoryRoot::home()?;
282//! for project in history.list_projects()? {
283//!     println!(
284//!         "{} ({} sessions)",
285//!         project.decoded_path.display(),
286//!         project.session_count,
287//!     );
288//! }
289//! # Ok(()) }
290//! # }
291//! ```
292//!
293//! # Dangerous: bypass mode
294//!
295//! `--permission-mode bypassPermissions` is isolated behind
296//! [`dangerous::DangerousClient`], which requires an env-var
297//! acknowledgement ([`dangerous::ALLOW_ENV`] = `"1"`) at process start.
298//! See the [dangerous module docs](dangerous) for details.
299//!
300//! # Escape hatch
301//!
302//! For subcommands not yet wrapped, use [`RawCommand`]:
303//!
304//! ```no_run
305//! # #[cfg(feature = "async")] {
306//! use claude_wrapper::{Claude, ClaudeCommand, RawCommand};
307//!
308//! # async fn example() -> claude_wrapper::Result<()> {
309//! let claude = Claude::builder().build()?;
310//! let output = RawCommand::new("some-future-command")
311//!     .arg("--new-flag")
312//!     .arg("value")
313//!     .execute(&claude)
314//!     .await?;
315//! # Ok(()) }
316//! # }
317//! ```
318#![warn(missing_docs)]
319
320pub mod artifacts;
321pub mod auth;
322pub mod budget;
323/// Per-subcommand builders and the [`command::ClaudeCommand`] trait.
324pub mod command;
325pub mod commands;
326#[cfg(all(feature = "json", feature = "async"))]
327pub mod conversation;
328pub mod dangerous;
329#[cfg(all(feature = "json", feature = "async"))]
330pub mod duplex;
331pub mod error;
332pub mod exec;
333#[cfg(feature = "json")]
334pub mod history;
335#[cfg(feature = "json")]
336pub mod jobs;
337pub mod mcp_config;
338pub mod memory;
339pub mod plans;
340pub mod retry;
341#[cfg(all(feature = "json", feature = "async"))]
342pub mod session;
343#[cfg(feature = "json")]
344pub mod sessions;
345#[cfg(feature = "json")]
346pub mod settings;
347pub mod skills;
348pub mod slash;
349pub mod streaming;
350#[cfg(feature = "json")]
351pub mod tasks;
352pub mod tool_pattern;
353pub mod types;
354pub mod version;
355pub mod worktrees;
356
357use std::collections::HashMap;
358use std::path::{Path, PathBuf};
359use std::time::Duration;
360
361pub use budget::{BudgetBuilder, BudgetTracker};
362pub use command::ClaudeCommand;
363#[cfg(feature = "sync")]
364pub use command::ClaudeCommandSyncExt;
365#[allow(deprecated)]
366pub use command::agents::AgentsCommand;
367pub use command::auth::{
368    AuthLoginCommand, AuthLogoutCommand, AuthStatusCommand, LoginMode, SetupTokenCommand,
369};
370pub use command::auto_mode::{
371    AutoModeConfigCommand, AutoModeCritiqueCommand, AutoModeDefaultsCommand,
372};
373pub use command::doctor::DoctorCommand;
374pub use command::install::InstallCommand;
375pub use command::marketplace::{
376    MarketplaceAddCommand, MarketplaceListCommand, MarketplaceRemoveCommand,
377    MarketplaceUpdateCommand,
378};
379pub use command::mcp::{
380    McpAddCommand, McpAddFromDesktopCommand, McpAddJsonCommand, McpGetCommand, McpListCommand,
381    McpLoginCommand, McpLogoutCommand, McpRemoveCommand, McpResetProjectChoicesCommand,
382    McpServeCommand,
383};
384pub use command::plugin::{
385    PluginDetailsCommand, PluginDisableCommand, PluginEnableCommand, PluginInstallCommand,
386    PluginListCommand, PluginPruneCommand, PluginTagCommand, PluginUninstallCommand,
387    PluginUpdateCommand, PluginValidateCommand,
388};
389pub use command::project::ProjectPurgeCommand;
390pub use command::query::QueryCommand;
391pub use command::raw::RawCommand;
392pub use command::ultrareview::UltrareviewCommand;
393pub use command::update::UpdateCommand;
394pub use command::version::VersionCommand;
395#[cfg(all(feature = "json", feature = "async"))]
396pub use conversation::Conversation;
397#[cfg(all(feature = "json", feature = "async"))]
398pub use duplex::{
399    DuplexOptions, DuplexSession, InboundEvent, PermissionDecision, PermissionHandler,
400    PermissionRequest, TurnResult,
401};
402pub use error::{Error, Result};
403pub use exec::CommandOutput;
404#[cfg(feature = "tempfile")]
405pub use mcp_config::TempMcpConfig;
406pub use mcp_config::{McpConfigBuilder, McpServerConfig};
407pub use retry::{BackoffStrategy, RetryPolicy};
408#[cfg(all(feature = "json", feature = "async"))]
409pub use session::Session;
410pub use tool_pattern::{PatternError, ToolPattern};
411pub use types::*;
412pub use version::{
413    CliVersion, CliVersionStatus, TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN, VersionParseError,
414};
415
416/// What the crate knows about a child the moment it is spawned.
417///
418/// Delivered to the [`ClaudeBuilder::on_spawn`] observer before the run can
419/// produce output, which is the point: a supervisor that records the pid only
420/// after a run *finishes* has nothing to reconcile when it crashes mid-run.
421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
422#[non_exhaustive]
423pub struct SpawnInfo {
424    /// The child's process id.
425    pub pid: u32,
426    /// The child's process group id, when it leads its own group.
427    ///
428    /// `None` when [`ClaudeBuilder::process_group`] is disabled, in which case
429    /// the child shares the parent's group and its pid must never be passed to
430    /// `killpg`: that would signal the caller's own process group.
431    pub pgid: Option<u32>,
432}
433
434/// Called with [`SpawnInfo`] each time the crate spawns a CLI child.
435///
436/// Must not block: it runs inline on the spawning thread, between `spawn` and
437/// the first read of the child's output.
438pub type SpawnObserver = std::sync::Arc<dyn Fn(SpawnInfo) + Send + Sync>;
439
440/// The Claude CLI client. Holds shared configuration applied to all commands.
441///
442/// Create one via [`Claude::builder()`] and reuse it across commands.
443#[derive(Clone)]
444pub struct Claude {
445    pub(crate) binary: PathBuf,
446    pub(crate) working_dir: Option<PathBuf>,
447    // env, timeout, and retry_policy are written by the builder under
448    // every feature combination but read only by the feature-gated
449    // exec paths, so they are "never read" with neither `async` nor
450    // `sync` feature.
451    #[allow(dead_code)]
452    pub(crate) env: HashMap<String, String>,
453    #[allow(dead_code)]
454    pub(crate) clear_env: bool,
455    pub(crate) global_args: Vec<String>,
456    #[allow(dead_code)]
457    pub(crate) timeout: Option<Duration>,
458    #[allow(dead_code)]
459    pub(crate) retry_policy: Option<RetryPolicy>,
460    pub(crate) tested_cli_version_range: Option<(CliVersion, CliVersion)>,
461    // Read only by the feature-gated exec paths, like env/timeout.
462    #[allow(dead_code)]
463    pub(crate) process_group: bool,
464    #[allow(dead_code)]
465    pub(crate) kill_grace: Option<Duration>,
466    #[allow(dead_code)]
467    pub(crate) on_spawn: Option<SpawnObserver>,
468    #[allow(dead_code)]
469    pub(crate) die_with_parent: bool,
470}
471
472impl std::fmt::Debug for Claude {
473    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474        f.debug_struct("Claude")
475            .field("binary", &self.binary)
476            .field("working_dir", &self.working_dir)
477            .field("clear_env", &self.clear_env)
478            .field("global_args", &self.global_args)
479            .field("timeout", &self.timeout)
480            .field("process_group", &self.process_group)
481            .field("kill_grace", &self.kill_grace)
482            // A closure cannot be rendered, and env may hold credentials, so
483            // neither is printed: only whether an observer is installed.
484            .field("on_spawn", &self.on_spawn.is_some())
485            .finish_non_exhaustive()
486    }
487}
488
489impl Claude {
490    /// Create a new builder for configuring the Claude client.
491    #[must_use]
492    pub fn builder() -> ClaudeBuilder {
493        ClaudeBuilder::default()
494    }
495
496    /// Get the path to the claude binary.
497    #[must_use]
498    pub fn binary(&self) -> &Path {
499        &self.binary
500    }
501
502    /// Get the working directory, if set.
503    #[must_use]
504    pub fn working_dir(&self) -> Option<&Path> {
505        self.working_dir.as_deref()
506    }
507
508    /// Create a clone of this client with a different working directory.
509    #[must_use]
510    pub fn with_working_dir(&self, dir: impl Into<PathBuf>) -> Self {
511        let mut clone = self.clone();
512        clone.working_dir = Some(dir.into());
513        clone
514    }
515
516    /// Query the installed CLI version.
517    ///
518    /// Runs `claude --version` and parses the output into a [`CliVersion`].
519    ///
520    /// # Example
521    ///
522    /// ```no_run
523    /// # async fn example() -> claude_wrapper::Result<()> {
524    /// let claude = claude_wrapper::Claude::builder().build()?;
525    /// let version = claude.cli_version().await?;
526    /// println!("Claude CLI {version}");
527    /// # Ok(())
528    /// # }
529    /// ```
530    #[cfg(feature = "async")]
531    pub async fn cli_version(&self) -> Result<CliVersion> {
532        let output = VersionCommand::new().execute(self).await?;
533        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
534            message: format!("failed to parse CLI version: {e}"),
535            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
536            working_dir: None,
537        })
538    }
539
540    /// Check that the installed CLI version meets a minimum requirement.
541    ///
542    /// Returns the detected version on success, or an error if the version
543    /// is below the minimum.
544    ///
545    /// # Example
546    ///
547    /// ```no_run
548    /// use claude_wrapper::CliVersion;
549    ///
550    /// # async fn example() -> claude_wrapper::Result<()> {
551    /// let claude = claude_wrapper::Claude::builder().build()?;
552    /// let version = claude.check_version(&CliVersion::new(2, 1, 0)).await?;
553    /// println!("CLI version {version} meets minimum requirement");
554    /// # Ok(())
555    /// # }
556    /// ```
557    #[cfg(feature = "async")]
558    pub async fn check_version(&self, minimum: &CliVersion) -> Result<CliVersion> {
559        let version = self.cli_version().await?;
560        if version.satisfies_minimum(minimum) {
561            Ok(version)
562        } else {
563            Err(Error::VersionMismatch {
564                found: version,
565                minimum: *minimum,
566            })
567        }
568    }
569
570    /// Blocking mirror of [`Claude::cli_version`]. Requires the
571    /// `sync` feature.
572    #[cfg(feature = "sync")]
573    pub fn cli_version_sync(&self) -> Result<CliVersion> {
574        let output = VersionCommand::new().execute_sync(self)?;
575        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
576            message: format!("failed to parse CLI version: {e}"),
577            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
578            working_dir: None,
579        })
580    }
581
582    /// Blocking mirror of [`Claude::check_version`]. Requires the
583    /// `sync` feature.
584    #[cfg(feature = "sync")]
585    pub fn check_version_sync(&self, minimum: &CliVersion) -> Result<CliVersion> {
586        let version = self.cli_version_sync()?;
587        if version.satisfies_minimum(minimum) {
588            Ok(version)
589        } else {
590            Err(Error::VersionMismatch {
591                found: version,
592                minimum: *minimum,
593            })
594        }
595    }
596
597    /// The tested-against `[min, max]` range declared at build time
598    /// via [`ClaudeBuilder::tested_cli_version_range`], if any.
599    ///
600    /// `None` means no override was set, in which case version checks
601    /// use the crate's own [`TESTED_CLI_VERSION_MIN`] /
602    /// [`TESTED_CLI_VERSION_MAX`]; see [`Self::effective_tested_range`].
603    #[must_use]
604    pub fn tested_cli_version_range(&self) -> Option<(CliVersion, CliVersion)> {
605        self.tested_cli_version_range
606    }
607
608    /// The range version checks actually use: the caller's override when one
609    /// was set, otherwise the crate's own declared range.
610    #[must_use]
611    pub fn effective_tested_range(&self) -> (CliVersion, CliVersion) {
612        self.tested_cli_version_range
613            .unwrap_or((TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX))
614    }
615
616    /// Classify the installed CLI against the tested-against range.
617    /// Logs a `tracing::warn!` when outside the range; returns the
618    /// typed status either way.
619    ///
620    /// The range defaults to the crate's own
621    /// [`TESTED_CLI_VERSION_MIN`] / [`TESTED_CLI_VERSION_MAX`],
622    /// because only the crate knows what it was built and tested
623    /// against. [`ClaudeBuilder::tested_cli_version_range`] overrides
624    /// it for hosts that have verified a different range themselves.
625    ///
626    /// Intended for one-shot use at startup, not on every command.
627    #[cfg(feature = "async")]
628    pub async fn cli_version_status(&self) -> Result<CliVersionStatus> {
629        let (min, max) = self.effective_tested_range();
630        let found = self.cli_version().await?;
631        let status = found.status_within(&min, &max);
632        warn_on_drift(&status);
633        Ok(status)
634    }
635
636    /// Blocking mirror of [`Claude::cli_version_status`]. Requires
637    /// the `sync` feature.
638    #[cfg(feature = "sync")]
639    pub fn cli_version_status_sync(&self) -> Result<CliVersionStatus> {
640        let (min, max) = self.effective_tested_range();
641        let found = self.cli_version_sync()?;
642        let status = found.status_within(&min, &max);
643        warn_on_drift(&status);
644        Ok(status)
645    }
646
647    /// Refuse to proceed against a CLI outside the tested range.
648    ///
649    /// The opt-in hard gate. [`Claude::cli_version_status`] is the
650    /// reporting path and keeps its behavior: it returns a typed
651    /// status and warns. This one turns the same condition into
652    /// [`Error::UntestedCliVersion`], for hosts that would rather fail
653    /// at startup than run on an unverified binary.
654    ///
655    /// Returns the detected version on success. The drift warning
656    /// still fires on the failure path, so a host that logs and a host
657    /// that gates see the same line.
658    ///
659    /// # Why this is a method and not a builder option
660    ///
661    /// [`ClaudeBuilder::build`] is synchronous and never spawns the
662    /// binary. Enforcing a version there would mean running a
663    /// subprocess inside a constructor, so the check lives where the
664    /// caller can await it.
665    ///
666    /// # Example
667    ///
668    /// ```no_run
669    /// # async fn example() -> claude_wrapper::Result<()> {
670    /// let claude = claude_wrapper::Claude::builder().build()?;
671    /// // Run once at startup; returns Err on an untested CLI.
672    /// let version = claude.ensure_tested_cli_version().await?;
673    /// println!("running against {version}");
674    /// # Ok(())
675    /// # }
676    /// ```
677    #[cfg(feature = "async")]
678    pub async fn ensure_tested_cli_version(&self) -> Result<CliVersion> {
679        let (min, max) = self.effective_tested_range();
680        let found = self.cli_version().await?;
681        self.gate_version(found, min, max)
682    }
683
684    /// Blocking mirror of [`Claude::ensure_tested_cli_version`].
685    /// Requires the `sync` feature.
686    #[cfg(feature = "sync")]
687    pub fn ensure_tested_cli_version_sync(&self) -> Result<CliVersion> {
688        let (min, max) = self.effective_tested_range();
689        let found = self.cli_version_sync()?;
690        self.gate_version(found, min, max)
691    }
692
693    /// Shared decision for the async and sync gates, so the two cannot
694    /// disagree about what "outside the range" means.
695    #[cfg(any(feature = "async", feature = "sync"))]
696    fn gate_version(
697        &self,
698        found: CliVersion,
699        min: CliVersion,
700        max: CliVersion,
701    ) -> Result<CliVersion> {
702        let status = found.status_within(&min, &max);
703        warn_on_drift(&status);
704        if status.is_tested() {
705            Ok(found)
706        } else {
707            Err(Error::UntestedCliVersion {
708                found,
709                tested_min: min,
710                tested_max: max,
711            })
712        }
713    }
714}
715
716#[allow(dead_code)] // unused with neither `async` nor `sync` feature
717fn warn_on_drift(status: &CliVersionStatus) {
718    match status {
719        CliVersionStatus::Tested => {}
720        CliVersionStatus::NewerUntested {
721            found, tested_max, ..
722        } => {
723            tracing::warn!(
724                found = %found,
725                tested_max = %tested_max,
726                "claude CLI is newer than the wrapper's tested-against range; \
727                 semantics may have drifted -- proceed with caution"
728            );
729        }
730        CliVersionStatus::OlderThanMinimum { found, minimum, .. } => {
731            tracing::warn!(
732                found = %found,
733                minimum = %minimum,
734                "claude CLI is older than the wrapper's declared minimum; \
735                 incorrect behavior is likely (missing flags, different shapes)"
736            );
737        }
738    }
739}
740
741/// Builder for creating a [`Claude`] client.
742///
743/// # Example
744///
745/// ```no_run
746/// use claude_wrapper::Claude;
747///
748/// # fn example() -> claude_wrapper::Result<()> {
749/// let claude = Claude::builder()
750///     .env("AWS_REGION", "us-west-2")
751///     .timeout_secs(120)
752///     .build()?;
753/// # Ok(())
754/// # }
755/// ```
756#[derive(Default)]
757pub struct ClaudeBuilder {
758    binary: Option<PathBuf>,
759    working_dir: Option<PathBuf>,
760    env: HashMap<String, String>,
761    clear_env: bool,
762    global_args: Vec<String>,
763    timeout: Option<Duration>,
764    retry_policy: Option<RetryPolicy>,
765    tested_cli_version_range: Option<(CliVersion, CliVersion)>,
766    process_group: Option<bool>,
767    kill_grace: Option<Duration>,
768    on_spawn: Option<SpawnObserver>,
769    die_with_parent: bool,
770}
771
772impl std::fmt::Debug for ClaudeBuilder {
773    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
774        // Mirrors Claude's Debug: a closure cannot be rendered and env may
775        // hold credentials, so neither is printed.
776        f.debug_struct("ClaudeBuilder")
777            .field("binary", &self.binary)
778            .field("working_dir", &self.working_dir)
779            .field("clear_env", &self.clear_env)
780            .field("global_args", &self.global_args)
781            .field("timeout", &self.timeout)
782            .field("process_group", &self.process_group)
783            .field("kill_grace", &self.kill_grace)
784            .field("on_spawn", &self.on_spawn.is_some())
785            .finish_non_exhaustive()
786    }
787}
788
789impl ClaudeBuilder {
790    /// Set the path to the claude binary.
791    ///
792    /// If not set, the binary is resolved from PATH using `which`.
793    #[must_use]
794    pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
795        self.binary = Some(path.into());
796        self
797    }
798
799    /// Set the working directory for all commands.
800    ///
801    /// The spawned process will use this as its current directory.
802    #[must_use]
803    pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
804        self.working_dir = Some(path.into());
805        self
806    }
807
808    /// Add an environment variable to pass to all commands.
809    #[must_use]
810    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
811        self.env.insert(key.into(), value.into());
812        self
813    }
814
815    /// Add multiple environment variables.
816    #[must_use]
817    pub fn envs(
818        mut self,
819        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
820    ) -> Self {
821        for (k, v) in vars {
822            self.env.insert(k.into(), v.into());
823        }
824        self
825    }
826
827    /// Clear the inherited environment of every spawned Claude CLI child.
828    ///
829    /// By default, children inherit the parent process environment and
830    /// [`env`](Self::env) / [`envs`](Self::envs) add or replace entries. With
831    /// this option enabled, the inherited environment is cleared first and
832    /// only explicitly configured entries are applied. The order in which
833    /// `clear_env`, `env`, and `envs` are called does not affect the result.
834    ///
835    /// Callers normally need to rebuild a minimal environment including
836    /// `PATH`, locale settings, the Claude config directory, and the intended
837    /// authentication selector.
838    ///
839    /// This controls only the direct child process environment. It is not an
840    /// operating-system sandbox and does not prevent a same-UID child from
841    /// reading accessible files or inspecting other processes where the OS
842    /// permits it.
843    ///
844    /// # Example
845    ///
846    /// ```no_run
847    /// use claude_wrapper::Claude;
848    ///
849    /// # fn example() -> claude_wrapper::Result<()> {
850    /// let claude = Claude::builder()
851    ///     .clear_env()
852    ///     .env("PATH", "/usr/local/bin:/usr/bin:/bin")
853    ///     .env("CLAUDE_CONFIG_DIR", "/srv/claude/config")
854    ///     .build()?;
855    /// # Ok(())
856    /// # }
857    /// ```
858    #[must_use]
859    pub fn clear_env(mut self) -> Self {
860        self.clear_env = true;
861        self
862    }
863
864    /// Set a default timeout for all commands (in seconds).
865    #[must_use]
866    pub fn timeout_secs(mut self, seconds: u64) -> Self {
867        self.timeout = Some(Duration::from_secs(seconds));
868        self
869    }
870
871    /// Set a default timeout for all commands.
872    #[must_use]
873    pub fn timeout(mut self, duration: Duration) -> Self {
874        self.timeout = Some(duration);
875        self
876    }
877
878    /// Add a global argument applied to all commands.
879    ///
880    /// This is an escape hatch for flags not yet covered by the API.
881    #[must_use]
882    pub fn arg(mut self, arg: impl Into<String>) -> Self {
883        self.global_args.push(arg.into());
884        self
885    }
886
887    /// Enable verbose output for all commands (`--verbose`).
888    #[must_use]
889    pub fn verbose(mut self) -> Self {
890        self.global_args.push("--verbose".into());
891        self
892    }
893
894    /// Enable debug output for all commands (`--debug`).
895    #[must_use]
896    pub fn debug(mut self) -> Self {
897        self.global_args.push("--debug".into());
898        self
899    }
900
901    /// Set a default retry policy for all commands.
902    ///
903    /// Individual commands can override this via their own retry settings.
904    ///
905    /// # Example
906    ///
907    /// ```no_run
908    /// use claude_wrapper::{Claude, RetryPolicy};
909    /// use std::time::Duration;
910    ///
911    /// # fn example() -> claude_wrapper::Result<()> {
912    /// let claude = Claude::builder()
913    ///     .retry(RetryPolicy::new()
914    ///         .max_attempts(3)
915    ///         .initial_backoff(Duration::from_secs(2))
916    ///         .exponential()
917    ///         .retry_on_timeout(true))
918    ///     .build()?;
919    /// # Ok(())
920    /// # }
921    /// ```
922    #[must_use]
923    pub fn retry(mut self, policy: RetryPolicy) -> Self {
924        self.retry_policy = Some(policy);
925        self
926    }
927
928    /// Declare the inclusive `[min, max]` range of `claude` CLI
929    /// versions this client has been tested against.
930    ///
931    /// The wrapper does not enforce the range -- nothing errors when
932    /// it's set wrong. Use [`Claude::cli_version_status`] (or its
933    /// sync mirror) at startup to classify the actually-installed CLI
934    /// against this declaration; that call returns a typed
935    /// [`CliVersionStatus`] AND emits a `tracing::warn!` when
936    /// outside the range. Hosts (claude-server, application code)
937    /// can additionally surface the status to operators.
938    ///
939    /// # Why this exists
940    ///
941    /// CLI semantics drift across minor / patch releases (e.g.
942    /// `claude agents` was repurposed in 2.1.143). The min floor
943    /// lets us say "we know it's broken below this"; the max ceiling
944    /// lets us say "we haven't verified above this -- proceed but
945    /// expect surprises."
946    ///
947    /// # You usually do not need this
948    ///
949    /// The crate declares its own range in
950    /// [`TESTED_CLI_VERSION_MIN`] / [`TESTED_CLI_VERSION_MAX`], and
951    /// version checks use it by default, because only the crate knows
952    /// what it was built and tested against. Set this only when a host
953    /// has verified a different range itself.
954    ///
955    /// # Example
956    ///
957    /// ```no_run
958    /// use claude_wrapper::{Claude, CliVersion};
959    ///
960    /// # async fn example() -> claude_wrapper::Result<()> {
961    /// let claude = Claude::builder()
962    ///     .tested_cli_version_range(CliVersion::new(2, 1, 0), CliVersion::new(2, 1, 999))
963    ///     .build()?;
964    /// // Run once at startup to log a warning if the CLI is out of range.
965    /// let _status = claude.cli_version_status().await?;
966    /// # Ok(()) }
967    /// ```
968    #[must_use]
969    pub fn tested_cli_version_range(mut self, min: CliVersion, max: CliVersion) -> Self {
970        self.tested_cli_version_range = Some((min, max));
971        self
972    }
973
974    /// Control whether spawned `claude` children are placed in their
975    /// own process group on Unix. Defaults to `true`.
976    ///
977    /// Own group (the default): cancellation and timeouts kill the
978    /// child's whole process tree, but the child no longer shares the
979    /// host terminal's process group, so terminal-generated signals
980    /// (Ctrl-C) do not reach it; terminating a run is the wrapper's
981    /// job via drop, timeout, or explicit kill. This is the right
982    /// contract for supervisors (daemons, MCP servers, worker queues).
983    ///
984    /// Shared group (`false`): the child stays in the host's process
985    /// group, so a terminal Ctrl-C reaches the whole run directly, but
986    /// a wrapper-side kill only reaches the direct child and any
987    /// subprocesses it spawned for tool use survive it. This is the
988    /// right contract for terminal-attached hosts that shell out
989    /// synchronously and rely on the terminal as the supervisor.
990    ///
991    /// No effect on non-Unix targets.
992    #[must_use]
993    pub fn process_group(mut self, enabled: bool) -> Self {
994        self.process_group = Some(enabled);
995        self
996    }
997
998    /// Grace period between SIGTERM and SIGKILL when a run is killed
999    /// by a timeout or a duplex shutdown overrun (Unix). Default:
1000    /// none; kills are immediate SIGKILL.
1001    ///
1002    /// With a grace set, the child's whole process group gets SIGTERM
1003    /// first so `claude` can flush its transcript and session state,
1004    /// and SIGKILL follows once the grace elapses. The full grace is
1005    /// waited before the timeout error returns, so keep it short
1006    /// (500ms to 2s). Dropping a future cannot wait, so drop-path
1007    /// cancellation stays immediate SIGKILL, and the grace applies
1008    /// only while the child is in its own process group (see
1009    /// [`process_group`](Self::process_group)).
1010    #[must_use]
1011    pub fn kill_grace(mut self, grace: Duration) -> Self {
1012        self.kill_grace = Some(grace);
1013        self
1014    }
1015
1016    /// Observe every child this client spawns, at spawn time.
1017    ///
1018    /// The observer receives a [`SpawnInfo`] before the run produces output,
1019    /// which is what makes it useful to a supervisor: recording the pid only
1020    /// once a run *finishes* leaves nothing to reconcile after a crash
1021    /// mid-run. Fires for one-shot runs, streaming runs, and duplex sessions
1022    /// alike, and on retry it fires once per attempt, since each attempt is a
1023    /// distinct process.
1024    ///
1025    /// The observer runs inline on the spawning thread, so it must not block.
1026    /// Write a pidfile or push to a channel; do not do I/O that can stall.
1027    ///
1028    /// # Why a callback rather than a return value
1029    ///
1030    /// The crash case needs the pid to be durable *before* the run can be
1031    /// orphaned. A pid on the result type arrives too late for exactly the
1032    /// scenario that motivates recording it.
1033    ///
1034    /// # Example
1035    ///
1036    /// ```no_run
1037    /// use std::sync::Arc;
1038    /// use claude_wrapper::Claude;
1039    ///
1040    /// # fn example() -> claude_wrapper::Result<()> {
1041    /// let claude = Claude::builder()
1042    ///     .on_spawn(Arc::new(|info| {
1043    ///         eprintln!("spawned pid {} (group {:?})", info.pid, info.pgid);
1044    ///     }))
1045    ///     .build()?;
1046    /// # Ok(())
1047    /// # }
1048    /// ```
1049    #[must_use]
1050    pub fn on_spawn(mut self, observer: SpawnObserver) -> Self {
1051        self.on_spawn = Some(observer);
1052        self
1053    }
1054
1055    /// Ask the kernel to kill spawned children when this process dies.
1056    ///
1057    /// **Linux only.** Check [`die_with_parent_supported`](crate::exec::die_with_parent_supported)
1058    /// rather than assuming; elsewhere this is accepted and does nothing.
1059    ///
1060    /// # The problem it addresses
1061    ///
1062    /// Every other cleanup path in this crate is a destructor: `kill_on_drop`,
1063    /// and the process-group kill on drop, timeout, or stream error. None of
1064    /// them run when *this* process is SIGKILLed. The child is then reparented
1065    /// to init, and because it leads its own process group (see
1066    /// [`process_group`](Self::process_group)) terminal signals cannot reach it
1067    /// either. It keeps running, keeps billing, and keeps appending to the
1068    /// session transcript, so a restarted supervisor that resumes the same
1069    /// session id can find itself interleaving with an orphan still writing.
1070    ///
1071    /// On Linux `PR_SET_PDEATHSIG` closes that: the kernel delivers SIGKILL to
1072    /// the child the moment its parent dies, with no cooperation from either
1073    /// side.
1074    ///
1075    /// # What it does not cover
1076    ///
1077    /// - **Non-Linux targets.** macOS has no equivalent. A supervisor that
1078    ///   needs the guarantee there has to poll and kill by pid; recording the
1079    ///   pid is what [`on_spawn`](Self::on_spawn) is for.
1080    /// - **Re-parenting.** The signal fires when the *immediate* parent dies.
1081    ///   If the crate's caller is itself an intermediate process that exits
1082    ///   normally, the child dies then, which is usually what you want but is
1083    ///   worth knowing if you daemonize between building the client and
1084    ///   spawning.
1085    /// - **The fork/prctl window.** Handled: the hook re-checks `getppid()`
1086    ///   after arming and exits if the parent already changed. Without that
1087    ///   check a parent dying in that window leaves exactly the orphan this
1088    ///   option exists to prevent.
1089    ///
1090    /// Off by default, because killing children on parent exit is the right
1091    /// default for a supervisor and the wrong one for a CLI that deliberately
1092    /// backgrounds work.
1093    #[must_use]
1094    pub fn die_with_parent(mut self, enabled: bool) -> Self {
1095        self.die_with_parent = enabled;
1096        self
1097    }
1098
1099    /// Build the Claude client, resolving the binary path.
1100    pub fn build(self) -> Result<Claude> {
1101        let binary = match self.binary {
1102            Some(path) => path,
1103            None => which::which("claude").map_err(|_| Error::NotFound)?,
1104        };
1105
1106        Ok(Claude {
1107            binary,
1108            working_dir: self.working_dir,
1109            env: self.env,
1110            clear_env: self.clear_env,
1111            global_args: self.global_args,
1112            timeout: self.timeout,
1113            retry_policy: self.retry_policy,
1114            tested_cli_version_range: self.tested_cli_version_range,
1115            process_group: self.process_group.unwrap_or(true),
1116            kill_grace: self.kill_grace,
1117            on_spawn: self.on_spawn,
1118            die_with_parent: self.die_with_parent,
1119        })
1120    }
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125    use super::*;
1126
1127    #[test]
1128    fn builder_process_group_defaults_on_and_can_opt_out() {
1129        let on = Claude::builder()
1130            .binary("/nonexistent/claude")
1131            .build()
1132            .unwrap();
1133        assert!(on.process_group);
1134
1135        let off = Claude::builder()
1136            .binary("/nonexistent/claude")
1137            .process_group(false)
1138            .build()
1139            .unwrap();
1140        assert!(!off.process_group);
1141    }
1142
1143    #[test]
1144    fn builder_clear_env_defaults_off_and_is_call_order_independent() {
1145        let inherited = Claude::builder()
1146            .binary("/nonexistent/claude")
1147            .build()
1148            .unwrap();
1149        assert!(!inherited.clear_env);
1150
1151        let cleared = Claude::builder()
1152            .binary("/nonexistent/claude")
1153            .env("FIRST", "1")
1154            .clear_env()
1155            .env("SECOND", "2")
1156            .build()
1157            .unwrap();
1158        assert!(cleared.clear_env);
1159        assert_eq!(cleared.env.get("FIRST").map(String::as_str), Some("1"));
1160        assert_eq!(cleared.env.get("SECOND").map(String::as_str), Some("2"));
1161    }
1162
1163    #[test]
1164    fn builder_kill_grace_defaults_off_and_can_be_set() {
1165        let off = Claude::builder()
1166            .binary("/nonexistent/claude")
1167            .build()
1168            .unwrap();
1169        assert!(off.kill_grace.is_none());
1170
1171        let on = Claude::builder()
1172            .binary("/nonexistent/claude")
1173            .kill_grace(Duration::from_millis(750))
1174            .build()
1175            .unwrap();
1176        assert_eq!(on.kill_grace, Some(Duration::from_millis(750)));
1177    }
1178
1179    // -- the version gate ------------------------------------------
1180    //
1181    // `gate_version` is the decision both the async and sync gates
1182    // share, and it takes the version rather than fetching it, so the
1183    // policy is testable without spawning a binary.
1184
1185    #[cfg(any(feature = "async", feature = "sync"))]
1186    fn gate(found: (u32, u32, u32)) -> Result<CliVersion> {
1187        let claude = Claude::builder()
1188            .binary("/nonexistent/claude")
1189            .build()
1190            .unwrap();
1191        let (min, max) = claude.effective_tested_range();
1192        claude.gate_version(CliVersion::new(found.0, found.1, found.2), min, max)
1193    }
1194
1195    #[cfg(any(feature = "async", feature = "sync"))]
1196    #[test]
1197    fn gate_accepts_a_version_inside_the_declared_range() {
1198        let found = gate((
1199            TESTED_CLI_VERSION_MIN.major,
1200            TESTED_CLI_VERSION_MIN.minor,
1201            TESTED_CLI_VERSION_MIN.patch,
1202        ))
1203        .expect("the declared minimum must pass its own gate");
1204        assert_eq!(found, TESTED_CLI_VERSION_MIN);
1205    }
1206
1207    #[cfg(any(feature = "async", feature = "sync"))]
1208    #[test]
1209    fn gate_rejects_older_than_minimum_with_both_bounds() {
1210        let err = gate((1, 0, 0)).expect_err("1.0.0 is below any supported floor");
1211        match err {
1212            Error::UntestedCliVersion {
1213                found,
1214                tested_min,
1215                tested_max,
1216            } => {
1217                assert_eq!(found, CliVersion::new(1, 0, 0));
1218                assert_eq!(tested_min, TESTED_CLI_VERSION_MIN);
1219                assert_eq!(tested_max, TESTED_CLI_VERSION_MAX);
1220                // The message must say which side it fell off, since
1221                // "too old" and "too new" call for opposite fixes.
1222                assert!(err_text(&err).contains("older"), "{}", err_text(&err));
1223            }
1224            other => panic!("expected UntestedCliVersion, got {other:?}"),
1225        }
1226    }
1227
1228    #[cfg(any(feature = "async", feature = "sync"))]
1229    #[test]
1230    fn gate_rejects_newer_than_maximum() {
1231        let err = gate((99, 0, 0)).expect_err("99.0.0 is above the tested ceiling");
1232        assert!(matches!(err, Error::UntestedCliVersion { .. }));
1233        assert!(err_text(&err).contains("newer"), "{}", err_text(&err));
1234    }
1235
1236    #[cfg(any(feature = "async", feature = "sync"))]
1237    #[test]
1238    fn gate_honours_a_caller_supplied_range_over_the_crate_default() {
1239        // A host that has verified a narrower window should be able to
1240        // enforce it, including rejecting versions the crate itself
1241        // considers fine.
1242        let claude = Claude::builder()
1243            .binary("/nonexistent/claude")
1244            .tested_cli_version_range(CliVersion::new(3, 0, 0), CliVersion::new(3, 0, 9))
1245            .build()
1246            .unwrap();
1247        let (min, max) = claude.effective_tested_range();
1248        assert_eq!(min, CliVersion::new(3, 0, 0));
1249        assert!(
1250            claude
1251                .gate_version(CliVersion::new(3, 0, 5), min, max)
1252                .is_ok()
1253        );
1254        assert!(
1255            claude
1256                .gate_version(TESTED_CLI_VERSION_MIN, min, max)
1257                .is_err(),
1258            "the caller's range must win over the crate's"
1259        );
1260    }
1261
1262    #[cfg(any(feature = "async", feature = "sync"))]
1263    fn err_text(e: &Error) -> String {
1264        e.to_string()
1265    }
1266
1267    #[test]
1268    fn test_builder_with_binary() {
1269        let claude = Claude::builder()
1270            .binary("/usr/local/bin/claude")
1271            .env("FOO", "bar")
1272            .timeout_secs(60)
1273            .build()
1274            .unwrap();
1275
1276        assert_eq!(claude.binary, PathBuf::from("/usr/local/bin/claude"));
1277        assert_eq!(claude.env.get("FOO").unwrap(), "bar");
1278        assert_eq!(claude.timeout, Some(Duration::from_secs(60)));
1279    }
1280
1281    #[test]
1282    fn test_builder_global_args() {
1283        let claude = Claude::builder()
1284            .binary("/usr/local/bin/claude")
1285            .arg("--verbose")
1286            .build()
1287            .unwrap();
1288
1289        assert_eq!(claude.global_args, vec!["--verbose"]);
1290    }
1291
1292    #[test]
1293    fn test_builder_verbose() {
1294        let claude = Claude::builder()
1295            .binary("/usr/local/bin/claude")
1296            .verbose()
1297            .build()
1298            .unwrap();
1299        assert!(claude.global_args.contains(&"--verbose".to_string()));
1300    }
1301
1302    #[test]
1303    fn test_builder_debug() {
1304        let claude = Claude::builder()
1305            .binary("/usr/local/bin/claude")
1306            .debug()
1307            .build()
1308            .unwrap();
1309        assert!(claude.global_args.contains(&"--debug".to_string()));
1310    }
1311}