Code Pluginsource linked

Session Compactv1.2.1

Smart session compaction plugin for OpenClaw to manage token usage and support unlimited conversation length.

openclaw-session-compact·runtime openclaw-session-compact·by @sdc-creator
Community code plugin. Review compatibility and verification before install.
openclaw plugins install clawhub:openclaw-session-compact
Latest release: v1.2.1Download zip

Capabilities

configSchema
Yes
Executes code
Yes
HTTP routes
0
Runtime ID
openclaw-session-compact

Compatibility

Built With Open Claw Version
2026.4.9
Plugin Api Range
>=2026.4.2
Security Scan
VirusTotalVirusTotal
Pending
View report →
OpenClawOpenClaw
Benign
medium confidence
Purpose & Capability
Name/description (session compaction) aligns with the included code (src/, dist/, openclaw.plugin.json), CLI commands, and config edits to ~/.openclaw/openclaw.json. The repo contains the expected entry points (dist/index.js, openclaw.plugin.json, bin/ script) and session persistence logic under ~/.openclaw/sessions — all coherent for a plugin that runs code.
Instruction Scope
SKILL.md instructs the user to clone into ~/.openclaw/extensions, run npm install --production and npm run build, modify ~/.openclaw/openclaw.json, and restart the OpenClaw gateway — these steps legitimately match a code plugin. However the docs and implementation notes mention invoking the OpenClaw CLI via execSync (callLLM uses CLI), which implies running shell commands built from program data; that pattern can be a source of command-injection bugs if not implemented carefully. Also building installs npm dependencies from the registry, which executes third‑party code on the host.
Install Mechanism
There is no platform-managed install spec; manual install requires git clone + npm install + npm run build. The source is a GitHub repository (expected), not an untrusted URL shortener. Still, npm install installs external packages and build scripts may run code — this is normal for code plugins but increases risk compared with an instruction-only skill.
Credentials
The skill declares no environment variables or unrelated credentials. The runtime behavior requires reading/writing OpenClaw configuration and session files under the user's home (~/.openclaw) and restarting the OpenClaw gateway — these accesses are proportionate to a session-management plugin.
Persistence & Privilege
The package is a code plugin (not a read-only skill) and will be loaded/executed by OpenClaw when enabled; it persists session data to ~/.openclaw/sessions and registers CLI commands. It does not set always: true. Because it runs code and may invoke shell commands, its autonomous execution by OpenClaw increases blast radius compared with documentation-only skills — review before enabling.
Assessment
This package appears to be what it claims (an OpenClaw code plugin) but it requires building and running third‑party JavaScript on your machine and the codebase notes use of shell execution to call the LLM. Before installing: 1) Inspect package.json scripts and dist/index.js (or build locally from src) for any postinstall/build scripts or use of child_process/execSync; 2) Review how callLLM() constructs shell commands to ensure user content is not interpolated unsafely; 3) Prefer installing from the official ClawHub package if available rather than running npm install from a clone; 4) Backup ~/.openclaw and test in an isolated environment (container or VM) first; 5) If you lack time to audit, treat this as higher‑risk: do not run as root and limit network/credential exposure. If you want, I can highlight exact files/lines that call execSync or run shell commands so you can review them.
dist/compact/engine.js:38
Shell command execution detected (child_process).
src/compact/engine.ts:64
Shell command execution detected (child_process).
Patterns worth reviewing
These patterns may indicate risky behavior. Check the VirusTotal and OpenClaw results above for context-aware analysis before installing.

Verification

Tier
source linked
Scope
artifact only
Summary
Validated package structure and linked the release to source metadata.
Commit
3e7e8ae1bede
Tag
3e7e8ae1bedebc605ab3657ebff276c6e180e590
Provenance
No
Scan status
pending

Tags

latest
1.2.1

OpenClaw Session Compact Plugin 🔄

Intelligent session compression plugin for OpenClaw that automatically manages token consumption and supports unlimited-length conversations. By automatically compressing historical messages into structured summaries, it significantly reduces token usage (typically 85-95% savings).

