Skip to main content

claude_code_agent/
compaction.rs

1//! Manual context compaction with custom instructions.
2//!
3//! `/compact <instructions>` sent as a user turn makes the CLI summarize the
4//! conversation, steering the summary with `instructions`. The turn's stream
5//! yields `AgentEvent::Compacted` and ends with `Done`.
6//!
7//! Fails with `AgentError::CommandUnavailable` when the CLI does not offer
8//! `/compact` (`SessionOptions::disable_slash_commands`): the text would
9//! reach the model as an ordinary prompt.
10//!
11//! Hooks see it too: `PreCompact` receives `trigger: "manual"` and
12//! `custom_instructions`; `PostCompact` receives `compact_summary`.
13//! Source: binary `PreCompact` / `PostCompact` hook input schemas,
14//!         `system/compact_boundary` schema
15use crate::agent::{Agent, AgentError, AgentStream};
16
17/// Compact the session's context now.
18pub async fn compact(agent: &Agent, instructions: Option<&str>) -> Result<AgentStream, AgentError> {
19    if !agent.session().offers_command("compact") {
20        return Err(AgentError::CommandUnavailable("compact".into()));
21    }
22    let command = match instructions {
23        Some(i) if !i.trim().is_empty() => format!("/compact {}", i.trim()),
24        _ => "/compact".to_string(),
25    };
26    agent.prompt(command).await
27}