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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//! # Agent SDK
//!
//! A Rust SDK for building AI agents powered by large language models (LLMs).
//!
//! This crate provides the infrastructure to build agents that can:
//! - Converse with users via multiple LLM providers
//! - Execute tools to interact with external systems
//! - Stream events in real-time for responsive UIs
//! - Persist conversation history and state
//!
//! ## Quick Start
//!
//! ```no_run
//! use agent_sdk::{
//! builder, AgentEvent, AgentInput, CancellationToken, ThreadId, ToolContext,
//! providers::AnthropicProvider,
//! };
//!
//! # async fn example() -> anyhow::Result<()> {
//! // 1. Create an LLM provider
//! let api_key = std::env::var("ANTHROPIC_API_KEY")?;
//! let provider = AnthropicProvider::sonnet(api_key);
//!
//! // 2. Build the agent
//! let agent = builder::<()>()
//! .provider(provider)
//! .build();
//!
//! // 3. Run a conversation
//! let thread_id = ThreadId::new();
//! let ctx = ToolContext::new(());
//! let cancel = CancellationToken::new();
//! let (mut events, _final_state) = agent.run(
//! thread_id,
//! AgentInput::Text("Hello!".to_string()),
//! ctx,
//! cancel,
//! );
//!
//! // 4. Process streaming events
//! while let Some(envelope) = events.recv().await {
//! match envelope.event {
//! AgentEvent::Text { message_id: _, text } => print!("{text}"),
//! AgentEvent::Done { .. } => break,
//! _ => {}
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Core Concepts
//!
//! ### Agent Loop
//!
//! The [`AgentLoop`] orchestrates the conversation cycle:
//!
//! 1. User sends a message
//! 2. Agent sends message to LLM
//! 3. LLM responds with text and/or tool calls
//! 4. Agent executes tools and feeds results back to LLM
//! 5. Repeat until LLM responds with only text
//!
//! Use [`builder()`] to construct an agent:
//!
//! ```no_run
//! use agent_sdk::{builder, AgentConfig, providers::AnthropicProvider};
//!
//! # fn example() {
//! # let api_key = String::new();
//! let agent = builder::<()>()
//! .provider(AnthropicProvider::sonnet(api_key))
//! .config(AgentConfig {
//! max_turns: Some(20),
//! system_prompt: "You are a helpful assistant.".into(),
//! ..Default::default()
//! })
//! .build();
//! # }
//! ```
//!
//! ### Tools
//!
//! Tools let the LLM interact with external systems. Implement the [`Tool`] trait:
//!
//! ```
//! use agent_sdk::{DynamicToolName, Tool, ToolContext, ToolResult, ToolTier};
//! use serde_json::{json, Value};
//! use std::future::Future;
//!
//! struct WeatherTool;
//!
//! // No #[async_trait] needed - Rust 1.75+ supports native async traits
//! impl Tool<()> for WeatherTool {
//! type Name = DynamicToolName;
//!
//! fn name(&self) -> DynamicToolName { DynamicToolName::new("get_weather") }
//!
//! fn display_name(&self) -> &'static str { "Weather" }
//!
//! fn description(&self) -> &'static str {
//! "Get current weather for a city"
//! }
//!
//! fn input_schema(&self) -> Value {
//! json!({
//! "type": "object",
//! "properties": {
//! "city": { "type": "string" }
//! },
//! "required": ["city"]
//! })
//! }
//!
//! fn tier(&self) -> ToolTier { ToolTier::Observe }
//!
//! fn execute(
//! &self,
//! _ctx: &ToolContext<()>,
//! input: Value,
//! ) -> impl Future<Output = anyhow::Result<ToolResult>> + Send {
//! async move {
//! let city = input["city"].as_str().unwrap_or("Unknown");
//! Ok(ToolResult::success(format!("Weather in {city}: Sunny, 72°F")))
//! }
//! }
//! }
//! ```
//!
//! Register tools with [`ToolRegistry`]:
//!
//! ```no_run
//! use agent_sdk::{builder, DynamicToolName, ToolRegistry, providers::AnthropicProvider};
//! # use agent_sdk::{Tool, ToolContext, ToolResult, ToolTier};
//! # use serde_json::Value;
//! # use std::future::Future;
//! # struct WeatherTool;
//! # impl Tool<()> for WeatherTool {
//! # type Name = DynamicToolName;
//! # fn name(&self) -> DynamicToolName { DynamicToolName::new("weather") }
//! # fn display_name(&self) -> &'static str { "" }
//! # fn description(&self) -> &'static str { "" }
//! # fn input_schema(&self) -> Value { Value::Null }
//! # fn execute(&self, _: &ToolContext<()>, _: Value) -> impl Future<Output = anyhow::Result<ToolResult>> + Send {
//! # async { Ok(ToolResult::success("")) }
//! # }
//! # }
//!
//! # fn example() {
//! # let api_key = String::new();
//! let mut tools = ToolRegistry::new();
//! tools.register(WeatherTool);
//!
//! let agent = builder::<()>()
//! .provider(AnthropicProvider::sonnet(api_key))
//! .tools(tools)
//! .build();
//! # }
//! ```
//!
//! ### Tool Tiers
//!
//! Tools are classified by permission level via [`ToolTier`]:
//!
//! | Tier | Description | Example |
//! |------|-------------|---------|
//! | [`ToolTier::Observe`] | Read-only, always allowed | Get balance, read file |
//! | [`ToolTier::Confirm`] | Requires user confirmation | Send email, transfer funds |
//!
//! ### Lifecycle Hooks
//!
//! Implement [`AgentHooks`] to intercept and control agent behavior:
//!
//! ```
//! use agent_sdk::{AgentHooks, ToolDecision, ToolResult, ToolTier};
//! use async_trait::async_trait;
//! use serde_json::Value;
//!
//! struct MyHooks;
//!
//! #[async_trait]
//! impl AgentHooks for MyHooks {
//! async fn pre_tool_use(
//! &self,
//! tool_name: &str,
//! _input: &Value,
//! tier: ToolTier,
//! ) -> ToolDecision {
//! println!("Tool called: {tool_name}");
//! match tier {
//! ToolTier::Observe => ToolDecision::Allow,
//! ToolTier::Confirm => ToolDecision::RequiresConfirmation(
//! "Please confirm this action".into()
//! ),
//! }
//! }
//!
//! async fn post_tool_use(&self, tool_name: &str, result: &ToolResult) {
//! println!("{tool_name} completed: {}", result.success);
//! }
//! }
//! ```
//!
//! Built-in hook implementations:
//! - [`DefaultHooks`] - Tier-based permissions (default)
//! - [`AllowAllHooks`] - Allow all tools without confirmation (for testing)
//! - [`LoggingHooks`] - Debug logging for all events
//!
//! ### Events
//!
//! The agent emits [`AgentEvent`]s during execution for real-time updates:
//!
//! | Event | Description |
//! |-------|-------------|
//! | [`AgentEvent::Start`] | Agent begins processing |
//! | [`AgentEvent::Text`] | Text response from LLM |
//! | [`AgentEvent::TextDelta`] | Streaming text chunk |
//! | [`AgentEvent::ToolCallStart`] | Tool execution starting |
//! | [`AgentEvent::ToolCallEnd`] | Tool execution completed |
//! | [`AgentEvent::TurnComplete`] | One LLM round-trip finished |
//! | [`AgentEvent::Done`] | Agent completed successfully |
//! | [`AgentEvent::Error`] | An error occurred |
//!
//! ### Task Tracking
//!
//! Use [`TodoWriteTool`] and [`TodoReadTool`] to track task progress:
//!
//! ```no_run
//! use agent_sdk::todo::{TodoState, TodoWriteTool, TodoReadTool};
//! use std::sync::Arc;
//! use tokio::sync::RwLock;
//!
//! let state = Arc::new(RwLock::new(TodoState::new()));
//! let write_tool = TodoWriteTool::new(Arc::clone(&state));
//! let read_tool = TodoReadTool::new(state);
//! ```
//!
//! Task states: `Pending` (○), `InProgress` (⚡), `Completed` (✓)
//!
//! ### Custom Context
//!
//! Pass application-specific data to tools via the generic type parameter:
//!
//! ```
//! use agent_sdk::{DynamicToolName, Tool, ToolContext, ToolResult, ToolTier};
//! use serde_json::Value;
//! use std::future::Future;
//!
//! // Your application context
//! struct AppContext {
//! user_id: String,
//! // database: Database,
//! }
//!
//! struct UserInfoTool;
//!
//! impl Tool<AppContext> for UserInfoTool {
//! type Name = DynamicToolName;
//!
//! fn name(&self) -> DynamicToolName { DynamicToolName::new("get_user_info") }
//! fn display_name(&self) -> &'static str { "User Info" }
//! fn description(&self) -> &'static str { "Get info about current user" }
//! fn input_schema(&self) -> Value { serde_json::json!({"type": "object"}) }
//!
//! fn execute(
//! &self,
//! ctx: &ToolContext<AppContext>,
//! _input: Value,
//! ) -> impl Future<Output = anyhow::Result<ToolResult>> + Send {
//! let user_id = ctx.app.user_id.clone();
//! async move {
//! Ok(ToolResult::success(format!("User: {user_id}")))
//! }
//! }
//! }
//! ```
//!
//! ## Modules
//!
//! | Module | Description |
//! |--------|-------------|
//! | [`providers`] | LLM provider implementations |
//! | [`primitive_tools`] | Built-in file operation tools (Read, Write, Edit, Glob, Grep, Bash) |
//! | [`llm`] | LLM abstraction layer |
//! | [`subagent`] | Nested agent execution with [`SubagentFactory`] |
//! | [`mcp`] | Model Context Protocol support |
//! | [`todo`] | Task tracking tools ([`TodoWriteTool`], [`TodoReadTool`]) |
//! | [`user_interaction`] | User question/confirmation tools ([`AskUserQuestionTool`]) |
//! | [`web`] | Web search and fetch tools |
//! | [`skills`] | Custom skill/command loading |
//! | [`reminders`] | System reminder infrastructure for agent guidance |
//!
//! ## System Reminders
//!
//! The SDK includes a reminder system that provides contextual guidance to the AI agent
//! using the `<system-reminder>` XML tag pattern. Claude is trained to recognize these
//! tags and follow the instructions without mentioning them to users.
//!
//! ```
//! use agent_sdk::reminders::{wrap_reminder, ReminderConfig, ReminderTracker};
//!
//! // Wrap guidance in system-reminder tags
//! let reminder = wrap_reminder("Verify the output before proceeding.");
//!
//! // Configure reminder behavior
//! let config = ReminderConfig::new()
//! .with_todo_reminder_turns(5)
//! .with_repeated_action_threshold(3);
//! ```
//!
//! ## Feature Flags
//!
//! All features are enabled by default. The crate has no optional features currently.
pub use ;
pub use AgentCapabilities;
pub use ;
pub use ;
pub use ;
// Re-export CancellationToken for use with `AgentLoop::run_with_cancel`.
pub use ;
pub use ;
pub use ;
pub use ;
pub use CancellationToken;
pub use ;
pub use ;
// Re-export user interaction types for convenience
pub use ;
// Re-export subagent types for convenience
pub use ;
// Re-export todo types for convenience
pub use ;
// Re-export reminder types for convenience
pub use ;