cc-agent-sdk 0.1.7

claude agent sdk
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
590
591
592
//! Configuration types for Claude Agent SDK

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use typed_builder::TypedBuilder;

use super::hooks::{HookEvent, HookMatcher};
use super::mcp::McpServers;
use super::permissions::CanUseToolCallback;
use super::plugin::SdkPluginConfig;

/// Main configuration options for Claude Agent
#[derive(Clone, TypedBuilder)]
#[builder(doc)]
pub struct ClaudeAgentOptions {
    /// Tools configuration (list of tool names or preset)
    #[builder(default, setter(strip_option))]
    pub tools: Option<Tools>,
    /// List of allowed tool names
    #[builder(default, setter(into))]
    pub allowed_tools: Vec<String>,
    /// System prompt configuration
    #[builder(default, setter(into, strip_option))]
    pub system_prompt: Option<SystemPrompt>,
    /// MCP server configuration
    #[builder(default)]
    pub mcp_servers: McpServers,
    /// Permission mode
    #[builder(default, setter(strip_option))]
    pub permission_mode: Option<PermissionMode>,
    /// Whether to continue the conversation
    #[builder(default = false)]
    pub continue_conversation: bool,
    /// Session ID to resume
    #[builder(default, setter(into, strip_option))]
    pub resume: Option<String>,
    /// Maximum number of turns
    #[builder(default, setter(strip_option))]
    pub max_turns: Option<u32>,
    /// List of disallowed tool names
    #[builder(default, setter(into))]
    pub disallowed_tools: Vec<String>,
    /// Model to use
    #[builder(default, setter(strip_option, into))]
    pub model: Option<String>,
    /// Fallback model to use if primary model fails
    #[builder(default, setter(into, strip_option))]
    pub fallback_model: Option<String>,
    /// Beta features to enable
    /// See <https://docs.anthropic.com/en/api/beta-headers>
    #[builder(default, setter(into))]
    pub betas: Vec<SdkBeta>,
    /// Maximum budget in USD for the conversation
    #[builder(default, setter(strip_option))]
    pub max_budget_usd: Option<f64>,
    /// Maximum tokens for thinking blocks
    #[builder(default, setter(strip_option))]
    pub max_thinking_tokens: Option<u32>,
    /// Tool name for permission prompts
    #[builder(default, setter(into, strip_option))]
    pub permission_prompt_tool_name: Option<String>,
    /// Working directory
    #[builder(default, setter(into, strip_option))]
    pub cwd: Option<PathBuf>,
    /// Path to Claude CLI
    #[builder(default, setter(into, strip_option))]
    pub cli_path: Option<PathBuf>,
    /// Settings file path
    #[builder(default, setter(into, strip_option))]
    pub settings: Option<String>,
    /// Additional directories to include
    #[builder(default, setter(into))]
    pub add_dirs: Vec<PathBuf>,
    /// Environment variables
    #[builder(default)]
    pub env: HashMap<String, String>,
    /// Extra CLI arguments
    #[builder(default)]
    pub extra_args: HashMap<String, Option<String>>,
    /// Maximum buffer size for subprocess output
    ///
    /// **Deprecated:** Use `buffer_config` instead for more fine-grained control.
    /// This field is kept for backward compatibility and sets the max_message_size
    /// if buffer_config is not specified.
    #[builder(default, setter(strip_option))]
    pub max_buffer_size: Option<usize>,
    /// Dynamic buffer configuration for adaptive memory management
    ///
    /// When enabled, provides intelligent buffer sizing that adapts to message
    /// sizes while protecting against memory exhaustion.
    ///
    /// Default: Uses `DynamicBufferConfig::default()` with 64KB initial size
    /// and 50MB max message size.
    #[builder(default, setter(strip_option))]
    pub buffer_config: Option<DynamicBufferConfig>,
    /// Callback for stderr output
    #[builder(default, setter(strip_option))]
    pub stderr_callback: Option<Arc<dyn Fn(String) + Send + Sync>>,
    /// Callback for tool usage permission
    #[builder(default, setter(strip_option))]
    pub can_use_tool: Option<CanUseToolCallback>,
    /// Hook callbacks
    #[builder(default, setter(strip_option))]
    pub hooks: Option<HashMap<HookEvent, Vec<HookMatcher>>>,
    /// User identifier
    #[builder(default, setter(into, strip_option))]
    pub user: Option<String>,
    /// Whether to include partial messages in stream
    #[builder(default = false)]
    pub include_partial_messages: bool,
    /// Whether to fork the session
    #[builder(default = false)]
    pub fork_session: bool,
    /// Custom agent definitions
    #[builder(default, setter(strip_option))]
    pub agents: Option<HashMap<String, AgentDefinition>>,
    /// Setting sources to use.
    ///
    /// When `None`, the SDK does **not** load any filesystem settings,
    /// providing isolation for SDK applications.
    ///
    /// Programmatic options (like `agents`, `allowed_tools`) always override filesystem settings.
    #[builder(default, setter(strip_option))]
    pub setting_sources: Option<Vec<SettingSource>>,
    /// Sandbox configuration for bash command isolation
    /// Filesystem and network restrictions are derived from permission rules (Read/Edit/WebFetch),
    /// not from these sandbox settings.
    #[builder(default, setter(strip_option))]
    pub sandbox: Option<SandboxSettings>,
    /// Plugin configurations for custom plugins
    #[builder(default, setter(into))]
    pub plugins: Vec<SdkPluginConfig>,
    /// Output format for structured outputs (matches Messages API structure)
    /// Example: `json!({"type": "json_schema", "schema": {"type": "object", "properties": {...}}})`
    #[builder(default, setter(strip_option))]
    pub output_format: Option<serde_json::Value>,
    /// Enable file checkpointing to track file changes during the session.
    /// When enabled, files can be rewound to their state at any user message
    /// using `ClaudeClient.rewind_files()`.
    #[builder(default = false)]
    pub enable_file_checkpointing: bool,
    /// Enable automatic discovery and loading of SKILL.md files
    ///
    /// When enabled, the SDK will automatically scan and load skills from
    /// `.claude/skills/` directories (project, user, and local).
    ///
    /// Default: `false` (opt-in for backward compatibility)
    #[builder(default = false)]
    pub auto_discover_skills: bool,
    /// Custom project skills directory path
    ///
    /// If not specified, defaults to `.claude/skills/` relative to `cwd`.
    /// Only used when `auto_discover_skills` is `true`.
    #[builder(default, setter(into, strip_option))]
    pub project_skills_dir: Option<PathBuf>,
    /// Custom user skills directory path
    ///
    /// If not specified, defaults to `~/.config/claude/skills/`.
    /// Only used when `auto_discover_skills` is `true`.
    #[builder(default, setter(into, strip_option))]
    pub user_skills_dir: Option<PathBuf>,
    /// Automatically install Claude Code CLI if not found
    ///
    /// When enabled, the SDK will attempt to download and install the CLI
    /// on first use if it's not already available.
    ///
    /// Can also be enabled via environment variable: `CLAUDE_AUTO_INSTALL_CLI=true`
    ///
    /// Default: `false` (opt-in for backward compatibility)
    #[builder(default = false)]
    pub auto_install_cli: bool,
    /// Callback for CLI installation progress
    ///
    /// Provides real-time updates during automatic CLI installation.
    #[builder(default, setter(strip_option))]
    pub cli_install_callback: Option<Arc<dyn Fn(crate::internal::cli_installer::InstallProgress) + Send + Sync>>,
    /// Connection pool configuration for reusing CLI processes
    ///
    /// When enabled, the SDK maintains a pool of CLI worker processes
    /// to reduce the overhead of spawning new processes for each query.
    /// This can significantly improve latency from ~300ms to <100ms for
    /// repeated queries.
    ///
    /// Default: `None` (pool disabled, spawns new process per query)
    #[builder(default, setter(strip_option))]
    pub pool_config: Option<crate::internal::pool::PoolConfig>,
    /// Message parsing mode for JSON deserialization
    ///
    /// Controls how JSON messages from the CLI are parsed into `Message` types:
    ///
    /// - `ParsingMode::Traditional` (default): Uses intermediate `serde_json::Value`
    ///   for maximum compatibility. Safer but allocates more memory.
    /// - `ParsingMode::ZeroCopy`: Parses directly from string to Message without
    ///   intermediate allocation. Faster and uses less memory (~30-50% reduction).
    ///
    /// # Performance
    ///
    /// Zero-copy mode is recommended for high-throughput scenarios:
    /// - ~30-50% less memory allocation for large messages
    /// - ~10-20% faster parsing time
    ///
    /// Default: `ParsingMode::Traditional` (for backward compatibility)
    #[builder(default)]
    pub parsing_mode: crate::internal::message_parser::ParsingMode,
}

