claude-agent 0.2.25

Rust SDK for building AI agents with Anthropic's Claude - Direct API, no CLI dependency
Documentation
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Agent configuration types.
//!
//! Domain-separated configuration for clarity and maintainability.

use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;

use rust_decimal::Decimal;

use crate::client::messages::DEFAULT_MAX_TOKENS;
use crate::output_style::OutputStyle;
use crate::permissions::PermissionPolicy;
use crate::tools::ToolAccess;

/// Model-related configuration.
#[derive(Debug, Clone)]
pub struct AgentModelConfig {
    /// Primary model for main operations
    pub primary: String,
    /// Smaller model for quick operations
    pub small: String,
    /// Maximum tokens per response
    pub max_tokens: u32,
    /// Enable extended context window (1M for supported models)
    pub extended_context: bool,
}

impl Default for AgentModelConfig {
    fn default() -> Self {
        Self {
            primary: crate::client::DEFAULT_MODEL.to_string(),
            small: crate::client::DEFAULT_SMALL_MODEL.to_string(),
            max_tokens: DEFAULT_MAX_TOKENS,
            extended_context: false,
        }
    }
}

impl AgentModelConfig {
    pub fn new(primary: impl Into<String>) -> Self {
        Self {
            primary: primary.into(),
            ..Default::default()
        }
    }

    pub fn small(mut self, small: impl Into<String>) -> Self {
        self.small = small.into();
        self
    }

    pub fn max_tokens(mut self, tokens: u32) -> Self {
        self.max_tokens = tokens;
        self
    }

    pub fn extended_context(mut self, enabled: bool) -> Self {
        self.extended_context = enabled;
        self
    }
}

/// Execution behavior configuration.
#[derive(Debug, Clone)]
pub struct ExecutionConfig {
    /// Maximum agentic loop iterations
    pub max_iterations: usize,
    /// Overall execution timeout
    pub timeout: Option<Duration>,
    /// Timeout between streaming chunks (detects stalled connections)
    pub chunk_timeout: Duration,
    /// Enable automatic context compaction
    pub auto_compact: bool,
    /// Context usage threshold for compaction (0.0-1.0)
    pub compact_threshold: f32,
    /// Messages to preserve during compaction
    pub compact_keep_messages: usize,
}

impl Default for ExecutionConfig {
    fn default() -> Self {
        Self {
            max_iterations: 100,
            timeout: Some(Duration::from_secs(300)),
            chunk_timeout: Duration::from_secs(60),
            auto_compact: true,
            compact_threshold: crate::session::compact::DEFAULT_COMPACT_THRESHOLD,
            compact_keep_messages: 4,
        }
    }
}

impl ExecutionConfig {
    pub fn max_iterations(mut self, max: usize) -> Self {
        self.max_iterations = max;
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    pub fn without_timeout(mut self) -> Self {
        self.timeout = None;
        self
    }

    pub fn chunk_timeout(mut self, timeout: Duration) -> Self {
        self.chunk_timeout = timeout;
        self
    }

    pub fn auto_compact(mut self, enabled: bool) -> Self {
        self.auto_compact = enabled;
        self
    }

    pub fn compact_threshold(mut self, threshold: f32) -> Self {
        self.compact_threshold = threshold.clamp(0.0, 1.0);
        self
    }

    pub fn compact_keep_messages(mut self, count: usize) -> Self {
        self.compact_keep_messages = count;
        self
    }
}

/// Security and permission configuration.
#[derive(Debug, Clone, Default)]
pub struct SecurityConfig {
    /// Tool permission policy
    pub permission_policy: PermissionPolicy,
    /// Tool access control
    pub tool_access: ToolAccess,
    /// Environment variables for tool execution
    pub env: HashMap<String, String>,
}

impl SecurityConfig {
    pub fn permissive() -> Self {
        Self {
            permission_policy: PermissionPolicy::permissive(),
            tool_access: ToolAccess::All,
            ..Default::default()
        }
    }

