Zero-latency middleware for Claude Code that enables query collection, analysis, and optimization through a plugin-based architecture.
- Zero-Latency Passthrough: CLI output is never delayed by processing
- Plugin System: Extensible middleware architecture
- Query Collection: Automatic storage and categorization of all queries
- SDK Integration: Works with both CLI and TypeScript SDK
- Token Optimization: Identifies opportunities to save tokens
- Error Isolation: Plugin failures don't affect Claude Code operation
- Hot Reloading: Add/remove plugins without restart (coming soon)
- Node.js 18+
- Claude Code CLI installed and authenticated
- TypeScript (for development)
npm install -g @instantlyeasy/claudewaregit clone https://github.com/instantlyeasy/claudeware.git
cd claudeware
npm install
npm run build
npm linkSimply prefix your Claude Code commands with claudeware:
# Instead of:
claude-code "What is 2 + 2?"
# Use:
claudeware "What is 2 + 2?"All Claude Code functionality remains unchanged, but your queries are now being collected and analyzed in the background.
import { createWrappedSDK } from '@instantlyeasy/claudeware';
// Create wrapped SDK instance
const wrappedClaude = createWrappedSDK({
pluginDirectory: '~/.claude-code/plugins',
databasePath: './queries.db'
});
// Use exactly like the Claude Code SDK
const result = await wrappedClaude()
.withModel('sonnet')
.query('Hello Claude')
.asText();
// Get metrics from plugins
const metrics = await wrappedClaude.getMetrics();
console.log('Tokens used:', metrics.sessionMetrics.totalTokens);See the SDK integration examples for comprehensive usage patterns.
The wrapper uses a decoupled architecture to ensure zero latency:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Claude Code │────▶│ Process Manager │────▶│ Stream Handler │
│ CLI │ │ │ │ │
└─────────────────┘ └─────────────────┘ └───────┬─────────┘
│
┌────────────────────┴───────┐
│ │
Direct Pipe JSON Parser
(Zero Latency) (Processing)
│ │
▼ ▼
Terminal Output Event Bus
│
┌─────┴─────┐
▼ ▼
Plugins Database
- Process Manager: Manages Claude Code child process lifecycle
- Stream Handler: Implements zero-latency passthrough with parallel processing
- Event Bus: Distributes events to plugins with error isolation
- Plugin Loader: Discovers and manages plugins with dependency resolution
- Database Layer: SQLite storage with batching and analytics
# Wrapper configuration
CLAUDE_WRAPPER_MODE=production # production | development
CLAUDE_WRAPPER_PLUGINS_DIR=~/.claude-code/plugins
CLAUDE_WRAPPER_DB_PATH=./claude-queries.db
CLAUDE_WRAPPER_LOG_LEVEL=info # debug | info | warn | error
# Plugin configuration
CLAUDE_WRAPPER_PLUGIN_TIMEOUT=5000 # Plugin execution timeout (ms)
CLAUDE_WRAPPER_PLUGIN_RETRIES=3 # Retry attempts for failed pluginsCreate ~/.claude-code/wrapper.config.json:
{
"wrapper": {
"timeout": 30000,
"bufferSize": 65536,
"gracefulShutdownTimeout": 5000
},
"plugins": {
"directory": "~/.claude-code/plugins",
"timeout": 5000,
"retryAttempts": 3,
"enabledPlugins": ["query-collector", "rate-limiter"],
"disabledPlugins": []
},
"database": {
"type": "sqlite",
"path": "~/.claude-code/queries.db",
"batchSize": 100,
"flushInterval": 1000,
"walMode": true
},
"monitoring": {
"enabled": true,
"metricsPort": 9090,
"logLevel": "info"
}
}The claudeware wrapper includes a powerful plugin system for extending functionality.
Automatically categorizes and analyzes all queries:
{
"name": "query-collector",
"version": "1.0.0",
"capabilities": ["query-analysis", "optimization-suggestions"]
}Features:
- Categorizes queries (code, debug, explain, refactor, test)
- Calculates complexity (low, medium, high)
- Suggests model optimizations
- Tracks token usage
See Plugin API Documentation for detailed information.
Quick example:
// my-plugin/index.ts
export default class MyPlugin implements Plugin {
name = 'my-plugin';
version = '1.0.0';
manifest = {
name: 'my-plugin',
version: '1.0.0',
dependencies: [],
priority: 10,
timeout: 5000,
capabilities: ['custom-analysis']
};
async initialize(context: PluginContext) {
context.logger.info('MyPlugin initialized');
}
async onEvent(event: QueryEvent, context: PluginContext) {
if (event.type === 'query') {
// Process query
await context.dataStore.saveQuery({
id: event.id,
query: event.data.content,
// ... additional processing
});
}
}
async shutdown() {
// Cleanup
}
}- Create plugin directory:
mkdir -p ~/.claude-code/plugins/my-plugin- Add manifest.json:
{
"name": "my-plugin",
"version": "1.0.0",
"main": "./index.js",
"dependencies": [],
"priority": 10,
"timeout": 5000,
"capabilities": ["custom-analysis"]
}- Add your plugin code
- Restart wrapper (or wait for hot reload)
The wrapper provides seamless SDK integration:
import { createWrappedSDK } from 'claudeware';
import { claude } from '@instantlyeasy/claude-code-sdk-ts';
// Option 1: Use wrapped SDK factory
const wrappedSDK = createWrappedSDK({
pluginDirectory: './plugins',
enabledPlugins: ['query-collector', 'cache']
});
// Option 2: Manual integration with existing SDK
const client = claude()
.withRetry({ maxAttempts: 3 })
.build();
// Wrap with plugin support
const { query } = wrapSDK(client, {
plugins: ['query-collector']
});Access collected query data:
import Database from 'better-sqlite3';
const db = new Database('~/.claude-code/queries.db');
// Get query statistics
const stats = db.prepare(`
SELECT
COUNT(*) as total_queries,
SUM(token_count) as total_tokens,
AVG(latency_ms) as avg_latency
FROM queries
WHERE timestamp > datetime('now', '-7 days')
`).get();
// Get queries by category
const categories = db.prepare(`
SELECT category, COUNT(*) as count
FROM queries
GROUP BY category
ORDER BY count DESC
`).all();
// Find optimization opportunities
const expensiveSimpleQueries = db.prepare(`
SELECT q.*, r.input_tokens + r.output_tokens as total_tokens
FROM queries q
JOIN responses r ON q.id = r.query_id
WHERE q.complexity = 'low'
AND q.model LIKE '%opus%'
AND total_tokens < 100
ORDER BY total_tokens DESC
`).all();# Clone repository
git clone https://github.com/instantlyeasy/claudeware.git
cd claudeware
# Install dependencies
npm install
# Run tests
npm test
# Build
npm run build
# Run in development mode
npm run dev# Run all tests
npm test
# Run specific component tests
npm test stream-handler
npm test plugin-loader
# Run with coverage
npm run test:coverage
# Run integration tests
npm run test:integrationclaudeware/
├── src/
│ ├── core/ # Core components
│ │ ├── wrapper.ts # Main wrapper orchestrator
│ │ ├── stream-handler.ts
│ │ ├── process-manager.ts
│ │ └── json-parser.ts
│ ├── plugins/ # Plugin system
│ │ ├── plugin-loader.ts
│ │ ├── event-bus.ts
│ │ └── builtin/ # Built-in plugins
│ ├── database/ # Data layer
│ │ ├── sqlite-adapter.ts
│ │ └── batch-queue.ts
│ ├── adapters/ # Integration adapters
│ │ └── sdk-adapter.ts
│ └── types/ # TypeScript types
├── tests/ # Test suites
├── docs/ # Documentation
└── examples/ # Usage examples
Creates a wrapped SDK instance with plugin support.
const { query, getMetrics, shutdown } = createWrappedSDK({
pluginDirectory: './plugins',
databasePath: './queries.db',
enabledPlugins: ['query-collector'],
logLevel: 'info'
});Main wrapper class for CLI integration.
const wrapper = new ClaudeWrapper(config);
await wrapper.start(args, stdin, stdout, stderr);See API Documentation for complete reference.
-
Wrapper not intercepting Claude Code
- Ensure wrapper is installed globally
- Check PATH environment variable
- Verify installation with
which claude-code
-
Plugin not loading
- Check plugin manifest.json
- Verify plugin dependencies
- Check logs for errors
-
Database errors
- Ensure write permissions
- Check disk space
- Verify SQLite installation
Enable debug logging:
export CLAUDE_WRAPPER_LOG_LEVEL=debug
claude-code "test query"We welcome contributions! See CONTRIBUTING.md for guidelines.
MIT License - see LICENSE for details.
Built with:
For more information: