Skip to main content

claude_code_agent/
lib.rs

1//! Run Claude Code from Rust.
2//!
3//! Each [`Session`] keeps one `claude` process running (Claude Code CLI
4//! 2.1.329 or newer). Send prompts with [`Agent`], approve or block tools with
5//! hooks and [`CanUseTool`], give Claude tools written in Rust, run many
6//! sessions with [`SessionPool`], and replay recorded sessions in tests.
7//!
8//! # Quick start
9//!
10//! ```rust,no_run
11//! use claude_code_agent::{Session, SessionOptions, Initialize, Agent, AgentEvent};
12//! use tokio_stream::StreamExt;
13//!
14//! #[tokio::main]
15//! async fn main() -> anyhow::Result<()> {
16//!     let session = Session::spawn(
17//!         SessionOptions { cwd: Some("/my/project".into()), ..Default::default() },
18//!         Initialize::default(),
19//!     ).await?;
20//!
21//!     let agent = Agent::new(session);
22//!     let mut stream = agent.prompt("hello").await?;
23//!
24//!     while let Some(event) = stream.next().await {
25//!         match event {
26//!             AgentEvent::Text(t) => print!("{}", t),
27//!             AgentEvent::Done(r) => {
28//!                 eprintln!("\ncost: ${:.4}", r.total_cost_usd.unwrap_or(0.0));
29//!                 break;
30//!             }
31//!             AgentEvent::Error(e) => eprintln!("error: {}", e),
32//!             _ => {}
33//!         }
34//!     }
35//!     Ok(())
36//! }
37//! ```
38//!
39//! # With hooks
40//!
41//! ```rust,no_run
42//! use claude_code_agent::{Agent, AgentEvent, CanUseTool, HookRegistry, Initialize, Session, SessionOptions};
43//! use claude_code_agent::protocol::{HookOutput, ToolDecision};
44//! use tokio_stream::StreamExt;
45//!
46//! #[tokio::main]
47//! async fn main() -> anyhow::Result<()> {
48//!     // Hooks are declared before spawn: the CLI learns them from `initialize`.
49//!     let mut hooks = HookRegistry::new();
50//!     hooks.on_pre_tool_use(|payload| async move {
51//!         match payload.tool_name.as_deref() {
52//!             Some("Bash") => HookOutput::allow(),
53//!             Some(name)   => HookOutput::block(format!("{name} not allowed")),
54//!             None         => HookOutput::allow(),
55//!         }
56//!     });
57//!
58//!     let opts = SessionOptions {
59//!         hooks,
60//!         // Asked whenever the CLI's own permission rules would prompt.
61//!         can_use_tool: Some(CanUseTool::new(|req| async move {
62//!             if req.tool_name == "Bash" { ToolDecision::allow() } else { ToolDecision::deny("read-only") }
63//!         })),
64//!         ..Default::default()
65//!     };
66//!     let session = Session::spawn(opts, Initialize::default()).await?;
67//!     let agent = Agent::new(session);
68//!
69//!     let mut stream = agent.prompt("list files in /tmp").await?;
70//!     while let Some(ev) = stream.next().await {
71//!         if let AgentEvent::Text(t) = &ev { print!("{}", t); }
72//!         if matches!(ev, AgentEvent::Done(_) | AgentEvent::Error(_)) { break; }
73//!     }
74//!     Ok(())
75//! }
76//! ```
77//!
78//! # With session pool (high throughput)
79//!
80//! ```rust,no_run
81//! use claude_code_agent::{SessionPool, PoolConfig, Agent, AgentEvent};
82//! use tokio_stream::StreamExt;
83//!
84//! #[tokio::main]
85//! async fn main() -> anyhow::Result<()> {
86//!     let pool = SessionPool::new(PoolConfig { max_sessions: 4, ..Default::default() });
87//!     pool.warm(2).await; // pre-warm 2 processes
88//!
89//!     // Parallel prompts — each reuses an idle session from the pool
90//!     let (r1, r2) = tokio::join!(
91//!         run_prompt(&pool, "task one"),
92//!         run_prompt(&pool, "task two"),
93//!     );
94//!     Ok(())
95//! }
96//!
97//! async fn run_prompt(pool: &SessionPool, text: &str) -> anyhow::Result<String> {
98//!     let borrowed = pool.acquire().await?;
99//!     let agent = Agent::new(borrowed.session.clone());
100//!     let mut stream = agent.prompt(text).await?;
101//!     let mut out = String::new();
102//!     while let Some(ev) = stream.next().await {
103//!         if let AgentEvent::Text(t) = &ev { out.push_str(t); }
104//!         if matches!(ev, AgentEvent::Done(_) | AgentEvent::Error(_)) { break; }
105//!     }
106//!     Ok(out)
107//! }
108//! ```
109
110#![forbid(unsafe_code)]
111#![warn(missing_docs)]
112#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
113
114pub mod agent;
115pub mod background;
116pub mod code_mode;
117pub mod compaction;
118pub mod fs_events;
119pub mod hooks;
120pub mod mcp;
121pub mod middleware;
122pub mod pool;
123pub mod protocol;
124pub mod replay;
125pub mod session;
126
127// ── Top-level re-exports ───────────────────────────────────────────────────────
128
129pub use agent::{Agent, AgentError, AgentEvent, AgentStream, TurnError, TurnResult};
130pub use hooks::HookRegistry;
131pub use mcp::{SdkMcpServer, SdkTool, ToolContent, ToolContext, ToolResult};
132/// `#[claude_tool]` — enable with the `macros` feature.
133#[cfg(feature = "macros")]
134pub use claude_code_agent_macros::claude_tool;
135pub use pool::{Checkout, PoolConfig, PooledSession, SessionPool};
136pub use protocol::{
137    // Core messages
138    Initialize, UserMessage, ContentBlock, Priority,
139    // Session settings
140    Autocompact, Effort, PermissionMode, PermissionPrompts, Thinking, ThinkingDisplay,
141    // Inbound
142    InboundMessage, SystemMessage, AssistantMessage, ResultMessage, UsageSummary,
143    BackgroundTask, TurnErrorKind,
144    // Control
145    ToolDecision, HookOutput, HookDecision, ControlRequest, ControlRequestBody,
146    ControlResponse, CanUseToolRequest, ElicitationRequest, ElicitationResponse, UserDialogBehavior, UserDialogRequest, UserDialogResponse,
147    // Hook types
148    HookEventKind, HookEventPayload, HookCallbackRequest,
149    // Tools/MCP
150    ToolDef, ToolAnnotations, McpManifest,
151    // Background
152    BackgroundTasksRequest,
153};
154pub use session::{
155    CanUseTool, McpCall, OnElicitation, OnStderr, OnUserDialog, ReloadPlugins, Session, SessionError,
156    SessionOptions, WeakSession,
157};
158
159/// Re-exports used by code generated from `#[claude_tool]`. Not public API.
160#[doc(hidden)]
161pub mod __private {
162    pub use serde_json;
163}