    pub fn read_only() -> Self {
        Self {
            permission_policy: PermissionPolicy::read_only(),
            tool_access: ToolAccess::only(["Read", "Glob", "Grep", "Task", "TaskOutput"]),
            ..Default::default()
        }
    }

    pub fn permission_policy(mut self, policy: PermissionPolicy) -> Self {
        self.permission_policy = policy;
        self
    }

    pub fn tool_access(mut self, access: ToolAccess) -> Self {
        self.tool_access = access;
        self
    }

    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.insert(key.into(), value.into());
        self
    }

    pub fn envs(
        mut self,
        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (k, v) in vars {
            self.env.insert(k.into(), v.into());
        }
        self
    }
}

/// Budget and cost control configuration.
#[derive(Debug, Clone, Default)]
pub struct BudgetConfig {
    /// Maximum cost in USD
    pub max_cost_usd: Option<Decimal>,
    /// Tenant identifier for multi-tenant tracking
    pub tenant_id: Option<String>,
    /// Model to fall back to when budget exceeded
    pub fallback_model: Option<String>,
}

impl BudgetConfig {
    pub fn unlimited() -> Self {
        Self::default()
    }

    pub fn max_cost(mut self, usd: Decimal) -> Self {
        self.max_cost_usd = Some(usd);
        self
    }

    pub fn tenant(mut self, tenant_id: impl Into<String>) -> Self {
        self.tenant_id = Some(tenant_id.into());
        self
    }

    pub fn fallback(mut self, model: impl Into<String>) -> Self {
        self.fallback_model = Some(model.into());
        self
    }
}

/// Prompt and output configuration.
#[derive(Debug, Clone, Default)]
pub struct PromptConfig {
    /// Custom system prompt
    pub system_prompt: Option<String>,
    /// How to apply system prompt
    pub system_prompt_mode: SystemPromptMode,
    /// Output style customization
    pub output_style: Option<OutputStyle>,
    /// Structured output schema
    pub output_schema: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SystemPromptMode {
    /// Replace default system prompt
    #[default]
    Replace,
    /// Append to default system prompt
    Append,
}

impl PromptConfig {
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }

    pub fn append_mode(mut self) -> Self {
        self.system_prompt_mode = SystemPromptMode::Append;
        self
    }

    pub fn output_style(mut self, style: OutputStyle) -> Self {
        self.output_style = Some(style);
        self
    }

    pub fn output_schema(mut self, schema: serde_json::Value) -> Self {
        self.output_schema = Some(schema);
        self
    }

    pub fn structured_output<T: schemars::JsonSchema>(mut self) -> Self {
        let schema = schemars::schema_for!(T);
        self.output_schema = serde_json::to_value(schema).ok();
        self
    }
}

/// Cache strategy determining which content types to cache.
///
/// Anthropic best practices recommend caching static content (system prompts,
/// tools) with longer TTLs and dynamic content (messages) with shorter TTLs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CacheStrategy {
    /// No caching - all content sent without cache_control
    Disabled,
    /// Cache system prompt only (static content with long TTL)
    SystemOnly,
    /// Cache messages only (last user turn with short TTL)
    MessagesOnly,
    /// Cache both system and messages (recommended)
    #[default]
    Full,
}

impl CacheStrategy {
    /// Returns true if system prompt caching is enabled
    pub fn cache_system(&self) -> bool {
        matches!(self, Self::SystemOnly | Self::Full)
    }

    /// Returns true if message caching is enabled
    pub fn cache_messages(&self) -> bool {
        matches!(self, Self::MessagesOnly | Self::Full)
    }

    /// Returns true if any caching is enabled
    pub fn is_enabled(&self) -> bool {
        !matches!(self, Self::Disabled)
    }
}

/// Cache configuration for prompt caching.
///
/// Implements Anthropic's prompt caching best practices:
/// - Static content (system prompt, CLAUDE.md) uses longer TTL (1 hour default)
/// - Dynamic content (messages) uses shorter TTL (5 minutes default)
/// - Long TTL content must come before short TTL content in requests
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Cache strategy determining which content types to cache
    pub strategy: CacheStrategy,
    /// TTL for static content (system prompt, tools, CLAUDE.md)
    pub static_ttl: crate::types::CacheTtl,
    /// TTL for message content (last user turn)
    pub message_ttl: crate::types::CacheTtl,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            strategy: CacheStrategy::Full,
            static_ttl: crate::types::CacheTtl::OneHour,
            message_ttl: crate::types::CacheTtl::FiveMinutes,
        }
    }
}

impl CacheConfig {
    /// Create a disabled cache configuration
    pub fn disabled() -> Self {
        Self {
            strategy: CacheStrategy::Disabled,
            ..Default::default()
        }
    }

    /// Create a system-only cache configuration
    pub fn system_only() -> Self {
        Self {
            strategy: CacheStrategy::SystemOnly,
            ..Default::default()
        }
    }

    /// Create a messages-only cache configuration
    pub fn messages_only() -> Self {
        Self {
            strategy: CacheStrategy::MessagesOnly,
            ..Default::default()
        }
    }

    /// Set the cache strategy
    pub fn strategy(mut self, strategy: CacheStrategy) -> Self {
        self.strategy = strategy;
        self
    }

    /// Set the TTL for static content
    pub fn static_ttl(mut self, ttl: crate::types::CacheTtl) -> Self {
        self.static_ttl = ttl;
        self
    }

    /// Set the TTL for message content
    pub fn message_ttl(mut self, ttl: crate::types::CacheTtl) -> Self {
        self.message_ttl = ttl;
        self
    }

    /// Get message TTL if message caching is enabled, None otherwise.
    ///
    /// This is a convenience method to avoid duplicating the cache_messages() check
    /// at every call site.
    pub fn message_ttl_option(&self) -> Option<crate::types::CacheTtl> {
        if self.strategy.cache_messages() {
            Some(self.message_ttl)
        } else {
            None
        }
    }
}

/// Server-side tools configuration.
///
/// Anthropic's built-in server-side tools (Brave Search, web fetch).
/// These are automatically enabled when "WebSearch" or "WebFetch" are in ToolAccess.
#[derive(Debug, Clone, Default)]
pub struct ServerToolsConfig {
    pub web_search: Option<crate::types::WebSearchTool>,
    pub web_fetch: Option<crate::types::WebFetchTool>,
}

impl ServerToolsConfig {
    pub fn all() -> Self {
        Self {
            web_search: Some(crate::types::WebSearchTool::default()),
            web_fetch: Some(crate::types::WebFetchTool::default()),
        }
    }

    pub fn web_search(mut self, config: crate::types::WebSearchTool) -> Self {
        self.web_search = Some(config);
        self
    }

    pub fn web_fetch(mut self, config: crate::types::WebFetchTool) -> Self {
        self.web_fetch = Some(config);
        self
    }
}

/// Complete agent configuration combining all domain configs.
#[derive(Debug, Clone, Default)]
pub struct AgentConfig {
    pub model: AgentModelConfig,
    pub execution: ExecutionConfig,
    pub security: SecurityConfig,
    pub budget: BudgetConfig,
    pub prompt: PromptConfig,
    pub cache: CacheConfig,
    pub working_dir: Option<PathBuf>,
    pub server_tools: ServerToolsConfig,
    pub coding_mode: bool,
}

impl AgentConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn model(mut self, config: AgentModelConfig) -> Self {
        self.model = config;
        self
    }

    pub fn execution(mut self, config: ExecutionConfig) -> Self {
        self.execution = config;
        self
    }

    pub fn security(mut self, config: SecurityConfig) -> Self {
        self.security = config;
        self
    }

    pub fn budget(mut self, config: BudgetConfig) -> Self {
        self.budget = config;
        self
    }

    pub fn prompt(mut self, config: PromptConfig) -> Self {
        self.prompt = config;
        self
    }

    pub fn cache(mut self, config: CacheConfig) -> Self {
        self.cache = config;
        self
    }

    pub fn working_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.working_dir = Some(dir.into());
        self
    }

    pub fn server_tools(mut self, config: ServerToolsConfig) -> Self {
        self.server_tools = config;
        self
    }

    pub fn coding_mode(mut self, enabled: bool) -> Self {
        self.coding_mode = enabled;
        self
    }
}

