π€ AI-Powered Multi-Channel Gateway with Efficient Algorithm Architecture
A modern, extensible AI gateway platform that combines the efficient algorithm architecture from Claude Code with the comprehensive functionality of OpenClaw.
openLittleTwo is designed to be a high-performance, feature-rich AI assistant framework that:
β
Efficient Task Management System - State machine-based task lifecycle with priority queues
β
Advanced Tool Interface Pattern - Factory pattern with permission system and lazy loading
β
Intelligent Query Engine - Context compaction, token budget optimization, streaming responses
β
Reactive State Management - Memoization, LRU cache, real-time updates
β
Modular Command System - Dynamic loading, feature flags, dead code elimination
β
Multi-Channel Integration - IRC, Slack, Telegram, Discord, Matrix, Line, WhatsApp, WebChat
β
Plugin System - Dynamic plugin loading, lifecycle management, hot-reload support
β
Gateway Server - WebSocket communication, authentication, event-driven architecture
β
CLI Toolchain - Comprehensive command-line interface with rich subcommands
β
Agent System - Sandbox execution, multi-agent coordination
β
Security Features - Permission model, audit logging, secret management
openLittleTwo/
βββ src/
β βββ core/ # Core Algorithm Architecture (from Claude Code)
β β βββ Task.ts # Task state machine and lifecycle
β β βββ Tool.ts # Tool interface and factory pattern
β β βββ QueryEngine.ts # Intelligent query processing engine
β β βββ StateManager.ts # Reactive state management
β β
β βββ channels/ # Multi-Channel Support (from OpenClaw)
β β βββ BaseChannel.ts # Abstract channel base class
β β
β βββ plugins/ # Plugin System (from OpenClaw)
β β βββ PluginSystem.ts # Plugin loader and registry
β β
β βββ gateway/ # Gateway Server (from OpenClaw)
β β βββ GatewayServer.ts # WebSocket server implementation
β β
β βββ cli/ # CLI Interface
β β βββ index.ts # Entry point
β β βββ CommandRouter.ts # Command routing system
β β
β βββ tools/ # Built-in Tools
β β βββ builtinTools.ts # Core tool implementations
β β
β βββ index.ts # Main exports
β
βββ package.json
βββ tsconfig.json
βββ README.md
# Clone or navigate to the project directory
cd openLittleTwo
# Install dependencies
npm install
# Build the project
npm run build# Start on default port 8080
npm run cli -- start
# Custom port and host
npm run cli -- start --port 3000 --host localhostnpm run cli -- chat# List all channels
npm run cli -- channel list
# Check channel status
npm run cli -- channel status# List installed plugins
npm run cli -- plugin list
# Enable a plugin
npm run cli -- plugin enable my-plugin
# Disable a plugin
npm run cli -- plugin disable my-pluginnpm run cli -- status# View all config
npm run cli -- config list
# Get specific config value
npm run cli -- config get debug
# Set config value
npm run cli -- config set debug true# List active tasks
npm run cli -- task
# View task details
npm run cli -- task <task-id>
# Show all tasks including completed
npm run cli -- task --allImplements a sophisticated task state machine:
type TaskType =
| 'local_bash' // Shell commands
| 'local_agent' // AI agent tasks
| 'remote_agent' // Remote agent tasks
| 'channel_message' // Channel message handling
| 'plugin_task' // Plugin-specific tasks
| 'gateway_request' // WebSocket requests
type TaskStatus =
| 'pending' β 'running' β 'completed' | 'failed' | 'killed'
| β 'paused'
| β 'retrying'Key Features:
- Priority queue system (low/normal/high/critical)
- Automatic retry mechanism with configurable limits
- Concurrent task limiting
- Graceful cancellation via AbortController
- Task output persistence to disk
Clean factory-based tool creation:
const MyTool = buildTool({
name: 'my_tool',
description: async () => 'Tool description',
inputSchema: z.object({ /* Zod schema */ }),
async call(args, context, canUseTool) {
// Implementation
return { data: result }
},
// Optional safety features
isReadOnly: () => false,
isDestructive: () => true,
isConcurrencySafe: () => false,
})Built-in Tools:
bash- Execute shell commandsread/write- File operationsgrep- Pattern searchglob- File discovery
Intelligent context management:
- Token Budget Optimization: Tracks usage per turn
- Context Compaction: Automatically compresses long conversations
- Tool Orchestration: Parallel tool execution with dependency resolution
- Streaming Responses: Real-time output delivery
- Error Recovery: Graceful degradation on failures
Multi-platform messaging support:
| Channel Type | Status | Protocol |
|---|---|---|
| IRC | β Planned | IRC protocol |
| Slack | β Planned | Slack API |
| Telegram | β Planned | Bot API |
| Discord | β Planned | Discord.js |
| Matrix | β Planned | Matrix SDK |
| Line | β Planned | Line Messaging API |
| β Planned | Business API | |
| WebChat | β Planned | WebSocket |
| Webhook | β Planned | HTTP endpoints |
Extensible plugin architecture:
// plugin.json
{
"name": "my-plugin",
"version": "1.0.0",
"main": "index.ts"
}
// index.ts
import { definePlugin } from 'openlittletwo'
export default definePlugin((context) => ({
tools: [/* custom tools */],
channels: [/* channel integrations */],
hooks: {
onMessage: async (message) => { /* ... */ },
}
}))Plugin Capabilities:
- Provide custom tools
- Add new channel integrations
- Register CLI commands
- Hook into message lifecycle
- Manage own configuration
Real-time communication hub:
const gateway = new GatewayServer({
port: 8080,
host: '0.0.0.0',
authSecret: process.env.AUTH_SECRET,
})
await gateway.start()
// Handle events
gateway.on('client_connected', (event) => {
console.log('New client:', event.clientId)
})
// Send messages
gateway.sendToClient(clientId, {
type: 'response',
payload: { text: 'Hello!' }
})
// Broadcast to all authenticated clients
gateway.broadcast({
type: 'event',
payload: { type: 'notification', data: {} }
})Features:
- WebSocket connection management
- Client authentication
- Heartbeat monitoring
- Message broadcasting
- Event-driven architecture
- Connection limits
Create a file in src/tools/:
// src/tools/my-tool.ts
import { z } from 'zod'
import { buildTool } from '../core/Tool'
export const MyTool = buildTool({
name: 'my_tool',
inputSchema: z.object({ query: z.string() }),
async call(args) {
return { data: `Result for: ${args.query}` }
},
isReadOnly: () => true,
})Register in src/tools/builtinTools.ts:
export const getBuiltinTools = (): Tools => [
// ... existing tools
MyTool,
]Extend BaseChannel:
// src/channels/my-channel.ts
import { BaseChannel, ChannelConfig } from './BaseChannel'
export class MyChannel extends BaseChannel {
readonly type = 'custom' as const
readonly name = 'My Channel'
async connect() {
// Initialize connection
this.setStatus('connected')
}
async disconnect() {
// Cleanup
this.setStatus('disconnected')
}
async sendMessage(userId, content) {
// Send message
}
async handleMessage(message) {
// Process incoming message
}
}See plugins/ directory structure:
my-plugin/
βββ plugin.json # Manifest
βββ index.ts # Entry point
βββ tools/ # Custom tools
βββ README.md # Documentation
Inherited from Claude Code's efficient design:
- Memoization: Expensive computations cached automatically
- Lazy Loading: Modules loaded on-demand to reduce startup time
- Dead Code Elimination: Feature flags remove unused code paths
- LRU Caching: Intelligent cache eviction prevents memory bloat
- Parallel Execution: Independent tasks run concurrently
- Streaming I/O: Large results streamed to reduce memory pressure
- Context Compression: Long conversations summarized efficiently
Permission system inspired by Claude Code:
- Tool-level permissions: Each tool declares safety properties
- Input validation: Zod schemas enforce strict types
- Sandboxing: Agent execution isolated from host
- Audit logging: All actions recorded for compliance
- Rate limiting: Prevent abuse and resource exhaustion
- Authentication: Secure client verification
- Messaging: Slack, Telegram, Discord, IRC, Matrix, Line, WhatsApp
- Voice: TTS/STT integration planned
- Media: Image/audio/video processing pipeline
- Web: Browser automation, web scraping
- Code: Git integration, IDE extensions
- Cloud: AWS, GCP, Azure adapters
Pluggable AI backend:
- OpenAI API
- Anthropic Claude
- Local models (Ollama, llama.cpp)
- Custom providers via plugin interface
Detailed API documentation available in source code TypeScript definitions.
Key exports:
Task- Task management types and utilitiesTool/buildTool- Tool interface and factoryQueryEngine- Query processing engineStateManager- Global state managementBaseChannel/ChannelRegistry- Channel abstractionGatewayServer- WebSocket gatewayPluginLoader- Plugin systemCLICommandRouter- CLI framework
Contributions welcome! Please read our guidelines:
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing) - Open Pull Request
MIT License - see LICENSE file for details.
- Claude Code - For the elegant algorithm architecture and design patterns
- OpenClaw - For the comprehensive multi-channel gateway functionality
- The open-source community for inspiration and tools
Built with β€οΈ using algorithms from Claude Code + functionality from OpenClaw