Skip to content

Feature Request: Add "/compact" Command for Context Compression #13

Description

@will-lamerton

Description

Add a new /compact command that compresses the current message history into a smaller, more efficient representation while preserving essential information and context continuity.

Use Case

When working on long conversations or complex projects, message history can consume significant context space, leading to:

  • Context limit pressure: Approaching model token limits
  • Performance degradation: Slower responses due to large context
  • Loss of recent context: Important information gets truncated
  • Inefficient token usage: Redundant or verbose information taking up space

The /compact command addresses these issues by:

  • Preserving key information: Maintaining critical decisions, code changes, and context
  • Reducing redundancy: Eliminating repetitive exchanges and verbose explanations
  • Maintaining continuity: Keeping enough context for coherent conversation flow
  • Optimizing token usage: Maximizing available space for new interactions

This is especially valuable for users working on large codebases, long debugging sessions, or extended feature development.

Proposed Solution

Implement a /compact command that processes message history and creates a condensed version:

1. Message Analysis

Analyze conversation history to identify:

  • Key decisions and outcomes: Important conclusions reached
  • Code changes: Files modified, functions added/changed
  • Active context: Current working files, ongoing tasks
  • User preferences: Established patterns and requirements
  • Error resolutions: Successfully resolved issues

2. Compression Strategy

Apply intelligent compression techniques:

  • Summarize repetitive exchanges: Convert back-and-forth debugging into concise summaries
  • Consolidate file operations: Group multiple edits to the same file
  • Extract key insights: Preserve important discoveries and decisions
  • Maintain recent context: Keep last few messages at full detail
  • Preserve tool results: Retain essential command outputs and file contents

3. Output Format

🗜️ Context Compacted: 2,845 tokens → 1,230 tokens (57% reduction)

Preserved:
• 3 key decisions and outcomes
• 8 file modifications across 5 files
• Current task: implementing user authentication
• Last 2 full message exchanges
• 4 important tool results

Previous conversation summary available with /compact --show

4. Compression Modes

  • Default: Balanced compression maintaining good context
  • Aggressive (--aggressive): Maximum compression for tight limits
  • Conservative (--conservative): Minimal compression, safer approach
  • Preview (--preview): Show what would be compressed without applying

Technical Implementation

Command Structure

  • Location: src/core/commands/compact.ts
  • Integration: Add to existing command registry
  • Usage: /compact [--aggressive|--conservative|--preview|--show]

Message Processing Pipeline

  1. Message Classification: Categorize messages by importance and type
  2. Content Analysis: Identify key information using pattern matching
  3. Redundancy Detection: Find repetitive or verbose content
  4. Summarization Logic: Create concise summaries of lengthy exchanges
  5. Context Preservation: Ensure critical context remains intact

Compression Techniques

  • Template-based summaries: Use structured formats for common patterns
  • Code diff compression: Represent file changes more efficiently
  • Tool result filtering: Keep only essential command outputs
  • Conversation threading: Group related message chains
  • Smart truncation: Remove verbose explanations while keeping conclusions

Safety Measures

  • Backup original: Store original context in case of reversion needed
  • Validation checks: Ensure compressed context maintains coherence
  • User confirmation: Optional preview before applying compression
  • Undo capability: Allow restoration of original context

Integration Points

  • Message history access: Interface with ChatSession message storage
  • Token counting: Use existing tokenization for before/after metrics
  • Context management: Update session context efficiently
  • Tool integration: Handle tool call summaries appropriately

Acceptance Criteria

  • /compact command appears in help menu
  • Compresses message history while preserving key information
  • Shows before/after token count and reduction percentage
  • Provides different compression modes (default, aggressive, conservative)
  • Includes preview mode to show changes before applying
  • Maintains conversation continuity and context flow
  • Preserves recent messages at full detail
  • Handles tool results and code changes appropriately
  • Includes safety measures (backup, validation, confirmation)
  • Shows summary of what was preserved/compressed
  • Optional display of compressed content with --show

Additional Context

This feature would be particularly valuable for:

  • Long development sessions: Extended coding conversations
  • Complex debugging: Multi-step problem-solving processes
  • Code review workflows: Lengthy back-and-forth discussions
  • Feature development: Extended implementation conversations
  • Local model users: Working with smaller context windows

The compression should be intelligent enough to maintain the essential context needed for the AI to continue providing relevant assistance while significantly reducing token consumption.

Technical Considerations

  • Compression quality: Balance between size reduction and information preservation
  • Context coherence: Ensure compressed context doesn't break conversation flow
  • Performance: Compression process should be fast and efficient
  • Reversibility: Consider ability to expand or restore original context
  • Model compatibility: Work across different AI providers and models

Type of Change

  • New feature
  • Bug fix
  • Breaking change
  • Documentation update

Activity

  1. added
    enhancement
    on Aug 27, 2025
  2. Avtrkrb commented on Nov 23, 2025

    @Avtrkrb
    Member

    @JimStenstrom @will-lamerton
    An additional feature to be considered, having auto compression of the context length without the user explicitly having to call the /compact command would be nice.
    We can probably have the following:

    • a default compression mode set to conservative & allow users to modify that as per their wish.
    • trigger the auto compression at a set context length threshold like 75% or 80%.

    This will be useful in the scenario that the context length is consumed when a sequence of file edits or tool calls are happening & before the agent has produced a final response to the user.

  3. will-lamerton commented on Nov 23, 2025

    @will-lamerton
    MemberAuthor

    Hey @Avtrkrb - I like this, I'll amend the spec!

  4. will-lamerton commented on Nov 23, 2025

    @will-lamerton
    MemberAuthor

    Hey @Avtrkrb - here is an updated spec, let me know what you think?

    Compact Command Specification

    Description

    Add a new /compact command that compresses the current message history into a smaller, more efficient representation while preserving essential information and context continuity.

    Use Case

    When working on long conversations or complex projects, message history can consume significant context space, leading to:

    • Context limit pressure: Approaching model token limits
    • Performance degradation: Slower responses due to large context
    • Loss of recent context: Important information gets truncated
    • Inefficient token usage: Redundant or verbose information taking up space

    The /compact command addresses these issues by:

    • Preserving key information: Maintaining critical decisions, code changes, and context
    • Reducing redundancy: Eliminating repetitive exchanges and verbose explanations
    • Maintaining continuity: Keeping enough context for coherent conversation flow
    • Optimizing token usage: Maximizing available space for new interactions

    This is especially valuable for users working on large codebases, long debugging sessions, or extended feature development.

    Proposed Solution

    Implement a /compact command that processes message history and creates a condensed version:

    1. Message Analysis

    Analyze conversation history to identify:

    • Key decisions and outcomes: Important conclusions reached
    • Code changes: Files modified, functions added/changed
    • Active context: Current working files, ongoing tasks
    • User preferences: Established patterns and requirements
    • Error resolutions: Successfully resolved issues

    2. Compression Strategy

    Apply intelligent compression techniques:

    • Summarize repetitive exchanges: Convert back-and-forth debugging into concise summaries
    • Consolidate file operations: Group multiple edits to the same file
    • Extract key insights: Preserve important discoveries and decisions
    • Maintain recent context: Keep last few messages at full detail
    • Preserve tool results: Retain essential command outputs and file contents

    3. Output Format

    🗜️ Context Compacted: 2,845 tokens → 1,230 tokens (57% reduction)
    
    Preserved:
    • 3 key decisions and outcomes
    • 8 file modifications across 5 files
    • Current task: implementing user authentication
    • Last 2 full message exchanges
    • 4 important tool results
    
    Previous conversation summary available with /compact --show
    

    4. Compression Modes

    • Default: Balanced compression maintaining good context
    • Aggressive (--aggressive): Maximum compression for tight limits
    • Conservative (--conservative): Minimal compression, safer approach
    • Preview (--preview): Show what would be compressed without applying

    Auto-Compacting Feature

    Overview

    In addition to the manual /compact command, implement an automatic compacting feature that triggers when context usage reaches a configurable threshold.

    Configuration

    Add an autoCompact configuration option to agents.config.json:

    {
      "nanocoder": {
        "providers": [...],
        "autoCompact": {
          "enabled": true,
          "threshold": 80,
          "mode": "default",
          "notifyUser": true
        }
      }
    }

    Configuration Options

    Option Type Default Description
    enabled boolean true Enable/disable auto-compacting
    threshold number 60 Context usage percentage (1-95) that triggers auto-compact
    mode string "conservative" Compression mode: "default", "aggressive", or "conservative"
    notifyUser boolean true Show notification when auto-compact occurs

    Note: Auto-compacting is enabled by default even without explicit configuration. If no autoCompact settings are provided, nanocoder will use conservative mode at 60% threshold.

    Threshold Behavior

    When context usage reaches the configured threshold percentage:

    1. Detection: Monitor token count against model's context window size
    2. Trigger: When (current_tokens / max_tokens) * 100 >= threshold, initiate compaction
    3. Notification: If notifyUser is enabled, display:
      ⚠️ Context at 62% capacity - auto-compacting...
      🗜️ Context Compacted: 12,450 tokens → 6,230 tokens (50% reduction)
      
    4. Seamless continuation: Conversation continues without interruption

    Context Monitoring

    Implement continuous context monitoring:

    interface ContextMonitor {
      currentTokens: number;
      maxTokens: number;
      usagePercentage: number;
      shouldAutoCompact: boolean;
    }

    The monitor should:

    • Track token usage after each message exchange
    • Calculate usage percentage against model's context limit
    • Check against configured threshold
    • Trigger compaction when threshold is exceeded

    User Override

    Users can override auto-compact settings per session:

    • /compact --auto-off: Disable auto-compacting for current session
    • /compact --auto-on: Enable auto-compacting for current session
    • /compact --threshold 90: Temporarily set threshold to 90%

    Technical Implementation

    Command Structure

    • Location: source/commands/compact.ts
    • Integration: Add to existing command registry in source/commands/index.ts
    • Usage: /compact [--aggressive|--conservative|--preview|--show|--auto-on|--auto-off|--threshold <n>]

    Configuration Types

    Add to source/types/config.ts:

    interface AutoCompactConfig {
      enabled: boolean;
      threshold: number;  // 1-95
      mode: 'default' | 'aggressive' | 'conservative';
      notifyUser: boolean;
    }
    
    interface NanocoderConfig {
      providers: AIProviderConfig[];
      mcpServers?: MCPServer[];
      autoCompact?: AutoCompactConfig;
    }

    Context Monitor Implementation

    Create source/utils/context-monitor.ts:

    interface ContextMonitorConfig {
      maxTokens: number;
      threshold: number;
      onThresholdReached: () => void;
    }
    
    class ContextMonitor {
      private currentTokens: number = 0;
      private config: ContextMonitorConfig;
    
      updateTokenCount(tokens: number): void;
      getUsagePercentage(): number;
      shouldTriggerCompact(): boolean;
    }

    Message Processing Pipeline

    1. Message Classification: Categorize messages by importance and type
    2. Content Analysis: Identify key information using pattern matching
    3. Redundancy Detection: Find repetitive or verbose content
    4. Summarization Logic: Create concise summaries of lengthy exchanges
    5. Context Preservation: Ensure critical context remains intact

    Compression Techniques

    • Template-based summaries: Use structured formats for common patterns
    • Code diff compression: Represent file changes more efficiently
    • Tool result filtering: Keep only essential command outputs
    • Conversation threading: Group related message chains
    • Smart truncation: Remove verbose explanations while keeping conclusions

    Safety Measures

    • Backup original: Store original context in case of reversion needed
    • Validation checks: Ensure compressed context maintains coherence
    • User confirmation: Optional preview before applying compression (manual mode only)
    • Undo capability: Allow restoration of original context
    • Minimum threshold: Prevent threshold below 50% to avoid constant compaction

    Integration Points

    • Message history access: Interface with prompt-history.ts message storage
    • Token counting: Use existing tokenization via AI SDK for before/after metrics
    • Context management: Update session context efficiently via useAppState
    • Tool integration: Handle tool call summaries appropriately
    • Configuration loading: Read auto-compact settings from config/index.ts

    Hook Integration

    Add auto-compact logic to source/hooks/useChatHandler.tsx:

    // After each message exchange
    const checkAutoCompact = useCallback(() => {
      if (!autoCompactConfig?.enabled) return;
    
      const usage = contextMonitor.getUsagePercentage();
      if (usage >= autoCompactConfig.threshold) {
        performAutoCompact(autoCompactConfig.mode);
      }
    }, [autoCompactConfig, contextMonitor]);

    Acceptance Criteria

    Manual Compact Command

    • /compact command appears in help menu
    • Compresses message history while preserving key information
    • Shows before/after token count and reduction percentage
    • Provides different compression modes (default, aggressive, conservative)
    • Includes preview mode to show changes before applying
    • Maintains conversation continuity and context flow
    • Preserves recent messages at full detail
    • Handles tool results and code changes appropriately
    • Includes safety measures (backup, validation, confirmation)
    • Shows summary of what was preserved/compressed
    • Optional display of compressed content with --show

    Auto-Compact Feature

    • autoCompact configuration option available in agents.config.json
    • Configurable threshold percentage (default 60%)
    • Configurable compression mode for auto-compact
    • Optional user notification when auto-compact triggers
    • Context monitoring tracks token usage accurately
    • Auto-compact triggers when threshold is reached
    • Session-level overrides work (--auto-on, --auto-off, --threshold)
    • Minimum threshold enforced (50%) to prevent excessive compaction
    • Auto-compact respects the same safety measures as manual compact
    • /status command shows current context usage and auto-compact settings

    Example Configuration

    No Configuration (uses defaults)

    Auto-compacting works out of the box with no configuration required:

    • Enabled: true
    • Threshold: 60%
    • Mode: conservative
    • Notify User: true

    Disable Auto-Compact

    {
      "nanocoder": {
        "providers": [...],
        "autoCompact": {
          "enabled": false
        }
      }
    }

    Custom Threshold

    {
      "nanocoder": {
        "providers": [...],
        "autoCompact": {
          "threshold": 75
        }
      }
    }

    Full Configuration (override all defaults)

    {
      "nanocoder": {
        "providers": [...],
        "autoCompact": {
          "enabled": true,
          "threshold": 70,
          "mode": "default",
          "notifyUser": false
        }
      }
    }

    Aggressive Auto-Compact for Small Context Models

    {
      "nanocoder": {
        "providers": [...],
        "autoCompact": {
          "enabled": true,
          "threshold": 60,
          "mode": "aggressive",
          "notifyUser": false
        }
      }
    }

    Additional Context

    This feature would be particularly valuable for:

    • Long development sessions: Extended coding conversations
    • Complex debugging: Multi-step problem-solving processes
    • Code review workflows: Lengthy back-and-forth discussions
    • Feature development: Extended implementation conversations
    • Local model users: Working with smaller context windows
    • Unattended workflows: Auto-compact prevents context overflow during long operations

    The compression should be intelligent enough to maintain the essential context needed for the AI to continue providing relevant assistance while significantly reducing token consumption.

    Technical Considerations

    • Compression quality: Balance between size reduction and information preservation
    • Context coherence: Ensure compressed context doesn't break conversation flow
    • Performance: Compression process should be fast and efficient
    • Reversibility: Consider ability to expand or restore original context
    • Model compatibility: Work across different AI providers and models
    • Token counting accuracy: Ensure accurate token counting for threshold calculation
    • Race conditions: Handle cases where multiple messages arrive near threshold
    • Context window detection: Accurately detect model's context window size

    Type of Change

    • New feature
    • Bug fix
    • Breaking change
    • Documentation update
  5. Avtrkrb commented on Nov 23, 2025

    @Avtrkrb
    Member

    threshold number 80 Context usage percentage (1-95) that triggers auto-compact

    The updated spec looks awesome @will-lamerton ! Just a suggestion, I think the starting range for default context usage percentage can be set to 50-60%. I have some previous bad experiences when using Roo Code with Qwen 30B A3B from a homelab server that when context usage hit 50% the model started hallucinating. The default threshold value can still be 80%...

  6. will-lamerton commented on Nov 23, 2025

    @will-lamerton
    MemberAuthor

    @Avtrkrb Yeah now you mention it I've had similar experiences, even with Nanocoder. I'll amend and set as the main spec for now. Open to anyone else's thoughts!

  7. added
    high-priority
    on Jan 4, 2026
  8. Pahari47 commented on Jan 7, 2026

    @Pahari47
    Contributor

    Hii @will-lamerton, let me work on this

  9. will-lamerton commented on Jan 7, 2026

    @will-lamerton
    MemberAuthor

    Hii @will-lamerton, let me work on this

    Go for it 😎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementhigh-priority

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions