Skip to main content

claude_codes/
lib.rs

1//! A tightly typed Rust interface for the Claude Code JSON protocol
2//!
3//! This crate provides type-safe bindings for interacting with the Claude CLI
4//! through its JSON Lines protocol. It handles the complexity of message serialization,
5//! deserialization, and streaming communication with Claude.
6//!
7//! # Quick Start
8//!
9//! Add this crate to your project:
10//! ```bash
11//! cargo add claude-codes
12//! ```
13//!
14//! ## Using the Async Client (Recommended)
15//!
16//! ```ignore
17//! use claude_codes::AsyncClient;
18//!
19//! #[tokio::main]
20//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
21//!     // Create a client with automatic version checking
22//!     let mut client = AsyncClient::with_defaults().await?;
23//!
24//!     // Send a query and stream responses
25//!     let mut stream = client.query_stream("What is 2 + 2?").await?;
26//!
27//!     while let Some(response) = stream.next().await {
28//!         match response {
29//!             Ok(output) => {
30//!                 println!("Received: {}", output.message_type());
31//!                 // Handle different message types
32//!             }
33//!             Err(e) => eprintln!("Error: {}", e),
34//!         }
35//!     }
36//!
37//!     Ok(())
38//! }
39//! ```
40//!
41//! ## Using the Sync Client
42//!
43//! ```ignore
44//! use claude_codes::{SyncClient, ClaudeInput};
45//!
46//! fn main() -> Result<(), Box<dyn std::error::Error>> {
47//!     // Create a synchronous client
48//!     let mut client = SyncClient::with_defaults()?;
49//!
50//!     // Build a structured input message
51//!     let input = ClaudeInput::user_message("What is 2 + 2?", uuid::Uuid::new_v4());
52//!
53//!     // Send and collect all responses
54//!     let responses = client.query(input)?;
55//!
56//!     for response in responses {
57//!         println!("Received: {}", response.message_type());
58//!     }
59//!
60//!     Ok(())
61//! }
62//! ```
63//!
64//! # Architecture
65//!
66//! The crate is organized into several key modules:
67//!
68//! - [`client`] - High-level async and sync clients for easy interaction
69//! - [`protocol`] - Core JSON Lines protocol implementation
70//! - [`io`] - Top-level message types (`ClaudeInput`, `ClaudeOutput`)
71//! - [`messages`] - Detailed message structures for requests and responses
72//! - [`cli`] - Builder for configuring Claude CLI invocation
73//! - [`error`] - Error types and result aliases
74//! - [`version`] - Version compatibility checking
75//!
76//! # Version Compatibility
77//!
78//! ⚠️ **Important**: The Claude CLI protocol is unstable and evolving. This crate
79//! automatically checks your Claude CLI version and warns if it's newer than tested.
80//!
81//! Current tested version: **2.1.239**
82//!
83//! Report compatibility issues at: <https://github.com/meawoppl/rust-claude-codes/pulls>
84//!
85//! # Message Types
86//!
87//! The protocol uses several message types:
88//!
89//! - **System** - Initialization and metadata messages
90//! - **User** - Input messages from the user
91//! - **Assistant** - Claude's responses
92//! - **Result** - Session completion with timing and cost info
93//!
94//! # Examples
95//!
96//! See the `examples/` directory for complete working examples:
97//! - `async_client.rs` - Simple async client usage
98//! - `sync_client.rs` - Synchronous client usage
99//! - `basic_repl.rs` - Interactive REPL implementation
100
101// Core modules always available
102pub mod error;
103pub mod io;
104pub mod messages;
105pub mod models;
106pub mod protocol;
107pub mod tool_inputs;
108pub mod types;
109
110// On-disk transcript locations (the CLI's unpublished path-encoding rule)
111pub mod transcript;
112
113// Login support tooling (PTY-driven `claude auth login` / `setup-token`)
114#[cfg(feature = "auth")]
115pub mod auth;
116
117// Client modules
118#[cfg(feature = "async-client")]
119pub mod client_async;
120#[cfg(feature = "async-client")]
121pub mod client_raw_async;
122#[cfg(feature = "sync-client")]
123pub mod client_sync;
124
125// Client-related modules
126#[cfg(any(feature = "sync-client", feature = "async-client"))]
127pub mod cli;
128#[cfg(any(feature = "sync-client", feature = "async-client"))]
129pub mod version;
130
131#[cfg(any(feature = "sync-client", feature = "async-client"))]
132mod process;
133
134// Core exports always available
135pub use error::{Error, Result};
136pub use io::{
137    AnthropicError, AnthropicErrorDetails, ApiErrorType, AssistantMessageContent, ClaudeInput,
138    ClaudeOutput, ParseError, TranscriptMessage,
139};
140pub use messages::*;
141pub use models::ClaudeModel;
142pub use protocol::{MessageEnvelope, Protocol};
143pub use types::*;
144
145// Content block types for message parsing
146pub use io::{
147    CodeExecutionToolResultBlock, ContainerUploadBlock, ContentBlock, FallbackBlock, FallbackModel,
148    ImageBlock, ImageSource, ImageSourceType, McpToolResultBlock, McpToolUseBlock, MediaType,
149    ServerToolUseBlock, TextBlock, ThinkingBlock, ToolResultBlock, ToolResultContent,
150    WebSearchToolResultBlock,
151};
152
153// Control protocol types for tool permission handling
154pub use io::{
155    AskUserQuestionResponseError, ControlRequest, ControlRequestMessage, ControlRequestPayload,
156    ControlResponse, ControlResponseMessage, ControlResponsePayload, GetUsageResponse,
157    HookCallbackRequest, InitializeRequest, McpMessageRequest, ModelScopedRateLimit, Permission,
158    PermissionBehavior, PermissionDenial, PermissionDestination, PermissionModeName,
159    PermissionResult, PermissionRule, PermissionSuggestion, PermissionType, ToolCaller,
160    ToolPermissionRequest, ToolUseBlock, UsageBehavior, UsageBehaviors, UsageModelUsage,
161    UsageRateLimitWindow, UsageRateLimits, UsageSession,
162};
163
164// System message and assistant message types
165pub use io::{
166    ApiKeySource, ApiRetryMessage, AssistantErrorKind, BackgroundTaskInfo,
167    BackgroundTasksChangedMessage, BatchToolUse, CodeChangePublishedMessage, CommandInfo,
168    CommandsChangedMessage, CompactBoundaryMessage, CompactMetadata, CompactionTrigger,
169    ContextAgent, ContextCategory, ContextMcpTool, ContextMemoryFile, ContextOverLimit,
170    ContextSkill, ContextUsage, ControlRequestProgressMessage, ElicitationCompleteMessage,
171    FailedPersistedFile, FeedbackDraftQueuedMessage, FilesPersistedMessage, HookProgressMessage,
172    HookResponseMessage, HookStartedMessage, InformationalMessage, InitMessage, InitPermissionMode,
173    KnownSystemEvent, LocalCommandOutputMessage, McpMeta, McpServerError, MemoryPaths,
174    MemoryRecallItem, MemoryRecallMessage, MessageOrigin, MessageRole, MirrorErrorKey,
175    MirrorErrorMessage, ModelRefusalFallbackMessage, ModelRefusalNoFallbackMessage,
176    NotificationMessage, OutputStyle, PermissionDeniedMessage, PersistedFile, PluginDiagnostic,
177    PluginInfo, PluginInstallMessage, PreservedMessages, PreservedSegment, RefusalFallbackScope,
178    StatusMessage, StatusMessageStatus, StopReason, SummarizeMetadata, SystemMessage,
179    SystemSubtype, TaskNotificationMessage, TaskPatch, TaskProgressMessage, TaskStartedMessage,
180    TaskStatus, TaskType, TaskUpdatedMessage, TaskUsage, ThinkingTokensMessage, ToolResultMeta,
181    ToolUseMeta, VcsMutationKind, VcsStateChangedMessage, WorkerShuttingDownMessage,
182};
183
184// Additional top-level output message wrappers
185pub use io::{
186    AuthStatusMessage, CommandLifecycleMessage, CommandLifecycleState, ConversationResetMessage,
187    PromptSuggestionMessage, StreamEventMessage, SubagentRetry, ToolProgressMessage,
188    ToolUseSummaryMessage,
189};
190
191// Wire-fidelity audit for verifying frames are fully typed
192pub use io::{assert_fully_wrapped, audit_frame, FrameAudit};
193
194// Rate limit types
195pub use io::{
196    OverageDisabledReason, OveragePeriodUtilization, OverageStatus, RateLimitErrorCode,
197    RateLimitEvent, RateLimitInfo, RateLimitStatus, RateLimitWindow,
198};
199
200// Usage types
201pub use io::{
202    AssistantUsage, CacheCreationDetails, DeferredToolUse, FastModeDisabledReason, ServerToolUse,
203    SubagentKillCounts, SubagentRefusalCounts, SubagentResult, SubagentSpawnRequests,
204    SubagentStats, SubagentToolStats, SubagentUsageRollup, UsageInfo,
205};
206
207// Typed tool input types
208pub use tool_inputs::{
209    AllowedPrompt, AskUserQuestionInput, BashInput, EditInput, EnterPlanModeInput,
210    ExitPlanModeInput, GlobInput, GrepInput, GrepOutputMode, KillShellInput, LsInput,
211    MultiEditInput, MultiEditOperation, NotebookCellType, NotebookEditInput, NotebookEditMode,
212    NotebookReadInput, Question, QuestionMetadata, QuestionOption, ReadInput, ScheduleWakeupInput,
213    SkillInput, SubagentType, TaskInput, TaskOutputInput, TodoItem, TodoStatus, TodoWriteInput,
214    ToolInput, ToolSearchInput, WebFetchInput, WebSearchInput, WriteInput,
215};
216
217// Client exports
218#[cfg(feature = "async-client")]
219pub use client_async::{AsyncClient, AsyncStreamProcessor};
220#[cfg(feature = "async-client")]
221pub use client_raw_async::RawAsyncClient;
222#[cfg(feature = "sync-client")]
223pub use client_sync::{StreamProcessor, SyncClient};
224
225// Client-related exports
226#[cfg(any(feature = "sync-client", feature = "async-client"))]
227pub use cli::{ClaudeCliBuilder, CliFlag, InputFormat, OutputFormat, PermissionMode};
228
229#[cfg(test)]
230mod tests {
231    #[test]
232    fn it_works() {
233        assert_eq!(2 + 2, 4);
234    }
235}