✨ Key Features

  • Automatic Compression: Triggers when session tokens approach threshold
  • Smart Summaries: Preserves key information (timeline, todos, files)
  • Seamless Continuation: Conversations continue without user intervention
  • Fallback Protection: Code-based extraction when LLM unavailable
  • Recursive Compression: Supports multiple compression cycles
  • CLI Commands: openclaw compact, openclaw compact-status, openclaw compact-config, openclaw sessions, openclaw session-info

🚀 Quick Start

1. Installation

From ClawHub (recommended):

# Install the code plugin
clawhub install openclaw-session-compact

Manual installation (if ClawHub is not available):

⚠️ Important: This plugin requires compilation. Do not skip the build step!

# Step 1: Clone the plugin
git clone https://github.com/SDC-creator/openclaw-session-compact.git \
  ~/.openclaw/extensions/openclaw-session-compact

# Step 2: Install dependencies
cd ~/.openclaw/extensions/openclaw-session-compact
npm install --production

# Step 3: Build the plugin (TypeScript → JavaScript)
npm run build

# Step 4: Verify the build
ls dist/index.js  # Should exist

Troubleshooting:

  • If you see plugin not found error, ensure dist/ directory exists
  • If build fails, check Node.js version (requires v18+ or v22+)

2. Plugin Configuration

After installation, configure the plugin in ~/.openclaw/openclaw.json:

{
  "plugins": {
    "allow": ["openclaw-session-compact"],
    "entries": {
      "openclaw-session-compact": {
        "enabled": true
      }
    }
  }
}

3. Restart Gateway

openclaw gateway restart

4. Verify Installation

openclaw status | grep session-compact
# Expected output: "openclaw-session-compact: loaded"

3. Compression Configuration (Optional)

Configure compression behavior in ~/.openclaw/openclaw.json:

{
  "plugins": {
    "entries": {
      "openclaw-session-compact": {
        "enabled": true,
        "config": {
          "max_tokens": 10000,
          "preserve_recent": 4,
          "auto_compact": true,
          "model": ""
        }
      }
    }
  }
}

Using CLI to set configuration (recommended):

# Set max_tokens threshold
openclaw config set plugins.entries.openclaw-session-compact.config.max_tokens 10000 --strict-json

# Set preserve_recent
openclaw config set plugins.entries.openclaw-session-compact.config.preserve_recent 4 --strict-json

# Set auto_compact
openclaw config set plugins.entries.openclaw-session-compact.config.auto_compact true --strict-json

# Restart gateway to apply changes
openclaw gateway restart

View current configuration:

openclaw config get plugins.entries.openclaw-session-compact.config

4. Usage

CLI Commands:

# Check current session status
openclaw compact-status

# Manually compress current session
openclaw compact

# Force compression (ignores threshold)
openclaw compact --force

# View configuration
openclaw compact-config

# View specific config value
openclaw compact-config max_tokens

# Set config value (not persisted)
openclaw compact-config max_tokens 5000

# List all saved sessions
openclaw sessions

# Show detailed session information
openclaw session-info --session-id my-session

Automatic Mode (Recommended):

# Start OpenClaw - compression works automatically
openclaw start
# Auto-compresses when conversation exceeds threshold

📊 How It Works

Compression Flow

1. Monitor token usage
   ↓
2. Exceeds threshold (90%)?
   ├─ No → Continue conversation
   └─ Yes → Trigger compression
        ↓
3. Keep last N messages (default: 4)
   ↓
4. Compress old messages into structured summary
   ├─ Scope: Statistics
   ├─ Recent requests: Last 3 user requests
   ├─ Pending work: To-dos
   ├─ Key files: Important files
   ├─ Tools used: Tools mentioned
   └─ Key timeline: Conversation timeline
   ↓
5. Replace old messages with System summary
   ↓
6. Seamlessly continue conversation

Compression Example

Before: 50 messages (1,250 tokens)

