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, OutputStream, 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) output_limit: Option<usize>,
468 #[allow(dead_code)]
469 pub(crate) on_spawn: Option<SpawnObserver>,
470 #[allow(dead_code)]
471 pub(crate) die_with_parent: bool,
472}
473
474impl std::fmt::Debug for Claude {
475 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476 f.debug_struct("Claude")
477 .field("binary", &self.binary)
478 .field("working_dir", &self.working_dir)
479 .field("clear_env", &self.clear_env)
480 .field("global_args", &self.global_args)
481 .field("timeout", &self.timeout)
482 .field("process_group", &self.process_group)
483 .field("kill_grace", &self.kill_grace)
484 .field("output_limit", &self.output_limit)
485 // A closure cannot be rendered, and env may hold credentials, so
486 // neither is printed: only whether an observer is installed.
487 .field("on_spawn", &self.on_spawn.is_some())
488 .finish_non_exhaustive()
489 }
490}
491
492impl Claude {
493 /// Create a new builder for configuring the Claude client.
494 #[must_use]
495 pub fn builder() -> ClaudeBuilder {
496 ClaudeBuilder::default()
497 }
498
499 /// Get the path to the claude binary.
500 #[must_use]
501 pub fn binary(&self) -> &Path {
502 &self.binary
503 }
504
505 /// Get the working directory, if set.
506 #[must_use]
507 pub fn working_dir(&self) -> Option<&Path> {
508 self.working_dir.as_deref()
509 }
510
511 /// Create a clone of this client with a different working directory.
512 #[must_use]
513 pub fn with_working_dir(&self, dir: impl Into<PathBuf>) -> Self {
514 let mut clone = self.clone();
515 clone.working_dir = Some(dir.into());
516 clone
517 }
518
519 /// Query the installed CLI version.
520 ///
521 /// Runs `claude --version` and parses the output into a [`CliVersion`].
522 ///
523 /// # Example
524 ///
525 /// ```no_run
526 /// # async fn example() -> claude_wrapper::Result<()> {
527 /// let claude = claude_wrapper::Claude::builder().build()?;
528 /// let version = claude.cli_version().await?;
529 /// println!("Claude CLI {version}");
530 /// # Ok(())
531 /// # }
532 /// ```
533 #[cfg(feature = "async")]
534 pub async fn cli_version(&self) -> Result<CliVersion> {
535 let output = VersionCommand::new().execute(self).await?;
536 CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
537 message: format!("failed to parse CLI version: {e}"),
538 source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
539 working_dir: None,
540 })
541 }
542
543 /// Check that the installed CLI version meets a minimum requirement.
544 ///
545 /// Returns the detected version on success, or an error if the version
546 /// is below the minimum.
547 ///
548 /// # Example
549 ///
550 /// ```no_run
551 /// use claude_wrapper::CliVersion;
552 ///
553 /// # async fn example() -> claude_wrapper::Result<()> {
554 /// let claude = claude_wrapper::Claude::builder().build()?;
555 /// let version = claude.check_version(&CliVersion::new(2, 1, 0)).await?;
556 /// println!("CLI version {version} meets minimum requirement");
557 /// # Ok(())
558 /// # }
559 /// ```
560 #[cfg(feature = "async")]
561 pub async fn check_version(&self, minimum: &CliVersion) -> Result<CliVersion> {
562 let version = self.cli_version().await?;
563 if version.satisfies_minimum(minimum) {
564 Ok(version)
565 } else {
566 Err(Error::VersionMismatch {
567 found: version,
568 minimum: *minimum,
569 })
570 }
571 }
572
573 /// Blocking mirror of [`Claude::cli_version`]. Requires the
574 /// `sync` feature.
575 #[cfg(feature = "sync")]
576 pub fn cli_version_sync(&self) -> Result<CliVersion> {
577 let output = VersionCommand::new().execute_sync(self)?;
578 CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
579 message: format!("failed to parse CLI version: {e}"),
580 source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
581 working_dir: None,
582 })
583 }
584
585 /// Blocking mirror of [`Claude::check_version`]. Requires the
586 /// `sync` feature.
587 #[cfg(feature = "sync")]
588 pub fn check_version_sync(&self, minimum: &CliVersion) -> Result<CliVersion> {
589 let version = self.cli_version_sync()?;
590 if version.satisfies_minimum(minimum) {
591 Ok(version)
592 } else {
593 Err(Error::VersionMismatch {
594 found: version,
595 minimum: *minimum,
596 })
597 }
598 }
599
600 /// The tested-against `[min, max]` range declared at build time
601 /// via [`ClaudeBuilder::tested_cli_version_range`], if any.
602 ///
603 /// `None` means no override was set, in which case version checks
604 /// use the crate's own [`TESTED_CLI_VERSION_MIN`] /
605 /// [`TESTED_CLI_VERSION_MAX`]; see [`Self::effective_tested_range`].
606 #[must_use]
607 pub fn tested_cli_version_range(&self) -> Option<(CliVersion, CliVersion)> {
608 self.tested_cli_version_range
609 }
610
611 /// The range version checks actually use: the caller's override when one
612 /// was set, otherwise the crate's own declared range.
613 #[must_use]
614 pub fn effective_tested_range(&self) -> (CliVersion, CliVersion) {
615 self.tested_cli_version_range
616 .unwrap_or((TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX))
617 }
618
619 /// Classify the installed CLI against the tested-against range.
620 /// Logs a `tracing::warn!` when outside the range; returns the
621 /// typed status either way.
622 ///
623 /// The range defaults to the crate's own
624 /// [`TESTED_CLI_VERSION_MIN`] / [`TESTED_CLI_VERSION_MAX`],
625 /// because only the crate knows what it was built and tested
626 /// against. [`ClaudeBuilder::tested_cli_version_range`] overrides
627 /// it for hosts that have verified a different range themselves.
628 ///
629 /// Intended for one-shot use at startup, not on every command.
630 #[cfg(feature = "async")]
631 pub async fn cli_version_status(&self) -> Result<CliVersionStatus> {
632 let (min, max) = self.effective_tested_range();
633 let found = self.cli_version().await?;
634 let status = found.status_within(&min, &max);
635 warn_on_drift(&status);
636 Ok(status)
637 }
638
639 /// Blocking mirror of [`Claude::cli_version_status`]. Requires
640 /// the `sync` feature.
641 #[cfg(feature = "sync")]
642 pub fn cli_version_status_sync(&self) -> Result<CliVersionStatus> {
643 let (min, max) = self.effective_tested_range();
644 let found = self.cli_version_sync()?;
645 let status = found.status_within(&min, &max);
646 warn_on_drift(&status);
647 Ok(status)
648 }
649
650 /// Refuse to proceed against a CLI outside the tested range.
651 ///
652 /// The opt-in hard gate. [`Claude::cli_version_status`] is the
653 /// reporting path and keeps its behavior: it returns a typed
654 /// status and warns. This one turns the same condition into
655 /// [`Error::UntestedCliVersion`], for hosts that would rather fail
656 /// at startup than run on an unverified binary.
657 ///
658 /// Returns the detected version on success. The drift warning
659 /// still fires on the failure path, so a host that logs and a host
660 /// that gates see the same line.
661 ///
662 /// # Why this is a method and not a builder option
663 ///
664 /// [`ClaudeBuilder::build`] is synchronous and never spawns the
665 /// binary. Enforcing a version there would mean running a
666 /// subprocess inside a constructor, so the check lives where the
667 /// caller can await it.
668 ///
669 /// # Example
670 ///
671 /// ```no_run
672 /// # async fn example() -> claude_wrapper::Result<()> {
673 /// let claude = claude_wrapper::Claude::builder().build()?;
674 /// // Run once at startup; returns Err on an untested CLI.
675 /// let version = claude.ensure_tested_cli_version().await?;
676 /// println!("running against {version}");
677 /// # Ok(())
678 /// # }
679 /// ```
680 #[cfg(feature = "async")]
681 pub async fn ensure_tested_cli_version(&self) -> Result<CliVersion> {
682 let (min, max) = self.effective_tested_range();
683 let found = self.cli_version().await?;
684 self.gate_version(found, min, max)
685 }
686
687 /// Blocking mirror of [`Claude::ensure_tested_cli_version`].
688 /// Requires the `sync` feature.
689 #[cfg(feature = "sync")]
690 pub fn ensure_tested_cli_version_sync(&self) -> Result<CliVersion> {
691 let (min, max) = self.effective_tested_range();
692 let found = self.cli_version_sync()?;
693 self.gate_version(found, min, max)
694 }
695
696 /// Shared decision for the async and sync gates, so the two cannot
697 /// disagree about what "outside the range" means.
698 #[cfg(any(feature = "async", feature = "sync"))]
699 fn gate_version(
700 &self,
701 found: CliVersion,
702 min: CliVersion,
703 max: CliVersion,
704 ) -> Result<CliVersion> {
705 let status = found.status_within(&min, &max);
706 warn_on_drift(&status);
707 if status.is_tested() {
708 Ok(found)
709 } else {
710 Err(Error::UntestedCliVersion {
711 found,
712 tested_min: min,
713 tested_max: max,
714 })
715 }
716 }
717}
718
719#[allow(dead_code)] // unused with neither `async` nor `sync` feature
720fn warn_on_drift(status: &CliVersionStatus) {
721 match status {
722 CliVersionStatus::Tested => {}
723 CliVersionStatus::NewerUntested {
724 found, tested_max, ..
725 } => {
726 tracing::warn!(
727 found = %found,
728 tested_max = %tested_max,
729 "claude CLI is newer than the wrapper's tested-against range; \
730 semantics may have drifted -- proceed with caution"
731 );
732 }
733 CliVersionStatus::OlderThanMinimum { found, minimum, .. } => {
734 tracing::warn!(
735 found = %found,
736 minimum = %minimum,
737 "claude CLI is older than the wrapper's declared minimum; \
738 incorrect behavior is likely (missing flags, different shapes)"
739 );
740 }
741 }
742}
743
744/// Builder for creating a [`Claude`] client.
745///
746/// # Example
747///
748/// ```no_run
749/// use claude_wrapper::Claude;
750///
751/// # fn example() -> claude_wrapper::Result<()> {
752/// let claude = Claude::builder()
753/// .env("AWS_REGION", "us-west-2")
754/// .timeout_secs(120)
755/// .build()?;
756/// # Ok(())
757/// # }
758/// ```
759#[derive(Default)]
760pub struct ClaudeBuilder {
761 binary: Option<PathBuf>,
762 working_dir: Option<PathBuf>,
763 env: HashMap<String, String>,
764 clear_env: bool,
765 global_args: Vec<String>,
766 timeout: Option<Duration>,
767 retry_policy: Option<RetryPolicy>,
768 tested_cli_version_range: Option<(CliVersion, CliVersion)>,
769 process_group: Option<bool>,
770 kill_grace: Option<Duration>,
771 output_limit: Option<usize>,
772 on_spawn: Option<SpawnObserver>,
773 die_with_parent: bool,
774}
775
776impl std::fmt::Debug for ClaudeBuilder {
777 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
778 // Mirrors Claude's Debug: a closure cannot be rendered and env may
779 // hold credentials, so neither is printed.
780 f.debug_struct("ClaudeBuilder")
781 .field("binary", &self.binary)
782 .field("working_dir", &self.working_dir)
783 .field("clear_env", &self.clear_env)
784 .field("global_args", &self.global_args)
785 .field("timeout", &self.timeout)
786 .field("process_group", &self.process_group)
787 .field("kill_grace", &self.kill_grace)
788 .field("output_limit", &self.output_limit)
789 .field("on_spawn", &self.on_spawn.is_some())
790 .finish_non_exhaustive()
791 }
792}
793
794impl ClaudeBuilder {
795 /// Set the path to the claude binary.
796 ///
797 /// If not set, the binary is resolved from PATH using `which`.
798 #[must_use]
799 pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
800 self.binary = Some(path.into());
801 self
802 }
803
804 /// Set the working directory for all commands.
805 ///
806 /// The spawned process will use this as its current directory.
807 #[must_use]
808 pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
809 self.working_dir = Some(path.into());
810 self
811 }
812
813 /// Add an environment variable to pass to all commands.
814 #[must_use]
815 pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
816 self.env.insert(key.into(), value.into());
817 self
818 }
819
820 /// Add multiple environment variables.
821 #[must_use]
822 pub fn envs(
823 mut self,
824 vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
825 ) -> Self {
826 for (k, v) in vars {
827 self.env.insert(k.into(), v.into());
828 }
829 self
830 }
831
832 /// Clear the inherited environment of every spawned Claude CLI child.
833 ///
834 /// By default, children inherit the parent process environment and
835 /// [`env`](Self::env) / [`envs`](Self::envs) add or replace entries. With
836 /// this option enabled, the inherited environment is cleared first and
837 /// only explicitly configured entries are applied. The order in which
838 /// `clear_env`, `env`, and `envs` are called does not affect the result.
839 ///
840 /// Callers normally need to rebuild a minimal environment including
841 /// `PATH`, locale settings, the Claude config directory, and the intended
842 /// authentication selector.
843 ///
844 /// This controls only the direct child process environment. It is not an
845 /// operating-system sandbox and does not prevent a same-UID child from
846 /// reading accessible files or inspecting other processes where the OS
847 /// permits it.
848 ///
849 /// # Example
850 ///
851 /// ```no_run
852 /// use claude_wrapper::Claude;
853 ///
854 /// # fn example() -> claude_wrapper::Result<()> {
855 /// let claude = Claude::builder()
856 /// .clear_env()
857 /// .env("PATH", "/usr/local/bin:/usr/bin:/bin")
858 /// .env("CLAUDE_CONFIG_DIR", "/srv/claude/config")
859 /// .build()?;
860 /// # Ok(())
861 /// # }
862 /// ```
863 #[must_use]
864 pub fn clear_env(mut self) -> Self {
865 self.clear_env = true;
866 self
867 }
868
869 /// Set a default timeout for all commands (in seconds).
870 #[must_use]
871 pub fn timeout_secs(mut self, seconds: u64) -> Self {
872 self.timeout = Some(Duration::from_secs(seconds));
873 self
874 }
875
876 /// Set a default timeout for all commands.
877 #[must_use]
878 pub fn timeout(mut self, duration: Duration) -> Self {
879 self.timeout = Some(duration);
880 self
881 }
882
883 /// Add a global argument applied to all commands.
884 ///
885 /// This is an escape hatch for flags not yet covered by the API.
886 #[must_use]
887 pub fn arg(mut self, arg: impl Into<String>) -> Self {
888 self.global_args.push(arg.into());
889 self
890 }
891
892 /// Enable verbose output for all commands (`--verbose`).
893 #[must_use]
894 pub fn verbose(mut self) -> Self {
895 self.global_args.push("--verbose".into());
896 self
897 }
898
899 /// Enable debug output for all commands (`--debug`).
900 #[must_use]
901 pub fn debug(mut self) -> Self {
902 self.global_args.push("--debug".into());
903 self
904 }
905
906 /// Set a default retry policy for all commands.
907 ///
908 /// Individual commands can override this via their own retry settings.
909 ///
910 /// # Example
911 ///
912 /// ```no_run
913 /// use claude_wrapper::{Claude, RetryPolicy};
914 /// use std::time::Duration;
915 ///
916 /// # fn example() -> claude_wrapper::Result<()> {
917 /// let claude = Claude::builder()
918 /// .retry(RetryPolicy::new()
919 /// .max_attempts(3)
920 /// .initial_backoff(Duration::from_secs(2))
921 /// .exponential()
922 /// .retry_on_timeout(true))
923 /// .build()?;
924 /// # Ok(())
925 /// # }
926 /// ```
927 #[must_use]
928 pub fn retry(mut self, policy: RetryPolicy) -> Self {
929 self.retry_policy = Some(policy);
930 self
931 }
932
933 /// Declare the inclusive `[min, max]` range of `claude` CLI
934 /// versions this client has been tested against.
935 ///
936 /// The wrapper does not enforce the range -- nothing errors when
937 /// it's set wrong. Use [`Claude::cli_version_status`] (or its
938 /// sync mirror) at startup to classify the actually-installed CLI
939 /// against this declaration; that call returns a typed
940 /// [`CliVersionStatus`] AND emits a `tracing::warn!` when
941 /// outside the range. Hosts (claude-server, application code)
942 /// can additionally surface the status to operators.
943 ///
944 /// # Why this exists
945 ///
946 /// CLI semantics drift across minor / patch releases (e.g.
947 /// `claude agents` was repurposed in 2.1.143). The min floor
948 /// lets us say "we know it's broken below this"; the max ceiling
949 /// lets us say "we haven't verified above this -- proceed but
950 /// expect surprises."
951 ///
952 /// # You usually do not need this
953 ///
954 /// The crate declares its own range in
955 /// [`TESTED_CLI_VERSION_MIN`] / [`TESTED_CLI_VERSION_MAX`], and
956 /// version checks use it by default, because only the crate knows
957 /// what it was built and tested against. Set this only when a host
958 /// has verified a different range itself.
959 ///
960 /// # Example
961 ///
962 /// ```no_run
963 /// use claude_wrapper::{Claude, CliVersion};
964 ///
965 /// # async fn example() -> claude_wrapper::Result<()> {
966 /// let claude = Claude::builder()
967 /// .tested_cli_version_range(CliVersion::new(2, 1, 0), CliVersion::new(2, 1, 999))
968 /// .build()?;
969 /// // Run once at startup to log a warning if the CLI is out of range.
970 /// let _status = claude.cli_version_status().await?;
971 /// # Ok(()) }
972 /// ```
973 #[must_use]
974 pub fn tested_cli_version_range(mut self, min: CliVersion, max: CliVersion) -> Self {
975 self.tested_cli_version_range = Some((min, max));
976 self
977 }
978
979 /// Control whether spawned `claude` children are placed in their
980 /// own process group on Unix. Defaults to `true`.
981 ///
982 /// Own group (the default): cancellation and timeouts kill the
983 /// child's whole process tree, but the child no longer shares the
984 /// host terminal's process group, so terminal-generated signals
985 /// (Ctrl-C) do not reach it; terminating a run is the wrapper's
986 /// job via drop, timeout, or explicit kill. This is the right
987 /// contract for supervisors (daemons, MCP servers, worker queues).
988 ///
989 /// Shared group (`false`): the child stays in the host's process
990 /// group, so a terminal Ctrl-C reaches the whole run directly, but
991 /// a wrapper-side kill only reaches the direct child and any
992 /// subprocesses it spawned for tool use survive it. This is the
993 /// right contract for terminal-attached hosts that shell out
994 /// synchronously and rely on the terminal as the supervisor.
995 ///
996 /// No effect on non-Unix targets.
997 #[must_use]
998 pub fn process_group(mut self, enabled: bool) -> Self {
999 self.process_group = Some(enabled);
1000 self
1001 }
1002
1003 /// Grace period between SIGTERM and SIGKILL when a run is killed
1004 /// by a timeout or a duplex shutdown overrun (Unix). Default:
1005 /// none; kills are immediate SIGKILL.
1006 ///
1007 /// With a grace set, the child's whole process group gets SIGTERM
1008 /// first so `claude` can flush its transcript and session state,
1009 /// and SIGKILL follows once the grace elapses. The full grace is
1010 /// waited before the timeout error returns, so keep it short
1011 /// (500ms to 2s). Dropping a future cannot wait, so drop-path
1012 /// cancellation stays immediate SIGKILL, and the grace applies
1013 /// only while the child is in its own process group (see
1014 /// [`process_group`](Self::process_group)).
1015 #[must_use]
1016 pub fn kill_grace(mut self, grace: Duration) -> Self {
1017 self.kill_grace = Some(grace);
1018 self
1019 }
1020
1021 /// Ceiling, in bytes, on stdout and stderr captured from a buffered
1022 /// run. Default: none; capture grows to whatever the child prints.
1023 ///
1024 /// The limit applies to each stream independently, so a client with
1025 /// a 1 MiB ceiling holds at most 2 MiB across the pair. Reaching it
1026 /// on either stream terminates the child's process group (honoring
1027 /// [`kill_grace`](Self::kill_grace)), reaps the direct child, and
1028 /// returns [`Error::OutputLimitExceeded`] rather than a truncated
1029 /// success: continuing to read past the ceiling would defeat the
1030 /// bound, and presenting a partial answer as a complete one is worse
1031 /// than failing. Output captured before the ceiling tripped is
1032 /// logged at warn.
1033 ///
1034 /// This bounds the buffered paths (`execute`, `execute_json`, and
1035 /// their cancellable and blocking forms). Streaming runs deliver
1036 /// events as they arrive and are not affected.
1037 #[must_use]
1038 pub fn output_limit(mut self, bytes: usize) -> Self {
1039 self.output_limit = Some(bytes);
1040 self
1041 }
1042
1043 /// Observe every child this client spawns, at spawn time.
1044 ///
1045 /// The observer receives a [`SpawnInfo`] before the run produces output,
1046 /// which is what makes it useful to a supervisor: recording the pid only
1047 /// once a run *finishes* leaves nothing to reconcile after a crash
1048 /// mid-run. Fires for one-shot runs, streaming runs, and duplex sessions
1049 /// alike, and on retry it fires once per attempt, since each attempt is a
1050 /// distinct process.
1051 ///
1052 /// The observer runs inline on the spawning thread, so it must not block.
1053 /// Write a pidfile or push to a channel; do not do I/O that can stall.
1054 ///
1055 /// # Why a callback rather than a return value
1056 ///
1057 /// The crash case needs the pid to be durable *before* the run can be
1058 /// orphaned. A pid on the result type arrives too late for exactly the
1059 /// scenario that motivates recording it.
1060 ///
1061 /// # Example
1062 ///
1063 /// ```no_run
1064 /// use std::sync::Arc;
1065 /// use claude_wrapper::Claude;
1066 ///
1067 /// # fn example() -> claude_wrapper::Result<()> {
1068 /// let claude = Claude::builder()
1069 /// .on_spawn(Arc::new(|info| {
1070 /// eprintln!("spawned pid {} (group {:?})", info.pid, info.pgid);
1071 /// }))
1072 /// .build()?;
1073 /// # Ok(())
1074 /// # }
1075 /// ```
1076 #[must_use]
1077 pub fn on_spawn(mut self, observer: SpawnObserver) -> Self {
1078 self.on_spawn = Some(observer);
1079 self
1080 }
1081
1082 /// Ask the kernel to kill spawned children when this process dies.
1083 ///
1084 /// **Linux only.** Check [`die_with_parent_supported`](crate::exec::die_with_parent_supported)
1085 /// rather than assuming; elsewhere this is accepted and does nothing.
1086 ///
1087 /// # The problem it addresses
1088 ///
1089 /// Every other cleanup path in this crate is a destructor: `kill_on_drop`,
1090 /// and the process-group kill on drop, timeout, or stream error. None of
1091 /// them run when *this* process is SIGKILLed. The child is then reparented
1092 /// to init, and because it leads its own process group (see
1093 /// [`process_group`](Self::process_group)) terminal signals cannot reach it
1094 /// either. It keeps running, keeps billing, and keeps appending to the
1095 /// session transcript, so a restarted supervisor that resumes the same
1096 /// session id can find itself interleaving with an orphan still writing.
1097 ///
1098 /// On Linux `PR_SET_PDEATHSIG` closes that: the kernel delivers SIGKILL to
1099 /// the child the moment its parent dies, with no cooperation from either
1100 /// side.
1101 ///
1102 /// # What it does not cover
1103 ///
1104 /// - **Non-Linux targets.** macOS has no equivalent. A supervisor that
1105 /// needs the guarantee there has to poll and kill by pid; recording the
1106 /// pid is what [`on_spawn`](Self::on_spawn) is for.
1107 /// - **Re-parenting.** The signal fires when the *immediate* parent dies.
1108 /// If the crate's caller is itself an intermediate process that exits
1109 /// normally, the child dies then, which is usually what you want but is
1110 /// worth knowing if you daemonize between building the client and
1111 /// spawning.
1112 /// - **The fork/prctl window.** Handled: the hook re-checks `getppid()`
1113 /// after arming and exits if the parent already changed. Without that
1114 /// check a parent dying in that window leaves exactly the orphan this
1115 /// option exists to prevent.
1116 ///
1117 /// Off by default, because killing children on parent exit is the right
1118 /// default for a supervisor and the wrong one for a CLI that deliberately
1119 /// backgrounds work.
1120 #[must_use]
1121 pub fn die_with_parent(mut self, enabled: bool) -> Self {
1122 self.die_with_parent = enabled;
1123 self
1124 }
1125
1126 /// Build the Claude client, resolving the binary path.
1127 pub fn build(self) -> Result<Claude> {
1128 let binary = match self.binary {
1129 Some(path) => path,
1130 None => which::which("claude").map_err(|_| Error::NotFound)?,
1131 };
1132
1133 Ok(Claude {
1134 binary,
1135 working_dir: self.working_dir,
1136 env: self.env,
1137 clear_env: self.clear_env,
1138 global_args: self.global_args,
1139 timeout: self.timeout,
1140 retry_policy: self.retry_policy,
1141 tested_cli_version_range: self.tested_cli_version_range,
1142 process_group: self.process_group.unwrap_or(true),
1143 kill_grace: self.kill_grace,
1144 output_limit: self.output_limit,
1145 on_spawn: self.on_spawn,
1146 die_with_parent: self.die_with_parent,
1147 })
1148 }
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153 use super::*;
1154
1155 #[test]
1156 fn builder_process_group_defaults_on_and_can_opt_out() {
1157 let on = Claude::builder()
1158 .binary("/nonexistent/claude")
1159 .build()
1160 .unwrap();
1161 assert!(on.process_group);
1162
1163 let off = Claude::builder()
1164 .binary("/nonexistent/claude")
1165 .process_group(false)
1166 .build()
1167 .unwrap();
1168 assert!(!off.process_group);
1169 }
1170
1171 #[test]
1172 fn builder_clear_env_defaults_off_and_is_call_order_independent() {
1173 let inherited = Claude::builder()
1174 .binary("/nonexistent/claude")
1175 .build()
1176 .unwrap();
1177 assert!(!inherited.clear_env);
1178
1179 let cleared = Claude::builder()
1180 .binary("/nonexistent/claude")
1181 .env("FIRST", "1")
1182 .clear_env()
1183 .env("SECOND", "2")
1184 .build()
1185 .unwrap();
1186 assert!(cleared.clear_env);
1187 assert_eq!(cleared.env.get("FIRST").map(String::as_str), Some("1"));
1188 assert_eq!(cleared.env.get("SECOND").map(String::as_str), Some("2"));
1189 }
1190
1191 #[test]
1192 fn builder_kill_grace_defaults_off_and_can_be_set() {
1193 let off = Claude::builder()
1194 .binary("/nonexistent/claude")
1195 .build()
1196 .unwrap();
1197 assert!(off.kill_grace.is_none());
1198
1199 let on = Claude::builder()
1200 .binary("/nonexistent/claude")
1201 .kill_grace(Duration::from_millis(750))
1202 .build()
1203 .unwrap();
1204 assert_eq!(on.kill_grace, Some(Duration::from_millis(750)));
1205 }
1206
1207 // -- the version gate ------------------------------------------
1208 //
1209 // `gate_version` is the decision both the async and sync gates
1210 // share, and it takes the version rather than fetching it, so the
1211 // policy is testable without spawning a binary.
1212
1213 #[cfg(any(feature = "async", feature = "sync"))]
1214 fn gate(found: (u32, u32, u32)) -> Result<CliVersion> {
1215 let claude = Claude::builder()
1216 .binary("/nonexistent/claude")
1217 .build()
1218 .unwrap();
1219 let (min, max) = claude.effective_tested_range();
1220 claude.gate_version(CliVersion::new(found.0, found.1, found.2), min, max)
1221 }
1222
1223 #[cfg(any(feature = "async", feature = "sync"))]
1224 #[test]
1225 fn gate_accepts_a_version_inside_the_declared_range() {
1226 let found = gate((
1227 TESTED_CLI_VERSION_MIN.major,
1228 TESTED_CLI_VERSION_MIN.minor,
1229 TESTED_CLI_VERSION_MIN.patch,
1230 ))
1231 .expect("the declared minimum must pass its own gate");
1232 assert_eq!(found, TESTED_CLI_VERSION_MIN);
1233 }
1234
1235 #[cfg(any(feature = "async", feature = "sync"))]
1236 #[test]
1237 fn gate_rejects_older_than_minimum_with_both_bounds() {
1238 let err = gate((1, 0, 0)).expect_err("1.0.0 is below any supported floor");
1239 match err {
1240 Error::UntestedCliVersion {
1241 found,
1242 tested_min,
1243 tested_max,
1244 } => {
1245 assert_eq!(found, CliVersion::new(1, 0, 0));
1246 assert_eq!(tested_min, TESTED_CLI_VERSION_MIN);
1247 assert_eq!(tested_max, TESTED_CLI_VERSION_MAX);
1248 // The message must say which side it fell off, since
1249 // "too old" and "too new" call for opposite fixes.
1250 assert!(err_text(&err).contains("older"), "{}", err_text(&err));
1251 }
1252 other => panic!("expected UntestedCliVersion, got {other:?}"),
1253 }
1254 }
1255
1256 #[cfg(any(feature = "async", feature = "sync"))]
1257 #[test]
1258 fn gate_rejects_newer_than_maximum() {
1259 let err = gate((99, 0, 0)).expect_err("99.0.0 is above the tested ceiling");
1260 assert!(matches!(err, Error::UntestedCliVersion { .. }));
1261 assert!(err_text(&err).contains("newer"), "{}", err_text(&err));
1262 }
1263
1264 #[cfg(any(feature = "async", feature = "sync"))]
1265 #[test]
1266 fn gate_honours_a_caller_supplied_range_over_the_crate_default() {
1267 // A host that has verified a narrower window should be able to
1268 // enforce it, including rejecting versions the crate itself
1269 // considers fine.
1270 let claude = Claude::builder()
1271 .binary("/nonexistent/claude")
1272 .tested_cli_version_range(CliVersion::new(3, 0, 0), CliVersion::new(3, 0, 9))
1273 .build()
1274 .unwrap();
1275 let (min, max) = claude.effective_tested_range();
1276 assert_eq!(min, CliVersion::new(3, 0, 0));
1277 assert!(
1278 claude
1279 .gate_version(CliVersion::new(3, 0, 5), min, max)
1280 .is_ok()
1281 );
1282 assert!(
1283 claude
1284 .gate_version(TESTED_CLI_VERSION_MIN, min, max)
1285 .is_err(),
1286 "the caller's range must win over the crate's"
1287 );
1288 }
1289
1290 #[cfg(any(feature = "async", feature = "sync"))]
1291 fn err_text(e: &Error) -> String {
1292 e.to_string()
1293 }
1294
1295 #[test]
1296 fn test_builder_with_binary() {
1297 let claude = Claude::builder()
1298 .binary("/usr/local/bin/claude")
1299 .env("FOO", "bar")
1300 .timeout_secs(60)
1301 .build()
1302 .unwrap();
1303
1304 assert_eq!(claude.binary, PathBuf::from("/usr/local/bin/claude"));
1305 assert_eq!(claude.env.get("FOO").unwrap(), "bar");
1306 assert_eq!(claude.timeout, Some(Duration::from_secs(60)));
1307 }
1308
1309 #[test]
1310 fn test_builder_global_args() {
1311 let claude = Claude::builder()
1312 .binary("/usr/local/bin/claude")
1313 .arg("--verbose")
1314 .build()
1315 .unwrap();
1316
1317 assert_eq!(claude.global_args, vec!["--verbose"]);
1318 }
1319
1320 #[test]
1321 fn test_builder_verbose() {
1322 let claude = Claude::builder()
1323 .binary("/usr/local/bin/claude")
1324 .verbose()
1325 .build()
1326 .unwrap();
1327 assert!(claude.global_args.contains(&"--verbose".to_string()));
1328 }
1329
1330 #[test]
1331 fn test_builder_debug() {
1332 let claude = Claude::builder()
1333 .binary("/usr/local/bin/claude")
1334 .debug()
1335 .build()
1336 .unwrap();
1337 assert!(claude.global_args.contains(&"--debug".to_string()));
1338 }
1339}