impl Default for ClaudeAgentOptions {
    fn default() -> Self {
        Self::builder().build()
    }
}

/// System prompt configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SystemPrompt {
    /// Direct text prompt
    Text(String),
    /// Preset-based prompt
    Preset(SystemPromptPreset),
}

impl From<String> for SystemPrompt {
    fn from(text: String) -> Self {
        SystemPrompt::Text(text)
    }
}

impl From<&str> for SystemPrompt {
    fn from(text: &str) -> Self {
        SystemPrompt::Text(text.to_string())
    }
}

/// System prompt preset
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemPromptPreset {
    /// Type field (always "preset")
    #[serde(rename = "type")]
    pub type_: String,
    /// Preset name (e.g., "claude_code")
    pub preset: String,
    /// Text to append to the preset
    #[serde(skip_serializing_if = "Option::is_none")]
    pub append: Option<String>,
}

impl SystemPromptPreset {
    /// Create a new preset with the given name
    pub fn new(preset: impl Into<String>) -> Self {
        Self {
            type_: "preset".to_string(),
            preset: preset.into(),
            append: None,
        }
    }

    /// Create a preset with appended text
    pub fn with_append(preset: impl Into<String>, append: impl Into<String>) -> Self {
        Self {
            type_: "preset".to_string(),
            preset: preset.into(),
            append: Some(append.into()),
        }
    }
}

