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
590
591
592
593
594
595
596
//! Context Compaction (Claude Code CLI compatible)
//!
//! Summarizes the entire conversation when context exceeds threshold.
//! Ported from Claude Code CLI's compact implementation for full compatibility.

use serde::{Deserialize, Serialize};

use super::state::{Session, SessionMessage};
use super::types::CompactRecord;
use super::{SessionError, SessionResult};
use crate::client::DEFAULT_SMALL_MODEL;
use crate::types::{CompactResult, ContentBlock, Role};

/// Context usage threshold for triggering compaction (80%).
pub const DEFAULT_COMPACT_THRESHOLD: f32 = 0.8;

/// Strategy for context compaction.
///
/// Controls when and how conversation history is summarized to fit within
/// context limits. The `keep_coding_instructions` flag determines whether
/// detailed coding information (code snippets, file changes, function
/// signatures) is preserved in summaries.
///
/// This flag mirrors `OutputStyle::keep_coding_instructions` for consistency.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CompactStrategy {
    pub enabled: bool,
    pub threshold_percent: f32,
    pub summary_model: String,
    pub max_summary_tokens: u32,
    /// When true, includes detailed coding information in summaries:
    /// - Full code snippets
    /// - File names and changes
    /// - Function signatures
    /// - Error details and fixes
    ///
    /// When false, creates a minimal summary focusing on:
    /// - Primary request and intent
    /// - Key decisions made
    /// - Current work status
    /// - Next steps
    ///
    /// This mirrors `OutputStyle::keep_coding_instructions` for API consistency.
    #[serde(default = "default_keep_coding_instructions")]
    pub keep_coding_instructions: bool,
    /// Optional custom instructions to append to the compact prompt.
    /// These are user-provided instructions for customizing the summary.
    #[serde(default)]
    pub custom_instructions: Option<String>,
}

fn default_keep_coding_instructions() -> bool {
    true
}

impl Default for CompactStrategy {
    fn default() -> Self {
        Self {
            enabled: true,
            threshold_percent: DEFAULT_COMPACT_THRESHOLD,
            summary_model: DEFAULT_SMALL_MODEL.to_string(),
            max_summary_tokens: 4000,
            keep_coding_instructions: true,
            custom_instructions: None,
        }
    }
}

impl CompactStrategy {
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            ..Default::default()
        }
    }

    pub fn threshold(mut self, percent: f32) -> Self {
        self.threshold_percent = percent.clamp(0.5, 0.95);
        self
    }

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

    /// Set whether to keep detailed coding information in summaries.
    ///
    /// This mirrors the `keep_coding_instructions` flag in `OutputStyle`.
    pub fn keep_coding_instructions(mut self, keep: bool) -> Self {
        self.keep_coding_instructions = keep;
        self
    }

    /// Set custom instructions for the compact prompt.
    pub fn custom_instructions(mut self, instructions: impl Into<String>) -> Self {
        self.custom_instructions = Some(instructions.into());
        self
    }

    /// Create a CompactStrategy that inherits coding instruction preference from OutputStyle.
    #[cfg(feature = "cli-integration")]
    pub fn from_output_style(style: &crate::output_style::OutputStyle) -> Self {
        Self {
            keep_coding_instructions: style.keep_coding_instructions,
            ..Default::default()
        }
    }
}

pub struct CompactExecutor {
    strategy: CompactStrategy,
}

impl CompactExecutor {
    pub fn new(strategy: CompactStrategy) -> Self {
        Self { strategy }
    }

    pub fn needs_compact(&self, current_tokens: u64, max_tokens: u64) -> bool {
        if !self.strategy.enabled {
            return false;
        }
        let threshold = (max_tokens as f32 * self.strategy.threshold_percent) as u64;
        current_tokens >= threshold
    }

