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