/// Permission mode for tool execution
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum PermissionMode {
    /// Default permission mode
    #[serde(rename = "default")]
    Default,
    /// Accept edits automatically
    AcceptEdits,
    /// Plan mode
    #[serde(rename = "plan")]
    Plan,
    /// Bypass all permissions
    BypassPermissions,
}

/// Controls which filesystem-based configuration sources the SDK loads settings from.
///
/// When multiple sources are loaded, settings are merged with this precedence (highest to lowest):
/// 1. `Local`
/// 2. `Project`
/// 3. `User`
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SettingSource {
    /// User settings from `~/.claude/settings.json`
    User,
    /// Project settings from `.claude/settings.json` (team-shared settings)
    Project,
    /// Local settings from `.claude/settings.local.json` (highest priority, git-ignored)
    Local,
}

/// Custom agent definition
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct AgentDefinition {
    /// Agent description
    #[builder(setter(into))]
    pub description: String,
    /// Agent prompt
    #[builder(setter(into))]
    pub prompt: String,
    /// Tools available to the agent
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub tools: Option<Vec<String>>,
    /// Model to use for the agent
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub model: Option<AgentModel>,
}

/// Model selection for agents
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AgentModel {
    /// Claude Sonnet
    Sonnet,
    /// Claude Opus
    Opus,
    /// Claude Haiku
    Haiku,
    /// Inherit from parent
    Inherit,
}

/// SDK Beta features
/// See <https://docs.anthropic.com/en/api/beta-headers>
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SdkBeta {
    /// Extended context window (1M tokens)
    #[serde(rename = "context-1m-2025-08-07")]
    Context1M,
}

/// Tools configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Tools {
    /// List of tool names
    List(Vec<String>),
    /// Preset configuration
    Preset(ToolsPreset),
}

/// Tools preset configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolsPreset {
    /// Type field (always "preset")
    #[serde(rename = "type")]
    pub type_: String,
    /// Preset name (e.g., "claude_code")
    pub preset: String,
}

impl ToolsPreset {
    /// Create a new tools preset
    pub fn new(preset: impl Into<String>) -> Self {
        Self {
            type_: "preset".to_string(),
            preset: preset.into(),
        }
    }

    /// Create the default claude_code preset
    pub fn claude_code() -> Self {
        Self::new("claude_code")
    }
}

/// Network configuration for sandbox
#[derive(Debug, Clone, Default, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct SandboxNetworkConfig {
    /// Unix socket paths accessible in sandbox (e.g., SSH agents)
    #[serde(skip_serializing_if = "Option::is_none", rename = "allowUnixSockets")]
    #[builder(default, setter(into, strip_option))]
    pub allow_unix_sockets: Option<Vec<String>>,

    /// Allow all Unix sockets (less secure)
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "allowAllUnixSockets"
    )]
    #[builder(default, setter(strip_option))]
    pub allow_all_unix_sockets: Option<bool>,

    /// Allow binding to localhost ports (macOS only)
    #[serde(skip_serializing_if = "Option::is_none", rename = "allowLocalBinding")]
    #[builder(default, setter(strip_option))]
    pub allow_local_binding: Option<bool>,

    /// HTTP proxy port if bringing your own proxy
    #[serde(skip_serializing_if = "Option::is_none", rename = "httpProxyPort")]
    #[builder(default, setter(strip_option))]
    pub http_proxy_port: Option<u16>,

    /// SOCKS5 proxy port if bringing your own proxy
    #[serde(skip_serializing_if = "Option::is_none", rename = "socksProxyPort")]
    #[builder(default, setter(strip_option))]
    pub socks_proxy_port: Option<u16>,
}

/// Violations to ignore in sandbox
#[derive(Debug, Clone, Default, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct SandboxIgnoreViolations {
    /// File paths for which violations should be ignored
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub file: Option<Vec<String>>,

    /// Network hosts for which violations should be ignored
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub network: Option<Vec<String>>,
}