user: Message 1...
assistant: Message 2...
...
user: Message 49...
assistant: Message 50...

After: 5 messages (360 tokens) - 92% token savings

system: Summary:
- Scope: 46 earlier messages compacted
- Recent requests:
  - Message 37: Discussing complex problem
  - Message 41: File operations
  - Message 45: Tool usage details
- Pending work: Continue debugging
- Key timeline:
  - user: Message 37...
  - assistant: Message 38...
  - user: Message 39...

user: Message 49...
assistant: Message 50...

🔧 Configuration Reference

ParameterTypeDefaultDescriptionRecommended
max_tokensnumber10000Token threshold for compression5000-20000
preserve_recentnumber4Number of recent messages to keep4-6
auto_compactbooleantrueEnable automatic compressiontrue
modelstring''Model for summary generationGlobal default

Configuration Examples

Conservative Mode (frequent compression, max token savings):

{
  "max_tokens": 5000,
  "preserve_recent": 6
}

Aggressive Mode (fewer compressions, more context):

{
  "max_tokens": 20000,
  "preserve_recent": 3
}

📚 API Documentation

Core Functions

compactSession(messages, config)

Compresses a session and returns the result.

async function compactSession(
  messages: Array<{ role: string; content?: string }>,
  config: CompactConfig
): Promise<CompactionResult>

Parameters:

  • messages: Array of conversation messages
  • config: Configuration object

Returns:

interface CompactionResult {
  summary: string;           // Raw summary
  formattedSummary: string;  // Formatted summary
  removedCount: number;      // Messages removed
  savedTokens: number;       // Tokens saved
}

Example:

const result = await compactSession(messages, {
  max_tokens: 10000,
  preserve_recent: 4
});

console.log(`Removed ${result.removedCount} messages, saved ${result.savedTokens} tokens`);

shouldCompact(messages, config)

Checks if compression is needed.

function shouldCompact(
  messages: Array<{ content?: string }>,
  config: CompactConfig
): boolean

Example:

if (shouldCompact(messages, config)) {
  console.log('Compression needed');
}

estimateTokenCount(messages)

Estimates token count for messages.

function estimateTokenCount(
  messages: Array<{ content?: string }>
): number

Note: Uses simplified algorithm (4 chars ≈ 1 token).

🛠️ Development Guide

Local Development

# Navigate to project
cd <project-root>

# Install dependencies
npm install

# Build
npm run build

# Development mode (watch for changes)
npm run dev

# Run tests
npm test

# Check coverage
npm run test:coverage

Project Structure

openclaw-session-compact/
├── src/
│   ├── index.ts              # Plugin entry point (register function)
│   ├── compact/
│   │   ├── config.ts         # Configuration management
│   │   ├── engine.ts         # Core compression logic
│   │   └── __tests__/        # Unit tests (94 tests, 94.65% coverage)
│   │       ├── config.test.ts
│   │       ├── engine.test.ts
│   │       ├── engine-integration.test.ts
│   │       └── engine-mock.test.ts
│   └── cli/
│       └── register.ts       # CLI command registration (legacy)
├── bin/
│   └── openclaw-compact.js   # Standalone CLI entry point
├── package.json
├── openclaw.plugin.json      # OpenClaw plugin manifest
├── tsconfig.json
└── README.md

Plugin Architecture

This project is an OpenClaw plugin (not just a workspace skill). Key differences:

AspectWorkspace SkillPlugin
Locationworkspace/skills/~/.openclaw/extensions/
PurposeDocumentation for LLMExecutable code
EntrySKILL.md with frontmatterdist/index.js with register()
CLINot supportedSupported via api.registerCli()

Adding New Features

  1. Add new function in src/compact/engine.ts
  2. Add corresponding test in src/compact/__tests__/ or src/__tests__/
  3. Run npm run test:coverage to ensure coverage doesn't decrease
  4. Update README.md documentation
  5. Rebuild: npm run build
  6. Sync to extensions: copy dist/, package.json, openclaw.plugin.json to ~/.openclaw/extensions/openclaw-session-compact/

