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
//! Type definitions for V2 API
//!
//! This module contains the simplified types used by the V2 API.

use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;

/// Simplified session options for V2 API
///
/// `SessionOptions` contains only the most commonly used configuration parameters,
/// making it easier to configure Claude compared to the full `ClaudeAgentOptions`.
///
/// For advanced configuration, convert to `ClaudeAgentOptions` using `.into()`.
///
/// # Example
///
/// ```no_run
/// use claude_agent_sdk::v2::SessionOptions;
/// use claude_agent_sdk::v2::PermissionMode;
///
/// // Default configuration
/// let options = SessionOptions::default();
///
/// // Custom configuration
/// let options = SessionOptions::builder()
///     .model("claude-sonnet-4-20250514".to_string())
///     .max_turns(10)
///     .permission_mode(PermissionMode::BypassPermissions)
///     .build();
/// ```
#[derive(Debug, Clone, TypedBuilder, Serialize, Deserialize)]
#[derive(Default)]
pub struct SessionOptions {
    /// Model to use (None = system default)
    #[builder(default, setter(strip_option))]
    pub model: Option<String>,

    /// Permission mode for tool execution
    #[builder(default, setter(strip_option))]
    pub permission_mode: Option<PermissionMode>,

    /// Maximum budget in USD (None = no limit)
    #[builder(default, setter(strip_option))]
    pub max_budget_usd: Option<f64>,

    /// Maximum number of conversation turns
    #[builder(default, setter(strip_option))]
    pub max_turns: Option<u32>,

    /// Maximum thinking tokens for extended thinking
    #[builder(default, setter(strip_option))]
    pub max_thinking_tokens: Option<u32>,

    /// Custom system prompt
    #[builder(default, setter(strip_option))]
    pub system_prompt: Option<String>,

    /// Whether to include partial messages in stream
    #[builder(default = false)]
    pub include_partial_messages: bool,
}


impl From<SessionOptions> for crate::types::config::ClaudeAgentOptions {
    fn from(options: SessionOptions) -> Self {
        // Convert permission_mode if present
        let permission_mode: Option<crate::types::config::PermissionMode> =
            options.permission_mode.map(|pm| pm.into());

        // Convert system_prompt to SystemPrompt if present
        let system_prompt: Option<crate::types::config::SystemPrompt> =
            options.system_prompt.map(crate::types::config::SystemPrompt::Text);

        // Build ClaudeAgentOptions using builder with conditional field setting
        // Since we can't use if-else with builder reassignment due to TypedBuilder's type system,
        // we use a match to handle the different cases
        match (options.model, permission_mode, options.max_budget_usd) {
            (Some(model), Some(pm), Some(max_budget)) => {
                crate::types::config::ClaudeAgentOptions::builder()
                    .model(model)
                    .permission_mode(pm)
                    .max_budget_usd(max_budget)
                    .max_turns(options.max_turns.unwrap_or(0))
                    .max_thinking_tokens(options.max_thinking_tokens.unwrap_or(0))
                    .system_prompt(system_prompt.unwrap_or(
                        crate::types::config::SystemPrompt::Text(String::new())
                    ))
                    .include_partial_messages(options.include_partial_messages)
                    .build()
            }
            (Some(model), Some(pm), None) => {
                crate::types::config::ClaudeAgentOptions::builder()
                    .model(model)
                    .permission_mode(pm)
                    .max_turns(options.max_turns.unwrap_or(0))
                    .max_thinking_tokens(options.max_thinking_tokens.unwrap_or(0))
                    .system_prompt(system_prompt.unwrap_or(
                        crate::types::config::SystemPrompt::Text(String::new())
                    ))
                    .include_partial_messages(options.include_partial_messages)
                    .build()
            }
            (Some(model), None, Some(max_budget)) => {
                crate::types::config::ClaudeAgentOptions::builder()
                    .model(model)
                    .max_budget_usd(max_budget)
                    .max_turns(options.max_turns.unwrap_or(0))
                    .max_thinking_tokens(options.max_thinking_tokens.unwrap_or(0))
                    .system_prompt(system_prompt.unwrap_or(
                        crate::types::config::SystemPrompt::Text(String::new())
                    ))
                    .include_partial_messages(options.include_partial_messages)
                    .build()
            }
            (Some(model), None, None) => {
                crate::types::config::ClaudeAgentOptions::builder()
                    .model(model)
                    .max_turns(options.max_turns.unwrap_or(0))
                    .max_thinking_tokens(options.max_thinking_tokens.unwrap_or(0))
                    .system_prompt(system_prompt.unwrap_or(
                        crate::types::config::SystemPrompt::Text(String::new())
                    ))
                    .include_partial_messages(options.include_partial_messages)
                    .build()
            }
            (None, Some(pm), Some(max_budget)) => {
                crate::types::config::ClaudeAgentOptions::builder()
                    .permission_mode(pm)
                    .max_budget_usd(max_budget)
                    .max_turns(options.max_turns.unwrap_or(0))
                    .max_thinking_tokens(options.max_thinking_tokens.unwrap_or(0))
                    .system_prompt(system_prompt.unwrap_or(
                        crate::types::config::SystemPrompt::Text(String::new())
                    ))
                    .include_partial_messages(options.include_partial_messages)
                    .build()
            }
            (None, Some(pm), None) => {
                crate::types::config::ClaudeAgentOptions::builder()
                    .permission_mode(pm)
                    .max_turns(options.max_turns.unwrap_or(0))
                    .max_thinking_tokens(options.max_thinking_tokens.unwrap_or(0))
                    .system_prompt(system_prompt.unwrap_or(
                        crate::types::config::SystemPrompt::Text(String::new())
                    ))
                    .include_partial_messages(options.include_partial_messages)
                    .build()
            }
            (None, None, Some(max_budget)) => {
                crate::types::config::ClaudeAgentOptions::builder()
                    .max_budget_usd(max_budget)
                    .max_turns(options.max_turns.unwrap_or(0))
                    .max_thinking_tokens(options.max_thinking_tokens.unwrap_or(0))
                    .system_prompt(system_prompt.unwrap_or(
                        crate::types::config::SystemPrompt::Text(String::new())
                    ))
                    .include_partial_messages(options.include_partial_messages)
                    .build()
            }
            (None, None, None) => {
                crate::types::config::ClaudeAgentOptions::builder()
                    .max_turns(options.max_turns.unwrap_or(0))
                    .max_thinking_tokens(options.max_thinking_tokens.unwrap_or(0))
                    .system_prompt(system_prompt.unwrap_or(
                        crate::types::config::SystemPrompt::Text(String::new())
                    ))
                    .include_partial_messages(options.include_partial_messages)
                    .build()
            }
        }
    }
}