/// Sandbox settings configuration
///
/// Controls how Claude Code sandboxes bash commands for filesystem
/// and network isolation.
///
/// **Important:** Filesystem and network restrictions are configured via permission
/// rules, not via these sandbox settings:
/// - Filesystem read restrictions: Use Read deny rules
/// - Filesystem write restrictions: Use Edit allow/deny rules
/// - Network restrictions: Use WebFetch allow/deny rules
#[derive(Debug, Clone, Default, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct SandboxSettings {
    /// Enable bash sandboxing (macOS/Linux only). Default: False
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enabled: Option<bool>,

    /// Auto-approve bash commands when sandboxed. Default: True
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "autoAllowBashIfSandboxed"
    )]
    #[builder(default, setter(strip_option))]
    pub auto_allow_bash_if_sandboxed: Option<bool>,

    /// Commands that should run outside the sandbox (e.g., ["git", "docker"])
    #[serde(skip_serializing_if = "Option::is_none", rename = "excludedCommands")]
    #[builder(default, setter(into, strip_option))]
    pub excluded_commands: Option<Vec<String>>,

    /// Allow commands to bypass sandbox via dangerouslyDisableSandbox.
    /// When False, all commands must run sandboxed (or be in excludedCommands). Default: True
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "allowUnsandboxedCommands"
    )]
    #[builder(default, setter(strip_option))]
    pub allow_unsandboxed_commands: Option<bool>,

    /// Network configuration for sandbox
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub network: Option<SandboxNetworkConfig>,

    /// Violations to ignore
    #[serde(skip_serializing_if = "Option::is_none", rename = "ignoreViolations")]
    #[builder(default, setter(strip_option))]
    pub ignore_violations: Option<SandboxIgnoreViolations>,

    /// Enable weaker sandbox for unprivileged Docker environments
    /// (Linux only). Reduces security. Default: False
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "enableWeakerNestedSandbox"
    )]
    #[builder(default, setter(strip_option))]
    pub enable_weaker_nested_sandbox: Option<bool>,
}

/// Dynamic buffer configuration for subprocess output handling
///
/// Controls how the SDK manages memory buffers when reading JSON messages
/// from the Claude CLI subprocess. Dynamic buffering adapts to message sizes
/// while protecting against memory exhaustion.
///
/// # Example
/// ```ignore
/// use claude_agent_sdk::types::config::DynamicBufferConfig;
///
/// let config = DynamicBufferConfig::builder()
///     .initial_size(64 * 1024)        // 64KB initial buffer
///     .max_message_size(50 * 1024 * 1024) // 50MB max message
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct DynamicBufferConfig {
    /// Initial buffer capacity in bytes.
    ///
    /// This is the starting size for the line buffer. The buffer will grow
    /// dynamically as needed up to `max_message_size`.
    ///
    /// Default: 64KB (65536 bytes) - suitable for most messages
    #[builder(default = 64 * 1024)]
    #[serde(default = "default_initial_size")]
    pub initial_size: usize,

    /// Maximum allowed message size in bytes.
    ///
    /// Messages larger than this will trigger an error. This is a hard limit
    /// to prevent memory exhaustion from malformed or malicious responses.
    ///
    /// Default: 50MB (52,428,800 bytes) - handles large responses with images
    #[builder(default = 50 * 1024 * 1024)]
    #[serde(default = "default_max_message_size")]
    pub max_message_size: usize,

    /// Buffer growth factor when resizing is needed.
    ///
    /// When a message exceeds the current buffer capacity, the buffer is
    /// resized by multiplying current capacity by this factor.
    ///
    /// Default: 2.0 (double the buffer when needed)
    #[builder(default = 2.0)]
    #[serde(default = "default_growth_factor")]
    pub growth_factor: f64,

    /// Enable buffer usage metrics collection.
    ///
    /// When enabled, tracks peak buffer usage and message size statistics.
    /// Useful for tuning buffer configuration.
    ///
    /// Default: true
    #[builder(default = true)]
    #[serde(default = "default_enable_metrics")]
    pub enable_metrics: bool,
}

fn default_initial_size() -> usize {
    64 * 1024 // 64KB
}

fn default_max_message_size() -> usize {
    50 * 1024 * 1024 // 50MB
}

fn default_growth_factor() -> f64 {
    2.0
}

fn default_enable_metrics() -> bool {
    true
}

impl Default for DynamicBufferConfig {
    fn default() -> Self {
        Self::builder().build()
    }
}

/// Buffer usage metrics for monitoring and tuning
#[derive(Debug, Clone, Default)]
pub struct BufferMetrics {
    /// Peak buffer size used during the session
    pub peak_size: usize,
    /// Total number of messages processed
    pub message_count: usize,
    /// Total bytes processed
    pub total_bytes: usize,
    /// Number of buffer resizes
    pub resize_count: usize,
}

impl BufferMetrics {
    /// Get average message size
    pub fn average_message_size(&self) -> usize {
        if self.message_count == 0 {
            0
        } else {
            self.total_bytes / self.message_count
        }
    }
}