    pub fn prepare_compact(&self, session: &Session) -> SessionResult<PreparedCompact> {
        if !self.strategy.enabled {
            return Err(SessionError::Compact {
                message: "Compact is disabled".to_string(),
            });
        }

        let messages = session.current_branch();
        if messages.is_empty() {
            return Ok(PreparedCompact::NotNeeded);
        }

        let summary_prompt = self.format_for_summary(&messages);

        Ok(PreparedCompact::Ready {
            summary_prompt,
            message_count: messages.len(),
        })
    }

    pub fn apply_compact(&self, session: &mut Session, summary: String) -> CompactResult {
        let original_count = session.messages.len();

        let removed_chars: usize = session
            .messages
            .iter()
            .map(|m| {
                m.content
                    .iter()
                    .filter_map(|c| c.as_text())
                    .map(|t| t.len())
                    .sum::<usize>()
            })
            .sum();
        let saved_tokens = (removed_chars / 4) as u64;

        // Build replacement message before modifying session (swap pattern)
        let summary_msg = SessionMessage::user(vec![ContentBlock::text(format!(
            "[Previous conversation summary]\n\n{}",
            summary
        ))])
        .as_compact_summary();

        let new_leaf_id = Some(summary_msg.id.clone());
        session.messages = vec![summary_msg];
        session.current_leaf_id = new_leaf_id;
        session.summary = Some(summary.clone());
        session.updated_at = chrono::Utc::now();

        CompactResult::Compacted {
            original_count,
            new_count: 1,
            saved_tokens: saved_tokens as usize,
            summary,
        }
    }

    pub fn record_compact(&self, session: &mut Session, result: &CompactResult) {
        if let CompactResult::Compacted {
            original_count,
            new_count,
            saved_tokens,
            summary,
        } = result
        {
            let record = CompactRecord::new(session.id)
                .counts(*original_count, *new_count)
                .summary(summary.clone())
                .saved_tokens(*saved_tokens);
            session.record_compact(record);
        }
    }

    fn format_for_summary(&self, messages: &[&SessionMessage]) -> String {
        let mut formatted = String::new();

        // Select prompt based on keep_coding_instructions flag
        let prompt = if self.strategy.keep_coding_instructions {
            COMPACTION_PROMPT_FULL
        } else {
            COMPACTION_PROMPT_MINIMAL
        };

        formatted.push_str(prompt);

        if let Some(ref instructions) = self.strategy.custom_instructions {
            formatted.push_str("\n\n");
            formatted.push_str("# Custom Summary Instructions\n\n");
            formatted.push_str(instructions);
        }

        formatted.push_str("\n\n---\n\n");
        formatted.push_str("# Conversation to summarize:\n\n");

        for msg in messages {
            let role = match msg.role {
                Role::User => "Human",
                Role::Assistant => "Assistant",
            };

            formatted.push_str(&format!("**{}**:\n", role));

            for block in &msg.content {
                if let Some(text) = block.as_text() {
                    // Truncate very long messages but keep more context than before
                    let display_text = if text.len() > 8000 {
                        let mut end = 8000;
                        while !text.is_char_boundary(end) {
                            end -= 1;
                        }
                        format!(
                            "{}... [truncated, {} chars total]",
                            &text[..end],
                            text.len()
                        )
                    } else {
                        text.to_string()
                    };
                    formatted.push_str(&display_text);
                    formatted.push('\n');
                }
            }
            formatted.push('\n');
        }

        formatted
    }

    pub fn strategy(&self) -> &CompactStrategy {
        &self.strategy
    }
}

/// Full compaction prompt with detailed coding information.
/// Ported from Claude Code CLI for full compatibility.
const COMPACTION_PROMPT_FULL: &str = r#"Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.

This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.

Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:

1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
   - The user's explicit requests and intents
   - Your approach to addressing the user's requests
   - Key decisions, technical concepts and code patterns
   - Specific details like:
     - file names
     - full code snippets
     - function signatures
     - file edits
   - Errors that you ran into and how you fixed them
   - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.

2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.

Your summary should include the following sections:

1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail

2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.

3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.

4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.

5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.

6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.

7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.

8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.

9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
   If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.

Here's an example of how your output should be structured:

<example>
<analysis>
[Your thought process, ensuring all points are covered thoroughly and accurately]
</analysis>

