claude_code_agent/lib.rs
1//! **claude-code-agent** — Rust SDK for Claude Code.
2//!
3//! Drives the `claude` CLI (verified against 2.1.328) over its stream-json
4//! control protocol: one persistent process per session, Rust closures as
5//! hook callbacks and permission handlers, in-process tools over the SDK MCP
6//! bridge, record/replay, and a session pool.
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#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
112
113pub mod agent;
114pub mod background;
115pub mod code_mode;
116pub mod compaction;
117pub mod fs_events;
118pub mod hooks;
119pub mod mcp;
120pub mod middleware;
121pub mod pool;
122pub mod protocol;
123pub mod replay;
124pub mod session;
125
126// ── Top-level re-exports ───────────────────────────────────────────────────────
127
128pub use agent::{Agent, AgentError, AgentEvent, AgentStream, TurnError, TurnResult};
129pub use hooks::HookRegistry;
130pub use mcp::{SdkMcpServer, SdkTool, ToolContent, ToolContext, ToolResult};
131/// `#[claude_tool]` — enable with the `macros` feature.
132#[cfg(feature = "macros")]
133pub use claude_code_agent_macros::claude_tool;
134pub use pool::{Checkout, PoolConfig, PooledSession, SessionPool};
135pub use protocol::{
136 // Core messages
137 Initialize, UserMessage, ContentBlock, Priority,
138 // Session settings
139 Autocompact, Effort, PermissionMode, PermissionPrompts, Thinking, ThinkingDisplay,
140 // Inbound
141 InboundMessage, SystemMessage, AssistantMessage, ResultMessage, UsageSummary,
142 BackgroundTask, TurnErrorKind,
143 // Control
144 ToolDecision, HookOutput, HookDecision, ControlRequest, ControlRequestBody,
145 ControlResponse, CanUseToolRequest, ElicitationRequest, ElicitationResponse, UserDialogBehavior, UserDialogRequest, UserDialogResponse,
146 // Hook types
147 HookEventKind, HookEventPayload, HookCallbackRequest,
148 // Tools/MCP
149 ToolDef, ToolAnnotations, McpManifest,
150 // Background
151 BackgroundTasksRequest,
152};
153pub use session::{
154 CanUseTool, McpCall, OnElicitation, OnStderr, OnUserDialog, ReloadPlugins, Session, SessionError,
155 SessionOptions,
156};
157
158/// Re-exports used by code generated from `#[claude_tool]`. Not public API.
159#[doc(hidden)]
160pub mod __private {
161 pub use serde_json;
162}