#[cfg(test)]
mod tests {
    use rust_decimal_macros::dec;

    use super::*;

    #[test]
    fn test_model_config() {
        let config = AgentModelConfig::new("claude-opus-4-6")
            .small("claude-haiku")
            .max_tokens(4096);

        assert_eq!(config.primary, "claude-opus-4-6");
        assert_eq!(config.small, "claude-haiku");
        assert_eq!(config.max_tokens, 4096);
    }

    #[test]
    fn test_execution_config() {
        let config = ExecutionConfig::default()
            .max_iterations(50)
            .timeout(Duration::from_secs(600))
            .auto_compact(false);

        assert_eq!(config.max_iterations, 50);
        assert_eq!(config.timeout, Some(Duration::from_secs(600)));
        assert!(!config.auto_compact);
    }

    #[test]
    fn test_security_config() {
        let config = SecurityConfig::permissive().env("API_KEY", "secret");

        assert_eq!(config.env.get("API_KEY"), Some(&"secret".to_string()));
    }

    #[test]
    fn test_budget_config() {
        let config = BudgetConfig::unlimited()
            .max_cost(dec!(10))
            .tenant("org-123")
            .fallback("claude-haiku");

        assert_eq!(config.max_cost_usd, Some(dec!(10)));
        assert_eq!(config.tenant_id, Some("org-123".to_string()));
        assert_eq!(config.fallback_model, Some("claude-haiku".to_string()));
    }

    #[test]
    fn test_agent_config() {
        let config = AgentConfig::new()
            .model(AgentModelConfig::new("claude-opus-4-6"))
            .budget(BudgetConfig::unlimited().max_cost(dec!(5)))
            .working_dir("/project");

        assert_eq!(config.model.primary, "claude-opus-4-6");
        assert_eq!(config.budget.max_cost_usd, Some(dec!(5)));
        assert_eq!(config.working_dir, Some(PathBuf::from("/project")));
    }

    #[test]
    fn test_cache_strategy_default_is_full() {
        let config = CacheConfig::default();
        assert_eq!(config.strategy, CacheStrategy::Full);
        assert_eq!(config.static_ttl, crate::types::CacheTtl::OneHour);
        assert_eq!(config.message_ttl, crate::types::CacheTtl::FiveMinutes);
    }

    #[test]
    fn test_cache_strategy_disabled() {
        let config = CacheConfig::disabled();
        assert_eq!(config.strategy, CacheStrategy::Disabled);
        assert!(!config.strategy.is_enabled());
        assert!(!config.strategy.cache_system());
        assert!(!config.strategy.cache_messages());
    }

    #[test]
    fn test_cache_strategy_system_only() {
        let config = CacheConfig::system_only();
        assert_eq!(config.strategy, CacheStrategy::SystemOnly);
        assert!(config.strategy.is_enabled());
        assert!(config.strategy.cache_system());
        assert!(!config.strategy.cache_messages());
    }

    #[test]
    fn test_cache_strategy_messages_only() {
        let config = CacheConfig::messages_only();
        assert_eq!(config.strategy, CacheStrategy::MessagesOnly);
        assert!(config.strategy.is_enabled());
        assert!(!config.strategy.cache_system());
        assert!(config.strategy.cache_messages());
    }

    #[test]
    fn test_cache_strategy_full() {
        let config = CacheConfig::default();
        assert!(config.strategy.is_enabled());
        assert!(config.strategy.cache_system());
        assert!(config.strategy.cache_messages());
    }

    #[test]
    fn test_cache_config_with_ttl() {
        let config = CacheConfig::default()
            .static_ttl(crate::types::CacheTtl::FiveMinutes)
            .message_ttl(crate::types::CacheTtl::OneHour);

        assert_eq!(config.static_ttl, crate::types::CacheTtl::FiveMinutes);
        assert_eq!(config.message_ttl, crate::types::CacheTtl::OneHour);
    }
}