<summary>
1. Primary Request and Intent:
   [Detailed description]

2. Key Technical Concepts:
   - [Concept 1]
   - [Concept 2]
   - [...]

3. Files and Code Sections:
   - [File Name 1]
      - [Summary of why this file is important]
      - [Summary of the changes made to this file, if any]
      - [Important Code Snippet]
   - [File Name 2]
      - [Important Code Snippet]
   - [...]

4. Errors and fixes:
    - [Detailed description of error 1]:
      - [How you fixed the error]
      - [User feedback on the error if any]
    - [...]

5. Problem Solving:
   [Description of solved problems and ongoing troubleshooting]

6. All user messages:
    - [Detailed non tool use user message]
    - [...]

7. Pending Tasks:
   - [Task 1]
   - [Task 2]
   - [...]

8. Current Work:
   [Precise description of current work]

9. Optional Next Step:
   [Optional Next step to take]
</summary>
</example>

Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response."#;

/// Minimal compaction prompt without detailed coding information.
/// Used when keep_coding_instructions is false.
const COMPACTION_PROMPT_MINIMAL: &str = r#"Your task is to create a concise summary of the conversation so far, focusing on the essential context needed to continue the interaction.

Before providing your final summary, briefly analyze the conversation in <analysis> tags.

Your summary should include the following sections:

1. Primary Request and Intent: What the user is trying to accomplish

2. Key Decisions Made: Important choices and approaches decided upon

3. Current Status: What has been completed and what remains

4. Next Steps: If applicable, what should be done next

Here's an example of how your output should be structured:

<example>
<analysis>
[Brief thought process]
</analysis>

<summary>
1. Primary Request and Intent:
   [Concise description]

2. Key Decisions Made:
   - [Decision 1]
   - [Decision 2]