/// Permission mode for tool execution
///
/// Controls how Claude requests permission to use tools.
///
/// # Variants
///
/// * `Default` - Default permission mode
/// * `AcceptEdits` - Accept edits automatically
/// * `Plan` - Plan mode
/// * `BypassPermissions` - Auto-approve all tool usage
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PermissionMode {
    /// Default permission mode
    Default,

    /// Accept edits automatically
    AcceptEdits,

    /// Plan mode
    Plan,

    /// Auto-approve all tool usage
    BypassPermissions,
}

impl From<PermissionMode> for crate::types::config::PermissionMode {
    fn from(mode: PermissionMode) -> Self {
        match mode {
            PermissionMode::Default => Self::Default,
            PermissionMode::AcceptEdits => Self::AcceptEdits,
            PermissionMode::Plan => Self::Plan,
            PermissionMode::BypassPermissions => Self::BypassPermissions,
        }
    }
}

/// Result of a one-shot prompt
///
/// Contains the response text and metadata from a `prompt()` call.
///
/// # Example
///
/// ```no_run
/// # use claude_agent_sdk::v2::PromptResult;
/// let result = PromptResult {
///     content: "The answer is 4".to_string(),
///     input_tokens: 15,
///     output_tokens: 5,
///     model: Some("claude-sonnet-4-20250514".to_string()),
///     buffer_metrics: None,
/// };
///
/// println!("Response: {}", result.content);
/// println!("Total tokens: {}", result.total_tokens());
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptResult {
    /// The text content of Claude's response
    pub content: String,

    /// Number of tokens in the input
    pub input_tokens: u64,

    /// Number of tokens in the output
    pub output_tokens: u64,

    /// Model used for generation (if known)
    pub model: Option<String>,

    /// Buffer metrics from the transport layer (if available)
    ///
    /// This provides insight into buffer usage during the query,
    /// including peak size, message count, and resize operations.
    /// Only available when using `SubprocessTransport` without pooling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buffer_metrics: Option<crate::internal::transport::BufferMetricsSnapshot>,
}

impl PromptResult {
    /// Get the total token usage (input + output)
    pub fn total_tokens(&self) -> u64 {
        self.input_tokens + self.output_tokens
    }

    /// Get the cost in USD (approximate)
    ///
    /// This is a rough estimate based on public pricing.
    /// Actual costs may vary.
    pub fn estimated_cost_usd(&self) -> f64 {
        // Rough pricing (subject to change)
        // Input: $3/M tokens, Output: $15/M tokens
        let input_cost = (self.input_tokens as f64) / 1_000_000.0 * 3.0;
        let output_cost = (self.output_tokens as f64) / 1_000_000.0 * 15.0;
        input_cost + output_cost
    }
}

