1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//! Rusty Claw - Rust implementation of the Claude Agent SDK
//!
//! This crate provides a Rust implementation of the Claude Agent SDK, architecturally
//! inspired by Anthropic's Python SDK ([claude-agent-sdk-python](https://github.com/anthropics/claude-agent-sdk-python))
//! licensed under MIT.
//!
//! # Overview
//!
//! Rusty Claw enables building Claude-powered agents in Rust with support for:
//! - Bidirectional JSONL transport over stdio
//! - Claude Control Protocol (CCP) message handling
//! - Model Context Protocol (MCP) tool integration
//! - Hook system for lifecycle events
//! - Procedural macros for ergonomic tool definitions
//!
//! # Architecture
//!
//! The SDK is organized into several key modules:
//! - `transport`: Low-level JSONL message transport over stdio
//! - `control`: Claude Control Protocol implementation
//! - `mcp`: Model Context Protocol integration
//! - `hooks`: Lifecycle event hooks
//! - `error`: Error types and handling
//!
//! # Subagent Support
//!
//! Rusty Claw supports spawning and managing subagents with dedicated prompts and tool restrictions:
//!
//! ```no_run
//! use rusty_claw::prelude::*;
//! use rusty_claw::options::AgentDefinition;
//! use std::collections::HashMap;
//!
//! # async fn example() -> Result<(), ClawError> {
//! // Define specialized agents
//! let mut agents = HashMap::new();
//! agents.insert(
//! "researcher".to_string(),
//! AgentDefinition {
//! description: "Research agent for code analysis".to_string(),
//! prompt: "You are a research assistant".to_string(),
//! tools: vec!["Read".to_string(), "Grep".to_string()],
//! model: Some("claude-sonnet-4".to_string()),
//! },
//! );
//!
//! // Configure lifecycle hooks
//! let mut hooks = HashMap::new();
//! hooks.insert(
//! HookEvent::SubagentStart,
//! vec![HookMatcher::tool("Bash")],
//! );
//!
//! // Build options and connect client
//! let options = ClaudeAgentOptions::builder()
//! .agents(agents)
//! .hooks(hooks)
//! .build();
//!
//! let mut client = ClaudeClient::new(options)?;
//! client.connect().await?;
//! # Ok(())
//! # }
//! ```
//!
//! See [`examples/subagent_usage.rs`](https://github.com/citadelgrad/rusty_claw/blob/main/crates/rusty_claw/examples/subagent_usage.rs)
//! for a complete working example.
//!
//! For detailed documentation on subagent lifecycle hooks, see [`docs/HOOKS.md`](https://github.com/citadelgrad/rusty_claw/blob/main/docs/HOOKS.md).
//!
//! # Example
//!
//! ```rust,no_run
//! use rusty_claw::prelude::*;
//! use tokio_stream::StreamExt;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), ClawError> {
//! let options = ClaudeAgentOptions::builder()
//! .allowed_tools(vec!["Read".into(), "Edit".into(), "Bash".into()])
//! .permission_mode(PermissionMode::AcceptEdits)
//! .build();
//!
//! let mut stream = query("Find and fix the bug in auth.py", Some(options)).await?;
//!
//! while let Some(message) = stream.next().await {
//! match message? {
//! Message::Assistant(msg) => {
//! for block in msg.message.content {
//! if let ContentBlock::Text { text } = block {
//! println!("{}", text);
//! }
//! }
//! }
//! Message::Result(ResultMessage::Success { result, .. }) => {
//! println!("Done: {}", result);
//! }
//! _ => {}
//! }
//! }
//! Ok(())
//! }
//! ```
//!
//! # License
//!
//! Licensed under MIT. See LICENSE file for details.
// Re-export macros from rusty_claw_macros
pub use *;
// Module structure - to be implemented in future tasks
/// Low-level transport layer for JSONL communication over stdio
///
/// This module provides the `Transport` trait, which defines an async interface for
/// bidirectional JSONL message exchange with the Claude Code CLI over stdin/stdout.
///
/// `SubprocessCLITransport` is the default implementation that spawns the `claude` CLI
/// as a subprocess and manages its lifecycle.
///
/// The `Transport` trait can be implemented for custom transports (e.g., remote connections,
/// testing mock transports, alternative CLIs).
/// Claude Control Protocol (CCP) implementation
///
/// This module implements the Claude Control Protocol for bidirectional communication between
/// the agent and the Claude CLI. It handles control requests like permission checks, tool
/// availability queries, and session lifecycle management.
/// Model Context Protocol (MCP) integration
///
/// This module provides the integration layer for MCP tools, allowing agents to expose
/// custom tools to the Claude CLI. See `SdkMcpServerImpl` for the main server implementation.
/// Hook system for lifecycle events
///
/// The hook system allows agents to intercept and respond to lifecycle events such as
/// tool invocations, permission requests, and subagent operations.
///
/// Key types:
/// - `HookEvent` - Events that trigger hooks (defined in options module)
/// - `HookMatcher` - Pattern matching for selective hook triggering (defined in options module)
/// - `HookCallback` - Trait for implementing hook logic
/// - `HookInput` - Data passed to hooks
/// - `HookContext` - Session context available to hooks
/// - `HookResponse` - Response with permission decisions
/// Permission management for tool usage control
///
/// This module provides permission handlers for controlling tool access and usage
/// in Claude agents. See `DefaultPermissionHandler` for the default implementation.
/// Error types and utilities
///
/// This module defines the `ClawError` enum, which covers all error cases in the SDK:
///
/// - `CliNotFound` - Claude Code CLI binary not found during discovery
/// - `InvalidCliVersion` - CLI version is older than required (< 2.0.0)
/// - `Connection` - Transport connection failures
/// - `Process` - CLI process crashes or non-zero exits
/// - `JsonDecode` - JSONL parsing errors (auto-converts from `serde_json::Error`)
/// - `MessageParse` - Malformed control protocol messages
/// - `ControlTimeout` - Control protocol request timeouts
/// - `ControlError` - Control protocol semantic errors
/// - `Io` - Filesystem and I/O operations (auto-converts from `std::io::Error`)
/// - `ToolExecution` - MCP tool handler failures
/// Message types and structures
///
/// This module defines all message types that flow between the agent and Claude CLI.
///
/// The primary `Message` enum represents all possible messages from the CLI:
///
/// - `System` - System lifecycle events (init, compact boundary)
/// - `Assistant` - Assistant responses with content blocks
/// - `User` - User input messages
/// - `Result` - Final results (success, error, input required)
///
/// Assistant messages contain `ContentBlock` items:
///
/// - `Text` - Plain text content
/// - `ToolUse` - Tool invocation requests
/// - `ToolResult` - Tool execution results
/// - `Thinking` - Extended thinking tokens
/// Simple query API for one-shot Claude interactions
///
/// This module provides the `query()` function for simple, one-shot queries to Claude
/// without managing a persistent client connection.
/// Configuration options and builder
///
/// This module provides `ClaudeAgentOptions` for configuring Claude agent behavior,
/// including model selection, permission modes, hook configurations, and agent definitions.
/// Client for interactive sessions with Claude CLI
///
/// This module provides `ClaudeClient`, a persistent client for multi-turn
/// conversations with the Claude Code CLI. Unlike the one-shot `query()` API, `ClaudeClient`
/// maintains state across multiple messages and supports control operations like model switching
/// and session interruption.
// Public API re-exports
pub use query;
// Prelude module for common imports