📦 Publishing to ClawHub

Prerequisites

  1. Login to ClawHub: clawhub login (GitHub OAuth)
  2. Verify identity: clawhub whoami

Publish as Code Plugin

# Build first
npm run build

# Publish to ClawHub
clawhub package publish . \
  --family code-plugin \
  --source-repo SDC-creator/openclaw-session-compact \
  --source-commit $(git rev-parse HEAD) \
  --version 1.0.0 \
  --changelog "Your changelog here" \
  --tags latest

Required package.json Fields

{
  "name": "openclaw-session-compact",
  "version": "1.0.0",
  "openclaw": {
    "extensions": ["./dist/index.js"],
    "compat": {
      "pluginApi": ">=2026.4.2"
    },
    "build": {
      "openclawVersion": "2026.4.5"
    }
  }
}

Verify Publication

clawhub package inspect openclaw-session-compact

📈 Performance Metrics

  • Test Coverage: 94.65% (94 tests passing)
  • Core Function Coverage: 89.76%
  • Average Compression Time: < 1 second (without LLM)
  • Token Savings: Typically 85-95%
  • Memory Usage: Low (no leaks)

🐛 Troubleshooting

Issue: Plugin Not Recognized

Cause: Missing plugin configuration Solution:

# Check plugin status
openclaw plugins list | grep compact

# Ensure plugin is in plugins.allow
# Add to openclaw.json:
# "plugins": { "allow": ["openclaw-session-compact"] }

Issue: Compression Not Triggered

Cause: Token count below threshold Solution:

# Check current token usage
openclaw compact-status

# Lower threshold for testing
openclaw compact-config max_tokens 1000

Issue: Poor Summary Quality

Cause: LLM misconfigured or unavailable Solution:

  • Verify model configuration
  • Ensure OpenClaw Gateway is running: openclaw gateway start
  • System auto-falls back to code extraction

Issue: Context Loss After Compression

Cause: preserve_recent set too low Solution:

{
  "preserve_recent": 6  // Increase to 6 or more
}

📝 Changelog

v1.2.0 (2026-04-11)

  • 🐛 Fixed: Configuration persistence — loadFromOpenClawConfig() correctly reads from plugins.entries.<id>.config
  • Added: 16 comprehensive test cases for OpenClaw config loading (163 total tests)
  • 📝 Improved: README with step-by-step installation guide and troubleshooting
  • 🔧 Updated: Dependencies — openclaw → 2026.4.9, basic-ftp → 5.2.2
  • 🔧 Updated: openclaw.build.openclawVersion → 2026.4.9

v1.1.0 (2026-04-11)

  • 🐛 Fixed: Configuration persistence issue - parameters now correctly persist to openclaw.json
  • Added: loadFromOpenClawConfig() function for proper configuration handling
  • Added: Debug logging for configuration troubleshooting
  • 📝 Updated: README with correct configuration path (plugins.entries.<id>.config)
  • 📝 Updated: Configuration examples using openclaw config set CLI commands
  • 🔧 Improved: Default max_tokens increased from 5000 to 10000
  • Verified: Configuration loading and persistence working correctly

v1.0.0 (2026-04-06)

  • ✨ Initial release
  • ✅ 94 unit tests passing (94.65% coverage)
  • ✅ CLI commands: compact, compact-status, compact-config
  • ✅ Plugin architecture with api.registerCli()
  • ✅ Published to ClawHub as code plugin
  • ✅ Compression functionality verified
  • ✅ Fallback mechanism validated
  • 📚 Complete documentation

🤝 Contributing

Contributions are welcome! Please submit Issues and Pull Requests.

  1. Fork the project
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

MIT License


Project Status: ✅ Stable Release Tests: ✅ 94/94 Passing Coverage: 📈 94.65% ClawHub: ✅ Published (openclaw-session-compact@1.2.0) Maintainer: SDC-creator

Chinese Documentation: SKILL_CN.md