[Feature Request] Add compact() method for programmatic context compaction with custom instructions
Resolved 💬 2 comments Opened Feb 10, 2026 by cdxiaodong Closed Mar 11, 2026
Problem
The CLI supports /compact <custom_instructions> to compact conversation context with custom summarization instructions. However, the SDK provides no way to trigger this programmatically.
The current control protocol subtypes are: initialize, interrupt, set_permission_mode, set_model, rewind_files, mcp_status — there is no compact subtype.
The PreCompact hook only reads custom_instructions and trigger but cannot initiate compaction or modify the compaction instructions.
Proposed Solution
Add a compact() method to ClaudeSDKClient:
async with ClaudeSDKClient(options=options) as client:
# ... long conversation ...
# Compact with custom instructions
await client.compact(
instructions="Preserve all discovered vulnerabilities, open ports, and incomplete test tasks"
)
# Continue with compacted context
await client.query("Continue to next phase")
Implementation Suggestion
Add a new control request subtype "compact":
{
"type": "control_request",
"request": {
"subtype": "compact",
"custom_instructions": "Preserve all vulnerability findings..."
}
}
Use Cases
- Long-running agent sessions: Compact context periodically while preserving critical domain-specific information
- Phase transitions: When switching task phases, compact with phase-specific instructions (e.g., "keep recon findings, discard exploration attempts")
- Token budget management: Proactively compact before hitting token limits with domain-aware summarization
- Automated pipelines: Integration into CI/CD or automated testing workflows where manual
/compactis not possible
Environment
- SDK Version: 0.1.33
- CLI Version: 2.1.37
This issue has 2 comments on GitHub. Read the full discussion on GitHub ↗