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 | via [`Conversation`] ([`TurnResult`] reports the session's running total) | 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//! Hosts with an explicit stop signal can use
223//! [`streaming::stream_query_cancellable`], which settles process cleanup
224//! before returning [`Error::Cancelled`].
225//!
226//! ```no_run
227//! # #[cfg(all(feature = "async", feature = "json"))] {
228//! use claude_wrapper::{Claude, OutputFormat, QueryCommand};
229//! use claude_wrapper::streaming::{StreamEvent, stream_query};
230//!
231//! # async fn example() -> claude_wrapper::Result<()> {
232//! let claude = Claude::builder().build()?;
233//! let cmd = QueryCommand::new("explain quicksort")
234//! .output_format(OutputFormat::StreamJson);
235//!
236//! stream_query(&claude, &cmd, |event: StreamEvent| {
237//! if event.is_result() {
238//! println!("result: {}", event.result_text().unwrap_or(""));
239//! }
240//! }).await?;
241//! # Ok(()) }
242//! # }
243//! ```
244//!
245//! # MCP config generation
246//!
247//! Generate `.mcp.json` files for `--mcp-config`:
248//!
249//! ```no_run
250//! # #[cfg(feature = "async")] {
251//! use claude_wrapper::{Claude, ClaudeCommand, McpConfigBuilder, QueryCommand};
252//!
253//! # async fn example() -> claude_wrapper::Result<()> {
254//! McpConfigBuilder::new()
255//! .http_server("hub", "http://127.0.0.1:9090")
256//! .stdio_server("tool", "npx", ["my-server"])
257//! .write_to("/tmp/my-project/.mcp.json")?;
258//!
259//! let claude = Claude::builder().build()?;
260//! QueryCommand::new("list tools")
261//! .mcp_config("/tmp/my-project/.mcp.json")
262//! .execute(&claude)
263//! .await?;
264//! # Ok(()) }
265//! # }
266//! ```
267//!
268//! # On-disk introspection
269//!
270//! A family of read-only modules parses Claude Code's on-disk state
271//! under `~/.claude` directly, without spawning the CLI. Each exposes a
272//! root/loader with `list` / `get` accessors and degrades to an empty
273//! result when the directory is absent: [`history`] (sessions and
274//! transcripts), [`artifacts`] (agents), [`skills`], [`commands`]
275//! (custom slash commands), [`settings`] (the four merged layers),
276//! [`jobs`] (background-agent state), and [`worktrees`]. See the
277//! `inspect_state` example for an end-to-end tour.
278//!
279//! ```no_run
280//! # #[cfg(feature = "json")] {
281//! use claude_wrapper::history::HistoryRoot;
282//!
283//! # fn example() -> claude_wrapper::Result<()> {
284//! let history = HistoryRoot::home()?;
285//! for project in history.list_projects()? {
286//! println!(
287//! "{} ({} sessions)",
288//! project.decoded_path.display(),
289//! project.session_count,
290//! );
291//! }
292//! # Ok(()) }
293//! # }
294//! ```
295//!
296//! # Dangerous: bypass mode
297//!
298//! `--permission-mode bypassPermissions` is isolated behind
299//! [`dangerous::DangerousClient`], which requires an env-var
300//! acknowledgement ([`dangerous::ALLOW_ENV`] = `"1"`) at process start.
301//! See the [dangerous module docs](dangerous) for details.
302//!
303//! # Escape hatch
304//!
305//! For subcommands not yet wrapped, use [`RawCommand`]:
306//!
307//! ```no_run
308//! # #[cfg(feature = "async")] {
309//! use claude_wrapper::{Claude, ClaudeCommand, RawCommand};
310//!
311//! # async fn example() -> claude_wrapper::Result<()> {
312//! let claude = Claude::builder().build()?;
313//! let output = RawCommand::new("some-future-command")
314//! .arg("--new-flag")
315//! .arg("value")
316//! .execute(&claude)
317//! .await?;
318//! # Ok(()) }
319//! # }
320//! ```
321#![warn(missing_docs)]
322
323pub mod artifacts;
324pub mod auth;
325pub mod budget;
326/// Per-subcommand builders and the [`command::ClaudeCommand`] trait.
327pub mod command;
328pub mod commands;
329#[cfg(all(feature = "json", feature = "async"))]
330pub mod conversation;
331pub mod dangerous;
332#[cfg(all(feature = "json", feature = "async"))]
333pub mod duplex;
334pub mod error;
335pub mod exec;
336#[cfg(feature = "json")]
337pub mod history;
338#[cfg(feature = "json")]
339pub mod jobs;
340pub mod mcp_config;
341pub mod memory;
342pub mod plans;
343pub mod retry;
344#[cfg(all(feature = "json", feature = "async"))]
345pub mod session;
346#[cfg(feature = "json")]
347pub mod sessions;
348#[cfg(feature = "json")]
349pub mod settings;
350pub mod skills;
351pub mod slash;
352pub mod streaming;
353#[cfg(feature = "json")]
354pub mod tasks;
355pub mod tool_pattern;
356pub mod types;
357pub mod version;
358pub mod worktrees;
359
360use std::collections::HashMap;
361use std::path::{Path, PathBuf};
362use std::time::Duration;
363
364pub use budget::{BudgetBuilder, BudgetTracker};
365pub use command::ClaudeCommand;
366#[cfg(feature = "sync")]
367pub use command::ClaudeCommandSyncExt;
368#[allow(deprecated)]
369pub use command::agents::AgentsCommand;
370pub use command::auth::{
371 AuthLoginCommand, AuthLogoutCommand, AuthStatusCommand, LoginMode, SetupTokenCommand,
372};
373pub use command::auto_mode::{
374 AutoModeConfigCommand, AutoModeCritiqueCommand, AutoModeDefaultsCommand,
375};
376pub use command::doctor::DoctorCommand;
377pub use command::install::InstallCommand;
378pub use command::marketplace::{
379 MarketplaceAddCommand, MarketplaceListCommand, MarketplaceRemoveCommand,
380 MarketplaceUpdateCommand,
381};
382pub use command::mcp::{
383 McpAddCommand, McpAddFromDesktopCommand, McpAddJsonCommand, McpGetCommand, McpListCommand,
384 McpLoginCommand, McpLogoutCommand, McpRemoveCommand, McpResetProjectChoicesCommand,
385 McpServeCommand,
386};
387pub use command::plugin::{
388 PluginDetailsCommand, PluginDisableCommand, PluginEnableCommand, PluginInstallCommand,
389 PluginListCommand, PluginPruneCommand, PluginTagCommand, PluginUninstallCommand,
390 PluginUpdateCommand, PluginValidateCommand,
391};
392pub use command::project::ProjectPurgeCommand;
393pub use command::query::QueryCommand;
394pub use command::raw::RawCommand;
395pub use command::ultrareview::UltrareviewCommand;
396pub use command::update::UpdateCommand;
397pub use command::version::VersionCommand;
398#[cfg(all(feature = "json", feature = "async"))]
399pub use conversation::Conversation;
400#[cfg(all(feature = "json", feature = "async"))]
401pub use duplex::{
402 DuplexOptions, DuplexSession, InboundEvent, PermissionDecision, PermissionHandler,
403 PermissionRequest, TurnResult,
404};
405pub use error::{Error, OutputStream, Result};
406pub use exec::CommandOutput;
407#[cfg(feature = "tempfile")]
408pub use mcp_config::TempMcpConfig;
409pub use mcp_config::{McpConfigBuilder, McpServerConfig};
410pub use retry::{BackoffStrategy, RetryPolicy};
411#[cfg(all(feature = "json", feature = "async"))]
412pub use session::Session;
413pub use tool_pattern::{PatternError, ToolPattern};
414pub use types::*;
415pub use version::{
416 CliVersion, CliVersionStatus, TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN, VersionParseError,
417};
418
419/// What the crate knows about a child the moment it is spawned.
420///
421/// Delivered to the [`ClaudeBuilder::on_spawn`] observer before the run can
422/// produce output, which is the point: a supervisor that records the pid only
423/// after a run *finishes* has nothing to reconcile when it crashes mid-run.
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425#[non_exhaustive]
426pub struct SpawnInfo {
427 /// The child's process id.
428 pub pid: u32,
429 /// The child's process group id, when it leads its own group.
430 ///
431 /// `None` when [`ClaudeBuilder::process_group`] is disabled, in which case
432 /// the child shares the parent's group and its pid must never be passed to
433 /// `killpg`: that would signal the caller's own process group.
434 pub pgid: Option<u32>,
435}
436
437/// Called with [`SpawnInfo`] each time the crate spawns a CLI child.
438///
439/// Must not block: it runs inline on the spawning thread, between `spawn` and
440/// the first read of the child's output.
441pub type SpawnObserver = std::sync::Arc<dyn Fn(SpawnInfo) + Send + Sync>;
442
443/// Signal sent before the configured [`ClaudeBuilder::kill_grace`] elapses.
444///
445/// Applies only to awaited shutdown on Unix with an owned process group and
446/// nonzero grace. Dropping a future always uses immediate SIGKILL.
447#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
448pub enum TerminationSignal {
449 /// Send SIGTERM, the default graceful termination signal.
450 #[default]
451 Terminate,
452 /// Send SIGINT so the CLI can cancel tools before exiting.
453 Interrupt,
454}
455
456/// The Claude CLI client. Holds shared configuration applied to all commands.
457///
458/// Create one via [`Claude::builder()`] and reuse it across commands.
459#[derive(Clone)]
460pub struct Claude {
461 pub(crate) binary: PathBuf,
462 pub(crate) working_dir: Option<PathBuf>,
463 // env, timeout, and retry_policy are written by the builder under
464 // every feature combination but read only by the feature-gated
465 // exec paths, so they are "never read" with neither `async` nor
466 // `sync` feature.
467 #[allow(dead_code)]
468 pub(crate) env: HashMap<String, String>,
469 #[allow(dead_code)]
470 pub(crate) clear_env: bool,
471 pub(crate) global_args: Vec<String>,
472 #[allow(dead_code)]
473 pub(crate) timeout: Option<Duration>,
474 #[allow(dead_code)]
475 pub(crate) retry_policy: Option<RetryPolicy>,
476 pub(crate) tested_cli_version_range: Option<(CliVersion, CliVersion)>,
477 // Read only by the feature-gated exec paths, like env/timeout.
478 #[allow(dead_code)]
479 pub(crate) process_group: bool,
480 #[allow(dead_code)]
481 pub(crate) kill_grace: Option<Duration>,
482 #[allow(dead_code)]
483 pub(crate) termination_signal: TerminationSignal,
484 #[allow(dead_code)]
485 pub(crate) output_limit: Option<usize>,
486 #[allow(dead_code)]
487 pub(crate) on_spawn: Option<SpawnObserver>,
488 #[allow(dead_code)]
489 pub(crate) die_with_parent: bool,
490}
491
492impl std::fmt::Debug for Claude {
493 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494 f.debug_struct("Claude")
495 .field("binary", &self.binary)
496 .field("working_dir", &self.working_dir)
497 .field("clear_env", &self.clear_env)
498 .field("global_args", &self.global_args)
499 .field("timeout", &self.timeout)
500 .field("process_group", &self.process_group)
501 .field("kill_grace", &self.kill_grace)
502 .field("termination_signal", &self.termination_signal)
503 .field("output_limit", &self.output_limit)
504 // A closure cannot be rendered, and env may hold credentials, so
505 // neither is printed: only whether an observer is installed.
506 .field("on_spawn", &self.on_spawn.is_some())
507 .finish_non_exhaustive()
508 }
509}
510
511impl Claude {
512 /// Create a new builder for configuring the Claude client.
513 #[must_use]
514 pub fn builder() -> ClaudeBuilder {
515 ClaudeBuilder::default()
516 }
517
518 /// Get the path to the claude binary.
519 #[must_use]
520 pub fn binary(&self) -> &Path {
521 &self.binary
522 }
523
524 /// Get the working directory, if set.
525 #[must_use]
526 pub fn working_dir(&self) -> Option<&Path> {
527 self.working_dir.as_deref()
528 }
529
530 /// Create a clone of this client with a different working directory.
531 #[must_use]
532 pub fn with_working_dir(&self, dir: impl Into<PathBuf>) -> Self {
533 let mut clone = self.clone();
534 clone.working_dir = Some(dir.into());
535 clone
536 }
537
538 /// Query the installed CLI version.
539 ///
540 /// Runs `claude --version` and parses the output into a [`CliVersion`].
541 ///
542 /// # Example
543 ///
544 /// ```no_run
545 /// # async fn example() -> claude_wrapper::Result<()> {
546 /// let claude = claude_wrapper::Claude::builder().build()?;
547 /// let version = claude.cli_version().await?;
548 /// println!("Claude CLI {version}");
549 /// # Ok(())
550 /// # }
551 /// ```
552 #[cfg(feature = "async")]
553 pub async fn cli_version(&self) -> Result<CliVersion> {
554 let output = VersionCommand::new().execute(self).await?;
555 CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
556 message: format!("failed to parse CLI version: {e}"),
557 source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
558 working_dir: None,
559 })
560 }
561
562 /// Check that the installed CLI version meets a minimum requirement.
563 ///
564 /// Returns the detected version on success, or an error if the version
565 /// is below the minimum.
566 ///
567 /// # Example
568 ///
569 /// ```no_run
570 /// use claude_wrapper::CliVersion;
571 ///
572 /// # async fn example() -> claude_wrapper::Result<()> {
573 /// let claude = claude_wrapper::Claude::builder().build()?;
574 /// let version = claude.check_version(&CliVersion::new(2, 1, 0)).await?;
575 /// println!("CLI version {version} meets minimum requirement");
576 /// # Ok(())
577 /// # }
578 /// ```
579 #[cfg(feature = "async")]
580 pub async fn check_version(&self, minimum: &CliVersion) -> Result<CliVersion> {
581 let version = self.cli_version().await?;
582 if version.satisfies_minimum(minimum) {
583 Ok(version)
584 } else {
585 Err(Error::VersionMismatch {
586 found: version,
587 minimum: *minimum,
588 })
589 }
590 }
591
592 /// Blocking mirror of [`Claude::cli_version`]. Requires the
593 /// `sync` feature.
594 #[cfg(feature = "sync")]
595 pub fn cli_version_sync(&self) -> Result<CliVersion> {
596 let output = VersionCommand::new().execute_sync(self)?;
597 CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
598 message: format!("failed to parse CLI version: {e}"),
599 source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
600 working_dir: None,
601 })
602 }
603
604 /// Blocking mirror of [`Claude::check_version`]. Requires the
605 /// `sync` feature.
606 #[cfg(feature = "sync")]
607 pub fn check_version_sync(&self, minimum: &CliVersion) -> Result<CliVersion> {
608 let version = self.cli_version_sync()?;
609 if version.satisfies_minimum(minimum) {
610 Ok(version)
611 } else {
612 Err(Error::VersionMismatch {
613 found: version,
614 minimum: *minimum,
615 })
616 }
617 }
618
619 /// The tested-against `[min, max]` range declared at build time
620 /// via [`ClaudeBuilder::tested_cli_version_range`], if any.
621 ///
622 /// `None` means no override was set, in which case version checks
623 /// use the crate's own [`TESTED_CLI_VERSION_MIN`] /
624 /// [`TESTED_CLI_VERSION_MAX`]; see [`Self::effective_tested_range`].
625 #[must_use]
626 pub fn tested_cli_version_range(&self) -> Option<(CliVersion, CliVersion)> {
627 self.tested_cli_version_range
628 }
629
630 /// The range version checks actually use: the caller's override when one
631 /// was set, otherwise the crate's own declared range.
632 #[must_use]
633 pub fn effective_tested_range(&self) -> (CliVersion, CliVersion) {
634 self.tested_cli_version_range
635 .unwrap_or((TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX))
636 }
637
638 /// Classify the installed CLI against the tested-against range.
639 /// Logs a `tracing::warn!` when outside the range; returns the
640 /// typed status either way.
641 ///
642 /// The range defaults to the crate's own
643 /// [`TESTED_CLI_VERSION_MIN`] / [`TESTED_CLI_VERSION_MAX`],
644 /// because only the crate knows what it was built and tested
645 /// against. [`ClaudeBuilder::tested_cli_version_range`] overrides
646 /// it for hosts that have verified a different range themselves.
647 ///
648 /// Intended for one-shot use at startup, not on every command.
649 #[cfg(feature = "async")]
650 pub async fn cli_version_status(&self) -> Result<CliVersionStatus> {
651 let (min, max) = self.effective_tested_range();
652 let found = self.cli_version().await?;
653 let status = found.status_within(&min, &max);
654 warn_on_drift(&status);
655 Ok(status)
656 }
657
658 /// Blocking mirror of [`Claude::cli_version_status`]. Requires
659 /// the `sync` feature.
660 #[cfg(feature = "sync")]
661 pub fn cli_version_status_sync(&self) -> Result<CliVersionStatus> {
662 let (min, max) = self.effective_tested_range();
663 let found = self.cli_version_sync()?;
664 let status = found.status_within(&min, &max);
665 warn_on_drift(&status);
666 Ok(status)
667 }
668
669 /// Refuse to proceed against a CLI outside the tested range.
670 ///
671 /// The opt-in hard gate. [`Claude::cli_version_status`] is the
672 /// reporting path and keeps its behavior: it returns a typed
673 /// status and warns. This one turns the same condition into
674 /// [`Error::UntestedCliVersion`], for hosts that would rather fail
675 /// at startup than run on an unverified binary.
676 ///
677 /// Returns the detected version on success. The drift warning
678 /// still fires on the failure path, so a host that logs and a host
679 /// that gates see the same line.
680 ///
681 /// # Why this is a method and not a builder option
682 ///
683 /// [`ClaudeBuilder::build`] is synchronous and never spawns the
684 /// binary. Enforcing a version there would mean running a
685 /// subprocess inside a constructor, so the check lives where the
686 /// caller can await it.
687 ///
688 /// # Example
689 ///
690 /// ```no_run
691 /// # async fn example() -> claude_wrapper::Result<()> {
692 /// let claude = claude_wrapper::Claude::builder().build()?;
693 /// // Run once at startup; returns Err on an untested CLI.
694 /// let version = claude.ensure_tested_cli_version().await?;
695 /// println!("running against {version}");
696 /// # Ok(())
697 /// # }
698 /// ```
699 #[cfg(feature = "async")]
700 pub async fn ensure_tested_cli_version(&self) -> Result<CliVersion> {
701 let (min, max) = self.effective_tested_range();
702 let found = self.cli_version().await?;
703 self.gate_version(found, min, max)
704 }
705
706 /// Blocking mirror of [`Claude::ensure_tested_cli_version`].
707 /// Requires the `sync` feature.
708 #[cfg(feature = "sync")]
709 pub fn ensure_tested_cli_version_sync(&self) -> Result<CliVersion> {
710 let (min, max) = self.effective_tested_range();
711 let found = self.cli_version_sync()?;
712 self.gate_version(found, min, max)
713 }
714
715 /// Shared decision for the async and sync gates, so the two cannot
716 /// disagree about what "outside the range" means.
717 #[cfg(any(feature = "async", feature = "sync"))]
718 fn gate_version(
719 &self,
720 found: CliVersion,
721 min: CliVersion,
722 max: CliVersion,
723 ) -> Result<CliVersion> {
724 let status = found.status_within(&min, &max);
725 warn_on_drift(&status);
726 if status.is_tested() {
727 Ok(found)
728 } else {
729 Err(Error::UntestedCliVersion {
730 found,
731 tested_min: min,
732 tested_max: max,
733 })
734 }
735 }
736}
737
738#[allow(dead_code)] // unused with neither `async` nor `sync` feature
739fn warn_on_drift(status: &CliVersionStatus) {
740 match status {
741 CliVersionStatus::Tested => {}
742 CliVersionStatus::NewerUntested {
743 found, tested_max, ..
744 } => {
745 tracing::warn!(
746 found = %found,
747 tested_max = %tested_max,
748 "claude CLI is newer than the wrapper's tested-against range; \
749 semantics may have drifted -- proceed with caution"
750 );
751 }
752 CliVersionStatus::OlderThanMinimum { found, minimum, .. } => {
753 tracing::warn!(
754 found = %found,
755 minimum = %minimum,
756 "claude CLI is older than the wrapper's declared minimum; \
757 incorrect behavior is likely (missing flags, different shapes)"
758 );
759 }
760 }
761}
762
763/// Builder for creating a [`Claude`] client.
764///
765/// # Example
766///
767/// ```no_run
768/// use claude_wrapper::Claude;
769///
770/// # fn example() -> claude_wrapper::Result<()> {
771/// let claude = Claude::builder()
772/// .env("AWS_REGION", "us-west-2")
773/// .timeout_secs(120)
774/// .build()?;
775/// # Ok(())
776/// # }
777/// ```
778#[derive(Default)]
779pub struct ClaudeBuilder {
780 binary: Option<PathBuf>,
781 working_dir: Option<PathBuf>,
782 env: HashMap<String, String>,
783 clear_env: bool,
784 global_args: Vec<String>,
785 timeout: Option<Duration>,
786 retry_policy: Option<RetryPolicy>,
787 tested_cli_version_range: Option<(CliVersion, CliVersion)>,
788 process_group: Option<bool>,
789 kill_grace: Option<Duration>,
790 termination_signal: TerminationSignal,
791 output_limit: Option<usize>,
792 on_spawn: Option<SpawnObserver>,
793 die_with_parent: bool,
794}
795
796impl std::fmt::Debug for ClaudeBuilder {
797 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
798 // Mirrors Claude's Debug: a closure cannot be rendered and env may
799 // hold credentials, so neither is printed.
800 f.debug_struct("ClaudeBuilder")
801 .field("binary", &self.binary)
802 .field("working_dir", &self.working_dir)
803 .field("clear_env", &self.clear_env)
804 .field("global_args", &self.global_args)
805 .field("timeout", &self.timeout)
806 .field("process_group", &self.process_group)
807 .field("kill_grace", &self.kill_grace)
808 .field("termination_signal", &self.termination_signal)
809 .field("output_limit", &self.output_limit)
810 .field("on_spawn", &self.on_spawn.is_some())
811 .finish_non_exhaustive()
812 }
813}
814
815impl ClaudeBuilder {
816 /// Set the path to the claude binary.
817 ///
818 /// If not set, the binary is resolved from PATH using `which`.
819 #[must_use]
820 pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
821 self.binary = Some(path.into());
822 self
823 }
824
825 /// Set the working directory for all commands.
826 ///
827 /// The spawned process will use this as its current directory.
828 #[must_use]
829 pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
830 self.working_dir = Some(path.into());
831 self
832 }
833
834 /// Add an environment variable to pass to all commands.
835 #[must_use]
836 pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
837 self.env.insert(key.into(), value.into());
838 self
839 }
840
841 /// Add multiple environment variables.
842 #[must_use]
843 pub fn envs(
844 mut self,
845 vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
846 ) -> Self {
847 for (k, v) in vars {
848 self.env.insert(k.into(), v.into());
849 }
850 self
851 }
852
853 /// Clear the inherited environment of every spawned Claude CLI child.
854 ///
855 /// By default, children inherit the parent process environment and
856 /// [`env`](Self::env) / [`envs`](Self::envs) add or replace entries. With
857 /// this option enabled, the inherited environment is cleared first and
858 /// only explicitly configured entries are applied. The order in which
859 /// `clear_env`, `env`, and `envs` are called does not affect the result.
860 ///
861 /// Callers normally need to rebuild a minimal environment including
862 /// `PATH`, locale settings, the Claude config directory, and the intended
863 /// authentication selector.
864 ///
865 /// This controls only the direct child process environment. It is not an
866 /// operating-system sandbox and does not prevent a same-UID child from
867 /// reading accessible files or inspecting other processes where the OS
868 /// permits it.
869 ///
870 /// # Example
871 ///
872 /// ```no_run
873 /// use claude_wrapper::Claude;
874 ///
875 /// # fn example() -> claude_wrapper::Result<()> {
876 /// let claude = Claude::builder()
877 /// .clear_env()
878 /// .env("PATH", "/usr/local/bin:/usr/bin:/bin")
879 /// .env("CLAUDE_CONFIG_DIR", "/srv/claude/config")
880 /// .build()?;
881 /// # Ok(())
882 /// # }
883 /// ```
884 #[must_use]
885 pub fn clear_env(mut self) -> Self {
886 self.clear_env = true;
887 self
888 }
889
890 /// Set a default timeout for all commands (in seconds).
891 #[must_use]
892 pub fn timeout_secs(mut self, seconds: u64) -> Self {
893 self.timeout = Some(Duration::from_secs(seconds));
894 self
895 }
896
897 /// Set a default timeout for all commands.
898 #[must_use]
899 pub fn timeout(mut self, duration: Duration) -> Self {
900 self.timeout = Some(duration);
901 self
902 }
903
904 /// Add a global argument applied to all commands.
905 ///
906 /// This is an escape hatch for flags not yet covered by the API.
907 #[must_use]
908 pub fn arg(mut self, arg: impl Into<String>) -> Self {
909 self.global_args.push(arg.into());
910 self
911 }
912
913 /// Enable verbose output for all commands (`--verbose`).
914 #[must_use]
915 pub fn verbose(mut self) -> Self {
916 self.global_args.push("--verbose".into());
917 self
918 }
919
920 /// Enable debug output for all commands (`--debug`).
921 #[must_use]
922 pub fn debug(mut self) -> Self {
923 self.global_args.push("--debug".into());
924 self
925 }
926
927 /// Set a default retry policy for all commands.
928 ///
929 /// Individual commands can override this via their own retry settings.
930 ///
931 /// # Example
932 ///
933 /// ```no_run
934 /// use claude_wrapper::{Claude, RetryPolicy};
935 /// use std::time::Duration;
936 ///
937 /// # fn example() -> claude_wrapper::Result<()> {
938 /// let claude = Claude::builder()
939 /// .retry(RetryPolicy::new()
940 /// .max_attempts(3)
941 /// .initial_backoff(Duration::from_secs(2))
942 /// .exponential()
943 /// .retry_on_timeout(true))
944 /// .build()?;
945 /// # Ok(())
946 /// # }
947 /// ```
948 #[must_use]
949 pub fn retry(mut self, policy: RetryPolicy) -> Self {
950 self.retry_policy = Some(policy);
951 self
952 }
953
954 /// Declare the inclusive `[min, max]` range of `claude` CLI
955 /// versions this client has been tested against.
956 ///
957 /// The wrapper does not enforce the range -- nothing errors when
958 /// it's set wrong. Use [`Claude::cli_version_status`] (or its
959 /// sync mirror) at startup to classify the actually-installed CLI
960 /// against this declaration; that call returns a typed
961 /// [`CliVersionStatus`] AND emits a `tracing::warn!` when
962 /// outside the range. Hosts (claude-server, application code)
963 /// can additionally surface the status to operators.
964 ///
965 /// # Why this exists
966 ///
967 /// CLI semantics drift across minor / patch releases (e.g.
968 /// `claude agents` was repurposed in 2.1.143). The min floor
969 /// lets us say "we know it's broken below this"; the max ceiling
970 /// lets us say "we haven't verified above this -- proceed but
971 /// expect surprises."
972 ///
973 /// # You usually do not need this
974 ///
975 /// The crate declares its own range in
976 /// [`TESTED_CLI_VERSION_MIN`] / [`TESTED_CLI_VERSION_MAX`], and
977 /// version checks use it by default, because only the crate knows
978 /// what it was built and tested against. Set this only when a host
979 /// has verified a different range itself.
980 ///
981 /// # Example
982 ///
983 /// ```no_run
984 /// use claude_wrapper::{Claude, CliVersion};
985 ///
986 /// # async fn example() -> claude_wrapper::Result<()> {
987 /// let claude = Claude::builder()
988 /// .tested_cli_version_range(CliVersion::new(2, 1, 0), CliVersion::new(2, 1, 999))
989 /// .build()?;
990 /// // Run once at startup to log a warning if the CLI is out of range.
991 /// let _status = claude.cli_version_status().await?;
992 /// # Ok(()) }
993 /// ```
994 #[must_use]
995 pub fn tested_cli_version_range(mut self, min: CliVersion, max: CliVersion) -> Self {
996 self.tested_cli_version_range = Some((min, max));
997 self
998 }
999
1000 /// Control whether spawned `claude` children are placed in their
1001 /// own process group on Unix. Defaults to `true`.
1002 ///
1003 /// Own group (the default): cancellation and timeouts kill the
1004 /// child's owned process group. Descendants that create another group
1005 /// require cooperative cleanup by the CLI. The child no longer shares the
1006 /// host terminal's process group, so terminal-generated signals
1007 /// (Ctrl-C) do not reach it; terminating a run is the wrapper's
1008 /// job via drop, timeout, or explicit kill. This is the right
1009 /// contract for supervisors (daemons, MCP servers, worker queues).
1010 ///
1011 /// Shared group (`false`): the child stays in the host's process
1012 /// group, so a terminal Ctrl-C reaches the whole run directly, but
1013 /// a wrapper-side kill only reaches the direct child and any
1014 /// subprocesses it spawned for tool use survive it. This is the
1015 /// right contract for terminal-attached hosts that shell out
1016 /// synchronously and rely on the terminal as the supervisor.
1017 ///
1018 /// No effect on non-Unix targets.
1019 #[must_use]
1020 pub fn process_group(mut self, enabled: bool) -> Self {
1021 self.process_group = Some(enabled);
1022 self
1023 }
1024
1025 /// Grace period before SIGKILL on timeout, explicit cancellation, or a
1026 /// duplex shutdown overrun (Unix). Default: none; kills are immediate.
1027 ///
1028 /// With nonzero grace, the owned process group first receives
1029 /// [`termination_signal`](Self::termination_signal), SIGTERM by default.
1030 /// Output is drained and discarded while the CLI gets a chance to clean
1031 /// up, then SIGKILL follows after the full grace. Keep the grace short
1032 /// (500ms to 2s). Detached descendants require cooperation from the CLI;
1033 /// group signals cannot guarantee their termination.
1034 ///
1035 /// Dropping a future cannot wait and always uses immediate SIGKILL.
1036 /// With [`process_group(false)`](Self::process_group), grace and the soft
1037 /// signal are skipped and only the direct child is killed.
1038 #[must_use]
1039 pub fn kill_grace(mut self, grace: Duration) -> Self {
1040 self.kill_grace = Some(grace);
1041 self
1042 }
1043
1044 /// Select the first signal for graceful shutdown. Defaults to SIGTERM.
1045 ///
1046 /// Requires nonzero [`kill_grace`](Self::kill_grace) and an owned Unix
1047 /// process group. SIGINT lets a cooperating CLI cancel its detached tools
1048 /// before the final group SIGKILL. Other platforms and drop cleanup are
1049 /// unchanged. Cancellation and timeout still return their original error
1050 /// even when the CLI exits successfully during this grace.
1051 ///
1052 /// ```no_run
1053 /// use claude_wrapper::{Claude, TerminationSignal};
1054 /// use std::time::Duration;
1055 /// # fn example() -> claude_wrapper::Result<()> {
1056 /// let claude = Claude::builder()
1057 /// .termination_signal(TerminationSignal::Interrupt)
1058 /// .kill_grace(Duration::from_secs(2))
1059 /// .build()?;
1060 /// # Ok(()) }
1061 /// ```
1062 #[must_use]
1063 pub fn termination_signal(mut self, signal: TerminationSignal) -> Self {
1064 self.termination_signal = signal;
1065 self
1066 }
1067
1068 /// Ceiling, in bytes, on stdout and stderr captured from a buffered
1069 /// run. Default: none; capture grows to whatever the child prints.
1070 ///
1071 /// The limit applies to each stream independently, so a client with
1072 /// a 1 MiB ceiling holds at most 2 MiB across the pair. Reaching it
1073 /// on either stream terminates the child's process group (honoring
1074 /// [`kill_grace`](Self::kill_grace)), reaps the direct child, and
1075 /// returns [`Error::OutputLimitExceeded`] rather than a truncated
1076 /// success: continuing to read past the ceiling would defeat the
1077 /// bound, and presenting a partial answer as a complete one is worse
1078 /// than failing. Output captured before the ceiling tripped is
1079 /// logged at warn.
1080 ///
1081 /// This bounds the buffered paths (`execute`, `execute_json`, and
1082 /// their cancellable and blocking forms). Streaming runs deliver
1083 /// events as they arrive and are not affected.
1084 #[must_use]
1085 pub fn output_limit(mut self, bytes: usize) -> Self {
1086 self.output_limit = Some(bytes);
1087 self
1088 }
1089
1090 /// Observe every child this client spawns, at spawn time.
1091 ///
1092 /// The observer receives a [`SpawnInfo`] before the run produces output,
1093 /// which is what makes it useful to a supervisor: recording the pid only
1094 /// once a run *finishes* leaves nothing to reconcile after a crash
1095 /// mid-run. Fires for one-shot runs, streaming runs, and duplex sessions
1096 /// alike, and on retry it fires once per attempt, since each attempt is a
1097 /// distinct process.
1098 ///
1099 /// The observer runs inline on the spawning thread, so it must not block.
1100 /// Write a pidfile or push to a channel; do not do I/O that can stall.
1101 ///
1102 /// # Why a callback rather than a return value
1103 ///
1104 /// The crash case needs the pid to be durable *before* the run can be
1105 /// orphaned. A pid on the result type arrives too late for exactly the
1106 /// scenario that motivates recording it.
1107 ///
1108 /// # Example
1109 ///
1110 /// ```no_run
1111 /// use std::sync::Arc;
1112 /// use claude_wrapper::Claude;
1113 ///
1114 /// # fn example() -> claude_wrapper::Result<()> {
1115 /// let claude = Claude::builder()
1116 /// .on_spawn(Arc::new(|info| {
1117 /// eprintln!("spawned pid {} (group {:?})", info.pid, info.pgid);
1118 /// }))
1119 /// .build()?;
1120 /// # Ok(())
1121 /// # }
1122 /// ```
1123 #[must_use]
1124 pub fn on_spawn(mut self, observer: SpawnObserver) -> Self {
1125 self.on_spawn = Some(observer);
1126 self
1127 }
1128
1129 /// Ask the kernel to kill spawned children when this process dies.
1130 ///
1131 /// **Linux only.** Check [`die_with_parent_supported`](crate::exec::die_with_parent_supported)
1132 /// rather than assuming; elsewhere this is accepted and does nothing.
1133 ///
1134 /// # The problem it addresses
1135 ///
1136 /// Every other cleanup path in this crate is a destructor: `kill_on_drop`,
1137 /// and the process-group kill on drop, timeout, or stream error. None of
1138 /// them run when *this* process is SIGKILLed. The child is then reparented
1139 /// to init, and because it leads its own process group (see
1140 /// [`process_group`](Self::process_group)) terminal signals cannot reach it
1141 /// either. It keeps running, keeps billing, and keeps appending to the
1142 /// session transcript, so a restarted supervisor that resumes the same
1143 /// session id can find itself interleaving with an orphan still writing.
1144 ///
1145 /// On Linux `PR_SET_PDEATHSIG` closes that: the kernel delivers SIGKILL to
1146 /// the child the moment its parent dies, with no cooperation from either
1147 /// side.
1148 ///
1149 /// # What it does not cover
1150 ///
1151 /// - **Non-Linux targets.** macOS has no equivalent. A supervisor that
1152 /// needs the guarantee there has to poll and kill by pid; recording the
1153 /// pid is what [`on_spawn`](Self::on_spawn) is for.
1154 /// - **Re-parenting.** The signal fires when the *immediate* parent dies.
1155 /// If the crate's caller is itself an intermediate process that exits
1156 /// normally, the child dies then, which is usually what you want but is
1157 /// worth knowing if you daemonize between building the client and
1158 /// spawning.
1159 /// - **The fork/prctl window.** Handled: the hook re-checks `getppid()`
1160 /// after arming and exits if the parent already changed. Without that
1161 /// check a parent dying in that window leaves exactly the orphan this
1162 /// option exists to prevent.
1163 ///
1164 /// Off by default, because killing children on parent exit is the right
1165 /// default for a supervisor and the wrong one for a CLI that deliberately
1166 /// backgrounds work.
1167 #[must_use]
1168 pub fn die_with_parent(mut self, enabled: bool) -> Self {
1169 self.die_with_parent = enabled;
1170 self
1171 }
1172
1173 /// Build the Claude client, resolving the binary path.
1174 pub fn build(self) -> Result<Claude> {
1175 let binary = match self.binary {
1176 Some(path) => path,
1177 None => which::which("claude").map_err(|_| Error::NotFound)?,
1178 };
1179
1180 Ok(Claude {
1181 binary,
1182 working_dir: self.working_dir,
1183 env: self.env,
1184 clear_env: self.clear_env,
1185 global_args: self.global_args,
1186 timeout: self.timeout,
1187 retry_policy: self.retry_policy,
1188 tested_cli_version_range: self.tested_cli_version_range,
1189 process_group: self.process_group.unwrap_or(true),
1190 kill_grace: self.kill_grace,
1191 termination_signal: self.termination_signal,
1192 output_limit: self.output_limit,
1193 on_spawn: self.on_spawn,
1194 die_with_parent: self.die_with_parent,
1195 })
1196 }
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201 use super::*;
1202
1203 #[test]
1204 fn builder_process_group_defaults_on_and_can_opt_out() {
1205 let on = Claude::builder()
1206 .binary("/nonexistent/claude")
1207 .build()
1208 .unwrap();
1209 assert!(on.process_group);
1210
1211 let off = Claude::builder()
1212 .binary("/nonexistent/claude")
1213 .process_group(false)
1214 .build()
1215 .unwrap();
1216 assert!(!off.process_group);
1217 }
1218
1219 #[test]
1220 fn builder_clear_env_defaults_off_and_is_call_order_independent() {
1221 let inherited = Claude::builder()
1222 .binary("/nonexistent/claude")
1223 .build()
1224 .unwrap();
1225 assert!(!inherited.clear_env);
1226
1227 let cleared = Claude::builder()
1228 .binary("/nonexistent/claude")
1229 .env("FIRST", "1")
1230 .clear_env()
1231 .env("SECOND", "2")
1232 .build()
1233 .unwrap();
1234 assert!(cleared.clear_env);
1235 assert_eq!(cleared.env.get("FIRST").map(String::as_str), Some("1"));
1236 assert_eq!(cleared.env.get("SECOND").map(String::as_str), Some("2"));
1237 }
1238
1239 #[test]
1240 fn builder_kill_grace_defaults_off_and_can_be_set() {
1241 let off = Claude::builder()
1242 .binary("/nonexistent/claude")
1243 .build()
1244 .unwrap();
1245 assert!(off.kill_grace.is_none());
1246
1247 let on = Claude::builder()
1248 .binary("/nonexistent/claude")
1249 .kill_grace(Duration::from_millis(750))
1250 .build()
1251 .unwrap();
1252 assert_eq!(on.kill_grace, Some(Duration::from_millis(750)));
1253 }
1254
1255 #[test]
1256 fn builder_termination_signal_defaults_to_term_and_can_select_interrupt() {
1257 let default = Claude::builder().binary("/unused").build().unwrap();
1258 assert_eq!(default.termination_signal, TerminationSignal::Terminate);
1259 let interrupt = Claude::builder()
1260 .binary("/unused")
1261 .termination_signal(TerminationSignal::Interrupt)
1262 .build()
1263 .unwrap();
1264 assert_eq!(interrupt.termination_signal, TerminationSignal::Interrupt);
1265 assert!(
1266 interrupt.kill_grace.is_none(),
1267 "signal alone does not enable grace"
1268 );
1269 }
1270
1271 // -- the version gate ------------------------------------------
1272 //
1273 // `gate_version` is the decision both the async and sync gates
1274 // share, and it takes the version rather than fetching it, so the
1275 // policy is testable without spawning a binary.
1276
1277 #[cfg(any(feature = "async", feature = "sync"))]
1278 fn gate(found: (u32, u32, u32)) -> Result<CliVersion> {
1279 let claude = Claude::builder()
1280 .binary("/nonexistent/claude")
1281 .build()
1282 .unwrap();
1283 let (min, max) = claude.effective_tested_range();
1284 claude.gate_version(CliVersion::new(found.0, found.1, found.2), min, max)
1285 }
1286
1287 #[cfg(any(feature = "async", feature = "sync"))]
1288 #[test]
1289 fn gate_accepts_a_version_inside_the_declared_range() {
1290 let found = gate((
1291 TESTED_CLI_VERSION_MIN.major,
1292 TESTED_CLI_VERSION_MIN.minor,
1293 TESTED_CLI_VERSION_MIN.patch,
1294 ))
1295 .expect("the declared minimum must pass its own gate");
1296 assert_eq!(found, TESTED_CLI_VERSION_MIN);
1297 }
1298
1299 #[cfg(any(feature = "async", feature = "sync"))]
1300 #[test]
1301 fn gate_rejects_older_than_minimum_with_both_bounds() {
1302 let err = gate((1, 0, 0)).expect_err("1.0.0 is below any supported floor");
1303 match err {
1304 Error::UntestedCliVersion {
1305 found,
1306 tested_min,
1307 tested_max,
1308 } => {
1309 assert_eq!(found, CliVersion::new(1, 0, 0));
1310 assert_eq!(tested_min, TESTED_CLI_VERSION_MIN);
1311 assert_eq!(tested_max, TESTED_CLI_VERSION_MAX);
1312 // The message must say which side it fell off, since
1313 // "too old" and "too new" call for opposite fixes.
1314 assert!(err_text(&err).contains("older"), "{}", err_text(&err));
1315 }
1316 other => panic!("expected UntestedCliVersion, got {other:?}"),
1317 }
1318 }
1319
1320 #[cfg(any(feature = "async", feature = "sync"))]
1321 #[test]
1322 fn gate_rejects_newer_than_maximum() {
1323 let err = gate((99, 0, 0)).expect_err("99.0.0 is above the tested ceiling");
1324 assert!(matches!(err, Error::UntestedCliVersion { .. }));
1325 assert!(err_text(&err).contains("newer"), "{}", err_text(&err));
1326 }
1327
1328 #[cfg(any(feature = "async", feature = "sync"))]
1329 #[test]
1330 fn gate_honours_a_caller_supplied_range_over_the_crate_default() {
1331 // A host that has verified a narrower window should be able to
1332 // enforce it, including rejecting versions the crate itself
1333 // considers fine.
1334 let claude = Claude::builder()
1335 .binary("/nonexistent/claude")
1336 .tested_cli_version_range(CliVersion::new(3, 0, 0), CliVersion::new(3, 0, 9))
1337 .build()
1338 .unwrap();
1339 let (min, max) = claude.effective_tested_range();
1340 assert_eq!(min, CliVersion::new(3, 0, 0));
1341 assert!(
1342 claude
1343 .gate_version(CliVersion::new(3, 0, 5), min, max)
1344 .is_ok()
1345 );
1346 assert!(
1347 claude
1348 .gate_version(TESTED_CLI_VERSION_MIN, min, max)
1349 .is_err(),
1350 "the caller's range must win over the crate's"
1351 );
1352 }
1353
1354 #[cfg(any(feature = "async", feature = "sync"))]
1355 fn err_text(e: &Error) -> String {
1356 e.to_string()
1357 }
1358
1359 #[test]
1360 fn test_builder_with_binary() {
1361 let claude = Claude::builder()
1362 .binary("/usr/local/bin/claude")
1363 .env("FOO", "bar")
1364 .timeout_secs(60)
1365 .build()
1366 .unwrap();
1367
1368 assert_eq!(claude.binary, PathBuf::from("/usr/local/bin/claude"));
1369 assert_eq!(claude.env.get("FOO").unwrap(), "bar");
1370 assert_eq!(claude.timeout, Some(Duration::from_secs(60)));
1371 }
1372
1373 #[test]
1374 fn test_builder_global_args() {
1375 let claude = Claude::builder()
1376 .binary("/usr/local/bin/claude")
1377 .arg("--verbose")
1378 .build()
1379 .unwrap();
1380
1381 assert_eq!(claude.global_args, vec!["--verbose"]);
1382 }
1383
1384 #[test]
1385 fn test_builder_verbose() {
1386 let claude = Claude::builder()
1387 .binary("/usr/local/bin/claude")
1388 .verbose()
1389 .build()
1390 .unwrap();
1391 assert!(claude.global_args.contains(&"--verbose".to_string()));
1392 }
1393
1394 #[test]
1395 fn test_builder_debug() {
1396 let claude = Claude::builder()
1397 .binary("/usr/local/bin/claude")
1398 .debug()
1399 .build()
1400 .unwrap();
1401 assert!(claude.global_args.contains(&"--debug".to_string()));
1402 }
1403}