3. Current Status:
   [What's done and what remains]

4. Next Steps:
   [What to do next, if applicable]
</summary>
</example>

Please provide a focused summary based on the conversation so far."#;

#[derive(Debug)]
pub enum PreparedCompact {
    NotNeeded,
    Ready {
        summary_prompt: String,
        message_count: usize,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::state::SessionConfig;

    fn create_test_session(message_count: usize) -> Session {
        let mut session = Session::new(SessionConfig::default());

        for i in 0..message_count {
            let content = if i % 2 == 0 {
                format!("User message {}", i)
            } else {
                format!("Assistant response {}", i)
            };

            let msg = if i % 2 == 0 {
                SessionMessage::user(vec![ContentBlock::text(content)])
            } else {
                SessionMessage::assistant(vec![ContentBlock::text(content)])
            };

            session.add_message(msg);
        }

        session
    }

    #[test]
    fn test_compact_strategy_default() {
        let strategy = CompactStrategy::default();
        assert!(strategy.enabled);
        assert_eq!(strategy.threshold_percent, 0.8);
        assert!(strategy.keep_coding_instructions);
        assert!(strategy.custom_instructions.is_none());
    }

    #[test]
    fn test_compact_strategy_disabled() {
        let strategy = CompactStrategy::disabled();
        assert!(!strategy.enabled);
    }

    #[test]
    fn test_compact_strategy_with_keep_coding_instructions() {
        let strategy = CompactStrategy::default().keep_coding_instructions(false);
        assert!(!strategy.keep_coding_instructions);

        let strategy = CompactStrategy::default().keep_coding_instructions(true);
        assert!(strategy.keep_coding_instructions);
    }

    #[test]
    fn test_compact_strategy_with_custom_instructions() {
        let strategy = CompactStrategy::default()
            .custom_instructions("Focus on test output and code changes.");

        assert_eq!(
            strategy.custom_instructions,
            Some("Focus on test output and code changes.".to_string())
        );
    }

    #[test]
    fn test_needs_compact() {
        let executor = CompactExecutor::new(CompactStrategy::default().threshold(0.8));

        assert!(!executor.needs_compact(70_000, 100_000));
        assert!(executor.needs_compact(80_000, 100_000));
        assert!(executor.needs_compact(90_000, 100_000));
    }

    #[test]
    fn test_prepare_compact_empty() {
        let session = Session::new(SessionConfig::default());
        let executor = CompactExecutor::new(CompactStrategy::default());

        let result = executor.prepare_compact(&session).unwrap();
        assert!(matches!(result, PreparedCompact::NotNeeded));
    }

    #[test]
    fn test_prepare_compact_ready_full_prompt() {
        let session = create_test_session(10);
        let executor =
            CompactExecutor::new(CompactStrategy::default().keep_coding_instructions(true));

        let result = executor.prepare_compact(&session).unwrap();

        match result {
            PreparedCompact::Ready {
                summary_prompt,
                message_count,
            } => {
                // Full prompt should contain detailed sections
                assert!(summary_prompt.contains("Primary Request and Intent"));
                assert!(summary_prompt.contains("Key Technical Concepts"));
                assert!(summary_prompt.contains("Files and Code Sections"));
                assert!(summary_prompt.contains("Errors and fixes"));
                assert!(summary_prompt.contains("All user messages"));
                assert!(summary_prompt.contains("Optional Next Step"));
                assert_eq!(message_count, 10);
            }
            _ => panic!("Expected Ready"),
        }
    }

    #[test]
    fn test_prepare_compact_ready_minimal_prompt() {
        let session = create_test_session(10);
        let executor =
            CompactExecutor::new(CompactStrategy::default().keep_coding_instructions(false));

        let result = executor.prepare_compact(&session).unwrap();

        match result {
            PreparedCompact::Ready {
                summary_prompt,
                message_count,
            } => {
                // Minimal prompt should be concise
                assert!(summary_prompt.contains("Primary Request and Intent"));
                assert!(summary_prompt.contains("Key Decisions Made"));
                assert!(summary_prompt.contains("Current Status"));
                assert!(summary_prompt.contains("Next Steps"));
                // Should NOT contain detailed coding sections
                assert!(!summary_prompt.contains("Files and Code Sections"));
                assert!(!summary_prompt.contains("All user messages"));
                assert_eq!(message_count, 10);
            }
            _ => panic!("Expected Ready"),
        }
    }

    #[test]
    fn test_prepare_compact_with_custom_instructions() {
        let session = create_test_session(5);
        let executor = CompactExecutor::new(
            CompactStrategy::default()
                .custom_instructions("Focus on Rust code changes and test results."),
        );

        let result = executor.prepare_compact(&session).unwrap();

        match result {
            PreparedCompact::Ready { summary_prompt, .. } => {
                assert!(summary_prompt.contains("# Custom Summary Instructions"));
                assert!(summary_prompt.contains("Focus on Rust code changes and test results."));
            }
            _ => panic!("Expected Ready"),
        }
    }

    #[test]
    fn test_apply_compact() {
        let mut session = create_test_session(10);
        let executor = CompactExecutor::new(CompactStrategy::default());

        let result = executor.apply_compact(&mut session, "Test summary".to_string());

        match result {
            CompactResult::Compacted {
                original_count,
                new_count,
                ..
            } => {
                assert_eq!(original_count, 10);
                assert_eq!(new_count, 1);
            }
            _ => panic!("Expected Compacted"),
        }

        assert!(session.summary.is_some());
        assert_eq!(session.messages.len(), 1);
        assert!(session.messages[0].is_compact_summary);
    }

    #[test]
    fn test_prompt_contains_analysis_tags() {
        // Both prompts should instruct to use <analysis> tags
        assert!(COMPACTION_PROMPT_FULL.contains("<analysis>"));
        assert!(COMPACTION_PROMPT_MINIMAL.contains("<analysis>"));
    }

    #[test]
    fn test_prompt_contains_summary_tags() {
        // Both prompts should show <summary> in examples
        assert!(COMPACTION_PROMPT_FULL.contains("<summary>"));
        assert!(COMPACTION_PROMPT_MINIMAL.contains("<summary>"));
    }
}