ursamu-mud
v1.0.1
Published
Ursamu - Modular MUD Engine with sandboxed scripting and plugin system
Maintainers
Readme
Ursamu - Modular MUD Engine
Ursamu is a next-generation Multi-User Dungeon (MUD) engine built with TypeScript, featuring a modular plugin system, sandboxed virtual machine for user scripts, hot-reload capabilities, and multi-protocol support.
Table of Contents
- Features
- Architecture Overview
- Quick Start
- Core Systems
- Getting Started
- Development
- Configuration
- API Documentation
- Contributing
- License
Features
🏗️ Modular Architecture
- Plugin-based system with automatic discovery and lifecycle management
- Hot-reload capabilities for zero-downtime updates
- Sandboxed execution environment for user scripts
- Event-driven architecture with comprehensive monitoring
🌐 Multi-Protocol Support
- Telnet - Traditional MUD protocol with full ANSI support
- WebSocket - Modern web-based connectivity with binary message support
- HTTP/REST - RESTful API for external integrations
- TCP Raw - Direct socket connections for custom protocols
🔒 Security & Isolation
- VM-based script sandboxing with resource limits
- Memory and CPU usage monitoring
- Security validation preventing dangerous code patterns
- Automatic rollback on validation failures
⚡ Performance & Reliability
- Sub-50ms hot-reload target times
- Parallel compilation with dependency resolution
- State preservation across updates
- Comprehensive error handling and recovery
🛠️ Developer Experience
- Powerful CLI tool for development and debugging
- Real-time script compilation and validation
- Performance profiling and analysis
- Project scaffolding and management
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Multi-Protocol │ │ Plugin System │ │ Hot-Reload Core │
│ Server │◄──►│ Discovery │◄──►│ File Watcher │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Connection Pool │ │ Lifecycle Manager│ │ Compilation │
│ Management │ │ Events & Deps │ │ Queue │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Sandboxed │ │ Game World │ │ Validation │
│ Virtual Machine │◄──►│ State Mgmt │◄──►│ Engine │
└─────────────────┘ └──────────────────┘ └─────────────────┘Quick Start
Prerequisites
- Node.js 18.0.0 or higher
- TypeScript 5.0 or higher
- npm or yarn package manager
Installation
# Clone the repository
git clone https://github.com/your-org/ursamu.git
cd ursamu
# Install dependencies
npm install
# Build the project
npm run build
# Start the server
npm start
# Or use the Ursamu CLI
npx ursamu-mud startBasic Usage
import { MUDEngine } from 'ursamu-mud';
const engine = new MUDEngine({
protocols: ['telnet', 'websocket'],
hotReload: {
enabled: true,
watchPaths: ['./scripts', './plugins']
},
vm: {
memoryLimit: 64 * 1024 * 1024, // 64MB
timeoutMs: 5000
}
});
await engine.start();
console.log('Ursamu MUD engine started successfully!');Core Systems
Multi-Protocol Server
The multi-protocol server provides seamless connectivity across different network protocols:
// Configure multiple protocols
const protocolConfig = {
telnet: {
port: 4000,
encoding: 'utf8',
ansiSupport: true
},
websocket: {
port: 8080,
path: '/ws',
binaryMessages: true
},
http: {
port: 3000,
cors: true,
rateLimiting: true
}
};Key Features:
- Protocol-agnostic message handling
- Connection pooling and lifecycle management
- Built-in rate limiting and security
- Real-time connection monitoring
Plugin System
Discover and manage plugins automatically with full lifecycle control:
// Plugin structure
export class ExamplePlugin implements Plugin {
name = 'example-plugin';
version = '1.0.0';
dependencies = ['core-engine'];
async onLoad(): Promise<void> {
console.log('Plugin loaded');
}
async onUnload(): Promise<void> {
console.log('Plugin unloaded');
}
}Features:
- Automatic plugin discovery
- Dependency resolution and management
- Hot-loading and unloading
- Version compatibility checking
Sandboxed Virtual Machine
Execute user scripts safely in an isolated environment:
// VM configuration
const vmConfig = {
memoryLimit: 64 * 1024 * 1024, // 64MB
timeoutMs: 5000,
allowedModules: ['util', 'crypto'],
blockedPatterns: [/eval/, /Function/, /require/]
};
// Execute script safely
const result = await vm.executeScript(scriptCode, {
context: gameContext,
timeout: 1000
});Security Features:
- Memory usage monitoring
- CPU time limits
- Module access control
- Dangerous pattern detection
Hot-Reload System
Zero-downtime updates with state preservation:
// Hot-reload configuration
const hotReloadConfig = {
enabled: true,
watchPaths: ['./scripts', './plugins', './modules'],
debounceMs: 250,
validateBeforeReload: true,
allowRollback: true,
backupOnReload: true
};Pipeline Stages:
- File Watching - Detect changes with debouncing
- Compilation - Process TypeScript, JavaScript, and MUD scripts
- Validation - Security and performance checks
- Deployment - Atomic updates with state preservation
- Rollback - Automatic recovery on failures
Developer CLI
Comprehensive development tools for building and debugging:
# Script management
ursamu-mud script create my-script --template typescript
ursamu-mud script compile ./scripts/combat.ts
ursamu-mud script validate ./scripts/*.js
# Development server
ursamu-mud dev --hot-reload --debug
ursamu-mud debug --inspect-brk
# Performance analysis
ursamu-mud profile --script ./scripts/ai.js --duration 60s
ursamu-mud benchmark --load-test --connections 1000
# Project management
ursamu-mud init --template basic-mud
ursamu-mud plugin install combat-system
ursamu-mud deploy --environment productionGetting Started
1. Create a New Project
# Initialize new Ursamu MUD project
ursamu-mud init my-mud-game --template typescript
# Navigate to project
cd my-mud-game
# Install dependencies
npm install2. Configure the Engine
Edit config/default.json:
{
"server": {
"protocols": {
"telnet": { "port": 4000, "enabled": true },
"websocket": { "port": 8080, "enabled": true },
"http": { "port": 3000, "enabled": true }
}
},
"hotReload": {
"enabled": true,
"watchPaths": ["./scripts", "./plugins"],
"debounceMs": 250,
"maxReloadTime": 50
},
"vm": {
"memoryLimit": 67108864,
"timeoutMs": 5000,
"enableProfiling": true
},
"plugins": {
"autoDiscovery": true,
"searchPaths": ["./plugins", "./node_modules/@mud/*"]
}
}3. Create Your First Script
// scripts/welcome.ts
export function onPlayerConnect(player: Player, context: GameContext): void {
player.send(`Welcome to ${context.world.name}!`);
player.send('Type "help" for available commands.');
}
export function helpCommand(player: Player, args: string[]): CommandResult {
const commands = [
'look - Examine your surroundings',
'inventory - Check your items',
'quit - Leave the game'
];
return {
success: true,
message: 'Available commands:\n' + commands.join('\n')
};
}4. Start the Server
# Development mode with hot-reload
npm run dev
# Production mode
npm start
# With custom configuration
npm start -- --config ./config/production.jsonDevelopment
Building from Source
# Clone repository
git clone https://github.com/your-org/ursamu.git
cd ursamu
# Install dependencies
npm install
# Build TypeScript
npm run build
# Run tests
npm test
# Development with watch mode
npm run devRunning Tests
# Run all tests
npm test
# Run specific test suite
npm test -- --testPathPattern="hotreload"
# Run with coverage
npm run test:coverage
# Run integration tests
npm run test:integrationProject Structure
ursamu/
├── src/
│ ├── core/ # Core engine systems
│ ├── protocols/ # Multi-protocol server
│ ├── plugins/ # Plugin discovery & lifecycle
│ ├── vm/ # Sandboxed virtual machine
│ ├── scripting/ # Hot-reload system
│ ├── cli/ # Developer CLI tool (ursamu-cli)
│ └── index.ts # Main entry point
├── scripts/ # Game scripts
├── plugins/ # Available plugins
├── config/ # Configuration files
├── tests/ # Test suites
└── docs/ # DocumentationConfiguration
Environment Variables
# Server configuration
URSAMU_PORT=4000
URSAMU_HOST=0.0.0.0
# Hot-reload settings
HOT_RELOAD_ENABLED=true
HOT_RELOAD_DEBOUNCE=250
# VM security
VM_MEMORY_LIMIT=67108864
VM_TIMEOUT_MS=5000
# Development
NODE_ENV=development
DEBUG=ursamu:*Advanced Configuration
// Advanced engine configuration
const engineConfig: MUDEngineConfig = {
protocols: {
telnet: {
port: 4000,
encoding: 'utf8',
options: {
localEcho: false,
lineMode: true
}
},
websocket: {
port: 8080,
path: '/ws',
options: {
compression: true,
maxPayload: 1024 * 1024 // 1MB
}
}
},
hotReload: {
enabled: true,
watchPaths: ['./scripts', './plugins'],
ignorePaths: ['node_modules', '.git'],
debounceMs: 250,
maxReloadTime: 50,
validateBeforeReload: true,
allowRollback: true,
backupOnReload: true
},
vm: {
memoryLimit: 64 * 1024 * 1024,
timeoutMs: 5000,
enableProfiling: true,
allowedModules: ['util', 'crypto'],
securityOptions: {
checkDangerous: true,
maxComplexity: 50,
maxMemoryUsage: 0.8
}
},
plugins: {
autoDiscovery: true,
searchPaths: ['./plugins'],
lifecycle: {
loadTimeout: 10000,
unloadTimeout: 5000
}
}
};API Documentation
Core Engine API
// Engine lifecycle
await engine.start();
await engine.stop();
await engine.restart();
// Plugin management
await engine.loadPlugin('combat-system');
await engine.unloadPlugin('combat-system');
const plugins = engine.getLoadedPlugins();
// Script execution
const result = await engine.executeScript(script, context);
// Hot-reload control
await engine.hotReload.start();
await engine.hotReload.reload(['script.js']);
const status = engine.hotReload.getStatus();Protocol Management
// Protocol control
await engine.protocols.start('telnet');
await engine.protocols.stop('websocket');
// Connection management
const connections = engine.protocols.getActiveConnections();
await engine.protocols.broadcast('Hello everyone!');
// Custom protocol handlers
engine.protocols.registerHandler('telnet', customTelnetHandler);Virtual Machine API
// Script execution
const result = await vm.executeScript(code, {
context: gameContext,
timeout: 5000,
memoryLimit: 1024 * 1024
});
// Resource monitoring
const stats = vm.getResourceUsage();
const profile = vm.getPerformanceProfile();
// Security validation
const validation = await vm.validateScript(code);Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Workflow
- Fork the repository
- Create a feature branch:
git checkout -b feature/new-feature - Make your changes and add tests
- Run tests:
npm test - Commit with conventional commits:
git commit -m "feat: add new feature" - Push to your fork:
git push origin feature/new-feature - Create a Pull Request
Code Standards
- TypeScript with strict mode enabled
- ESLint configuration provided
- 100% test coverage for new features
- Comprehensive documentation for APIs
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- 📖 Documentation: Full API docs
- 🐛 Bug Reports: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 🔧 Development: Contributing Guide
Ursamu - Built with ❤️ for the MUD development community