/// Simplified message type for V2 API
///
/// This is a simplified version of the full `Message` type,
/// containing only the most essential information.
///
/// # Variants
///
/// * `User` - Message from the user
/// * `Assistant` - Response from Claude
/// * `ToolResult` - Result from a tool execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Message {
    /// Message from the user
    User {
        /// The text content
        content: String,
    },

    /// Response from Claude
    Assistant {
        /// The text content
        content: String,
    },

    /// Result from a tool execution
    ToolResult {
        /// Tool name
        tool_name: String,
        /// Tool result
        result: String,
    },
}

impl Message {
    /// Get the content text as a string (if applicable)
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Message::User { content } => Some(content),
            Message::Assistant { content } => Some(content),
            Message::ToolResult { .. } => None,
        }
    }

    /// Check if this is a user message
    pub fn is_user(&self) -> bool {
        matches!(self, Message::User { .. })
    }

    /// Check if this is an assistant message
    pub fn is_assistant(&self) -> bool {
        matches!(self, Message::Assistant { .. })
    }

    /// Check if this is a tool result
    pub fn is_tool_result(&self) -> bool {
        matches!(self, Message::ToolResult { .. })
    }
}

impl From<crate::types::messages::Message> for Message {
    fn from(msg: crate::types::messages::Message) -> Self {
        match msg {
            crate::types::messages::Message::User(user_msg) => {
                // Extract text from user message
                // UserMessage has text: Option<String> and content: Option<Vec<ContentBlock>>
                let content = if let Some(text) = user_msg.text {
                    text
                } else if let Some(blocks) = user_msg.content {
                    blocks
                        .iter()
                        .filter_map(|block| match block {
                            crate::types::messages::ContentBlock::Text(text) => Some(text.text.clone()),
                            _ => None,
                        })
                        .collect::<Vec<_>>()
                        .join("\n")
                } else {
                    String::new()
                };

                Message::User { content }
            }
            crate::types::messages::Message::Assistant(assist_msg) => {
                // Extract text from assistant message
                let content = assist_msg
                    .message
                    .content
                    .iter()
                    .filter_map(|block| match block {
                        crate::types::messages::ContentBlock::Text(text) => Some(text.text.clone()),
                        _ => None,
                    })
                    .collect::<Vec<_>>()
                    .join("\n");

                Message::Assistant { content }
            }
            _ => Message::Assistant {
                content: String::new(),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_session_options_builder() {
        let options = SessionOptions::builder()
            .model("claude-sonnet-4-20250514".to_string())
            .max_turns(5)
            .build();

        assert_eq!(options.model, Some("claude-sonnet-4-20250514".to_string()));
        assert_eq!(options.max_turns, Some(5));
    }

    #[test]
    fn test_permission_mode_conversion() {
        let mode = PermissionMode::BypassPermissions;
        let converted: crate::types::config::PermissionMode = mode.into();
        assert!(matches!(
            converted,
            crate::types::config::PermissionMode::BypassPermissions
        ));
    }

    #[test]
    fn test_prompt_result_total_tokens() {
        let result = PromptResult {
            content: "Test".to_string(),
            input_tokens: 100,
            output_tokens: 50,
            model: None,
            buffer_metrics: None,
        };

        assert_eq!(result.total_tokens(), 150);
    }

    #[test]
    fn test_message_is_user() {
        let msg = Message::User {
            content: "Hello".to_string(),
        };

        assert!(msg.is_user());
        assert!(!msg.is_assistant());
        assert_eq!(msg.as_text(), Some("Hello"));
    }

    #[test]
    fn test_message_is_assistant() {
        let msg = Message::Assistant {
            content: "Hi there!".to_string(),
        };

        assert!(!msg.is_user());
        assert!(msg.is_assistant());
        assert_eq!(msg.as_text(), Some("Hi there!"));
    }

    #[test]
    fn test_message_is_tool_result() {
        let msg = Message::ToolResult {
            tool_name: "calculator".to_string(),
            result: "42".to_string(),
        };

        assert!(msg.is_tool_result());
        assert!(!msg.is_user());
        assert!(!msg.is_assistant());
        assert_eq!(msg.as_text(), None);
    }

    #[test]
    fn test_prompt_result_cost_estimation() {
        let result = PromptResult {
            content: "Test".to_string(),
            input_tokens: 1_000_000, // 1M input tokens
            output_tokens: 1_000_000, // 1M output tokens
            model: None,
            buffer_metrics: None,
        };

        // 1M input * $3/M = $3
        // 1M output * $15/M = $15
        // Total = $18
        let cost = result.estimated_cost_usd();
        assert!((cost - 18.0).abs() < 0.01); // Allow small floating point error
    }
}