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 retry;
339#[cfg(all(feature = "json", feature = "async"))]
340pub mod session;
341#[cfg(feature = "json")]
342pub mod settings;
343pub mod skills;
344pub mod slash;
345pub mod streaming;
346pub mod tool_pattern;
347pub mod types;
348pub mod version;
349pub mod worktrees;
350
351use std::collections::HashMap;
352use std::path::{Path, PathBuf};
353use std::time::Duration;
354
355pub use budget::{BudgetBuilder, BudgetTracker};
356pub use command::ClaudeCommand;
357#[cfg(feature = "sync")]
358pub use command::ClaudeCommandSyncExt;
359#[allow(deprecated)]
360pub use command::agents::AgentsCommand;
361pub use command::auth::{
362    AuthLoginCommand, AuthLogoutCommand, AuthStatusCommand, LoginMode, SetupTokenCommand,
363};
364pub use command::auto_mode::{
365    AutoModeConfigCommand, AutoModeCritiqueCommand, AutoModeDefaultsCommand,
366};
367pub use command::doctor::DoctorCommand;
368pub use command::install::InstallCommand;
369pub use command::marketplace::{
370    MarketplaceAddCommand, MarketplaceListCommand, MarketplaceRemoveCommand,
371    MarketplaceUpdateCommand,
372};
373pub use command::mcp::{
374    McpAddCommand, McpAddFromDesktopCommand, McpAddJsonCommand, McpGetCommand, McpListCommand,
375    McpLoginCommand, McpLogoutCommand, McpRemoveCommand, McpResetProjectChoicesCommand,
376    McpServeCommand,
377};
378pub use command::plugin::{
379    PluginDetailsCommand, PluginDisableCommand, PluginEnableCommand, PluginInstallCommand,
380    PluginListCommand, PluginPruneCommand, PluginTagCommand, PluginUninstallCommand,
381    PluginUpdateCommand, PluginValidateCommand,
382};
383pub use command::project::ProjectPurgeCommand;
384pub use command::query::QueryCommand;
385pub use command::raw::RawCommand;
386pub use command::ultrareview::UltrareviewCommand;
387pub use command::update::UpdateCommand;
388pub use command::version::VersionCommand;
389#[cfg(all(feature = "json", feature = "async"))]
390pub use conversation::Conversation;
391#[cfg(all(feature = "json", feature = "async"))]
392pub use duplex::{
393    DuplexOptions, DuplexSession, InboundEvent, PermissionDecision, PermissionHandler,
394    PermissionRequest, TurnResult,
395};
396pub use error::{Error, Result};
397pub use exec::CommandOutput;
398#[cfg(feature = "tempfile")]
399pub use mcp_config::TempMcpConfig;
400pub use mcp_config::{McpConfigBuilder, McpServerConfig};
401pub use retry::{BackoffStrategy, RetryPolicy};
402#[cfg(all(feature = "json", feature = "async"))]
403pub use session::Session;
404pub use tool_pattern::{PatternError, ToolPattern};
405pub use types::*;
406pub use version::{CliVersion, CliVersionStatus, VersionParseError};
407
408/// The Claude CLI client. Holds shared configuration applied to all commands.
409///
410/// Create one via [`Claude::builder()`] and reuse it across commands.
411#[derive(Debug, Clone)]
412pub struct Claude {
413    pub(crate) binary: PathBuf,
414    pub(crate) working_dir: Option<PathBuf>,
415    pub(crate) env: HashMap<String, String>,
416    pub(crate) global_args: Vec<String>,
417    pub(crate) timeout: Option<Duration>,
418    pub(crate) retry_policy: Option<RetryPolicy>,
419    pub(crate) tested_cli_version_range: Option<(CliVersion, CliVersion)>,
420}
421
422impl Claude {
423    /// Create a new builder for configuring the Claude client.
424    #[must_use]
425    pub fn builder() -> ClaudeBuilder {
426        ClaudeBuilder::default()
427    }
428
429    /// Get the path to the claude binary.
430    #[must_use]
431    pub fn binary(&self) -> &Path {
432        &self.binary
433    }
434
435    /// Get the working directory, if set.
436    #[must_use]
437    pub fn working_dir(&self) -> Option<&Path> {
438        self.working_dir.as_deref()
439    }
440
441    /// Create a clone of this client with a different working directory.
442    #[must_use]
443    pub fn with_working_dir(&self, dir: impl Into<PathBuf>) -> Self {
444        let mut clone = self.clone();
445        clone.working_dir = Some(dir.into());
446        clone
447    }
448
449    /// Query the installed CLI version.
450    ///
451    /// Runs `claude --version` and parses the output into a [`CliVersion`].
452    ///
453    /// # Example
454    ///
455    /// ```no_run
456    /// # async fn example() -> claude_wrapper::Result<()> {
457    /// let claude = claude_wrapper::Claude::builder().build()?;
458    /// let version = claude.cli_version().await?;
459    /// println!("Claude CLI {version}");
460    /// # Ok(())
461    /// # }
462    /// ```
463    #[cfg(feature = "async")]
464    pub async fn cli_version(&self) -> Result<CliVersion> {
465        let output = VersionCommand::new().execute(self).await?;
466        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
467            message: format!("failed to parse CLI version: {e}"),
468            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
469            working_dir: None,
470        })
471    }
472
473    /// Check that the installed CLI version meets a minimum requirement.
474    ///
475    /// Returns the detected version on success, or an error if the version
476    /// is below the minimum.
477    ///
478    /// # Example
479    ///
480    /// ```no_run
481    /// use claude_wrapper::CliVersion;
482    ///
483    /// # async fn example() -> claude_wrapper::Result<()> {
484    /// let claude = claude_wrapper::Claude::builder().build()?;
485    /// let version = claude.check_version(&CliVersion::new(2, 1, 0)).await?;
486    /// println!("CLI version {version} meets minimum requirement");
487    /// # Ok(())
488    /// # }
489    /// ```
490    #[cfg(feature = "async")]
491    pub async fn check_version(&self, minimum: &CliVersion) -> Result<CliVersion> {
492        let version = self.cli_version().await?;
493        if version.satisfies_minimum(minimum) {
494            Ok(version)
495        } else {
496            Err(Error::VersionMismatch {
497                found: version,
498                minimum: *minimum,
499            })
500        }
501    }
502
503    /// Blocking mirror of [`Claude::cli_version`]. Requires the
504    /// `sync` feature.
505    #[cfg(feature = "sync")]
506    pub fn cli_version_sync(&self) -> Result<CliVersion> {
507        let output = VersionCommand::new().execute_sync(self)?;
508        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
509            message: format!("failed to parse CLI version: {e}"),
510            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
511            working_dir: None,
512        })
513    }
514
515    /// Blocking mirror of [`Claude::check_version`]. Requires the
516    /// `sync` feature.
517    #[cfg(feature = "sync")]
518    pub fn check_version_sync(&self, minimum: &CliVersion) -> Result<CliVersion> {
519        let version = self.cli_version_sync()?;
520        if version.satisfies_minimum(minimum) {
521            Ok(version)
522        } else {
523            Err(Error::VersionMismatch {
524                found: version,
525                minimum: *minimum,
526            })
527        }
528    }
529
530    /// The tested-against `[min, max]` range declared at build time
531    /// via [`ClaudeBuilder::tested_cli_version_range`], if any.
532    #[must_use]
533    pub fn tested_cli_version_range(&self) -> Option<(CliVersion, CliVersion)> {
534        self.tested_cli_version_range
535    }
536
537    /// Classify the installed CLI against the declared
538    /// tested-against range. Logs a `tracing::warn!` when outside
539    /// the range; returns the typed status either way. If no range
540    /// was declared via [`ClaudeBuilder::tested_cli_version_range`],
541    /// returns [`CliVersionStatus::Tested`] -- callers that didn't
542    /// opt in get the silent-success path.
543    ///
544    /// Intended for one-shot use at startup, not on every command.
545    #[cfg(feature = "async")]
546    pub async fn cli_version_status(&self) -> Result<CliVersionStatus> {
547        let Some((min, max)) = self.tested_cli_version_range else {
548            return Ok(CliVersionStatus::Tested);
549        };
550        let found = self.cli_version().await?;
551        let status = found.status_within(&min, &max);
552        warn_on_drift(&status);
553        Ok(status)
554    }
555
556    /// Blocking mirror of [`Claude::cli_version_status`]. Requires
557    /// the `sync` feature.
558    #[cfg(feature = "sync")]
559    pub fn cli_version_status_sync(&self) -> Result<CliVersionStatus> {
560        let Some((min, max)) = self.tested_cli_version_range else {
561            return Ok(CliVersionStatus::Tested);
562        };
563        let found = self.cli_version_sync()?;
564        let status = found.status_within(&min, &max);
565        warn_on_drift(&status);
566        Ok(status)
567    }
568}
569
570#[allow(dead_code)] // unused with neither `async` nor `sync` feature
571fn warn_on_drift(status: &CliVersionStatus) {
572    match status {
573        CliVersionStatus::Tested => {}
574        CliVersionStatus::NewerUntested {
575            found, tested_max, ..
576        } => {
577            tracing::warn!(
578                found = %found,
579                tested_max = %tested_max,
580                "claude CLI is newer than the wrapper's tested-against range; \
581                 semantics may have drifted -- proceed with caution"
582            );
583        }
584        CliVersionStatus::OlderThanMinimum { found, minimum, .. } => {
585            tracing::warn!(
586                found = %found,
587                minimum = %minimum,
588                "claude CLI is older than the wrapper's declared minimum; \
589                 incorrect behavior is likely (missing flags, different shapes)"
590            );
591        }
592    }
593}
594
595/// Builder for creating a [`Claude`] client.
596///
597/// # Example
598///
599/// ```no_run
600/// use claude_wrapper::Claude;
601///
602/// # fn example() -> claude_wrapper::Result<()> {
603/// let claude = Claude::builder()
604///     .env("AWS_REGION", "us-west-2")
605///     .timeout_secs(120)
606///     .build()?;
607/// # Ok(())
608/// # }
609/// ```
610#[derive(Debug, Default)]
611pub struct ClaudeBuilder {
612    binary: Option<PathBuf>,
613    working_dir: Option<PathBuf>,
614    env: HashMap<String, String>,
615    global_args: Vec<String>,
616    timeout: Option<Duration>,
617    retry_policy: Option<RetryPolicy>,
618    tested_cli_version_range: Option<(CliVersion, CliVersion)>,
619}
620
621impl ClaudeBuilder {
622    /// Set the path to the claude binary.
623    ///
624    /// If not set, the binary is resolved from PATH using `which`.
625    #[must_use]
626    pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
627        self.binary = Some(path.into());
628        self
629    }
630
631    /// Set the working directory for all commands.
632    ///
633    /// The spawned process will use this as its current directory.
634    #[must_use]
635    pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
636        self.working_dir = Some(path.into());
637        self
638    }
639
640    /// Add an environment variable to pass to all commands.
641    #[must_use]
642    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
643        self.env.insert(key.into(), value.into());
644        self
645    }
646
647    /// Add multiple environment variables.
648    #[must_use]
649    pub fn envs(
650        mut self,
651        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
652    ) -> Self {
653        for (k, v) in vars {
654            self.env.insert(k.into(), v.into());
655        }
656        self
657    }
658
659    /// Set a default timeout for all commands (in seconds).
660    #[must_use]
661    pub fn timeout_secs(mut self, seconds: u64) -> Self {
662        self.timeout = Some(Duration::from_secs(seconds));
663        self
664    }
665
666    /// Set a default timeout for all commands.
667    #[must_use]
668    pub fn timeout(mut self, duration: Duration) -> Self {
669        self.timeout = Some(duration);
670        self
671    }
672
673    /// Add a global argument applied to all commands.
674    ///
675    /// This is an escape hatch for flags not yet covered by the API.
676    #[must_use]
677    pub fn arg(mut self, arg: impl Into<String>) -> Self {
678        self.global_args.push(arg.into());
679        self
680    }
681
682    /// Enable verbose output for all commands (`--verbose`).
683    #[must_use]
684    pub fn verbose(mut self) -> Self {
685        self.global_args.push("--verbose".into());
686        self
687    }
688
689    /// Enable debug output for all commands (`--debug`).
690    #[must_use]
691    pub fn debug(mut self) -> Self {
692        self.global_args.push("--debug".into());
693        self
694    }
695
696    /// Set a default retry policy for all commands.
697    ///
698    /// Individual commands can override this via their own retry settings.
699    ///
700    /// # Example
701    ///
702    /// ```no_run
703    /// use claude_wrapper::{Claude, RetryPolicy};
704    /// use std::time::Duration;
705    ///
706    /// # fn example() -> claude_wrapper::Result<()> {
707    /// let claude = Claude::builder()
708    ///     .retry(RetryPolicy::new()
709    ///         .max_attempts(3)
710    ///         .initial_backoff(Duration::from_secs(2))
711    ///         .exponential()
712    ///         .retry_on_timeout(true))
713    ///     .build()?;
714    /// # Ok(())
715    /// # }
716    /// ```
717    #[must_use]
718    pub fn retry(mut self, policy: RetryPolicy) -> Self {
719        self.retry_policy = Some(policy);
720        self
721    }
722
723    /// Declare the inclusive `[min, max]` range of `claude` CLI
724    /// versions this client has been tested against.
725    ///
726    /// The wrapper does not enforce the range -- nothing errors when
727    /// it's set wrong. Use [`Claude::cli_version_status`] (or its
728    /// sync mirror) at startup to classify the actually-installed CLI
729    /// against this declaration; that call returns a typed
730    /// [`CliVersionStatus`] AND emits a `tracing::warn!` when
731    /// outside the range. Hosts (claude-server, application code)
732    /// can additionally surface the status to operators.
733    ///
734    /// # Why this exists
735    ///
736    /// CLI semantics drift across minor / patch releases (e.g.
737    /// `claude agents` was repurposed in 2.1.143). The min floor
738    /// lets us say "we know it's broken below this"; the max ceiling
739    /// lets us say "we haven't verified above this -- proceed but
740    /// expect surprises."
741    ///
742    /// # Example
743    ///
744    /// ```no_run
745    /// use claude_wrapper::{Claude, CliVersion};
746    ///
747    /// # async fn example() -> claude_wrapper::Result<()> {
748    /// let claude = Claude::builder()
749    ///     .tested_cli_version_range(CliVersion::new(2, 1, 0), CliVersion::new(2, 1, 999))
750    ///     .build()?;
751    /// // Run once at startup to log a warning if the CLI is out of range.
752    /// let _status = claude.cli_version_status().await?;
753    /// # Ok(()) }
754    /// ```
755    #[must_use]
756    pub fn tested_cli_version_range(mut self, min: CliVersion, max: CliVersion) -> Self {
757        self.tested_cli_version_range = Some((min, max));
758        self
759    }
760
761    /// Build the Claude client, resolving the binary path.
762    pub fn build(self) -> Result<Claude> {
763        let binary = match self.binary {
764            Some(path) => path,
765            None => which::which("claude").map_err(|_| Error::NotFound)?,
766        };
767
768        Ok(Claude {
769            binary,
770            working_dir: self.working_dir,
771            env: self.env,
772            global_args: self.global_args,
773            timeout: self.timeout,
774            retry_policy: self.retry_policy,
775            tested_cli_version_range: self.tested_cli_version_range,
776        })
777    }
778}
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783
784    #[test]
785    fn test_builder_with_binary() {
786        let claude = Claude::builder()
787            .binary("/usr/local/bin/claude")
788            .env("FOO", "bar")
789            .timeout_secs(60)
790            .build()
791            .unwrap();
792
793        assert_eq!(claude.binary, PathBuf::from("/usr/local/bin/claude"));
794        assert_eq!(claude.env.get("FOO").unwrap(), "bar");
795        assert_eq!(claude.timeout, Some(Duration::from_secs(60)));
796    }
797
798    #[test]
799    fn test_builder_global_args() {
800        let claude = Claude::builder()
801            .binary("/usr/local/bin/claude")
802            .arg("--verbose")
803            .build()
804            .unwrap();
805
806        assert_eq!(claude.global_args, vec!["--verbose"]);
807    }
808
809    #[test]
810    fn test_builder_verbose() {
811        let claude = Claude::builder()
812            .binary("/usr/local/bin/claude")
813            .verbose()
814            .build()
815            .unwrap();
816        assert!(claude.global_args.contains(&"--verbose".to_string()));
817    }
818
819    #[test]
820    fn test_builder_debug() {
821        let claude = Claude::builder()
822            .binary("/usr/local/bin/claude")
823            .debug()
824            .build()
825            .unwrap();
826        assert!(claude.global_args.contains(&"--debug".to_string()));
827    }
828}