wond-v3
v3.0.1
Published
Wonderland v3 - Event-driven Agent Framework with TypeScript
Downloads
15
Maintainers
Readme
Wonderland v3 (wond-v3)
Modern event-driven Agent Framework for Node.js with TypeScript
Overview
Wonderland v3 is a comprehensive agent framework built around event-driven architecture and controller-based design. It provides a modular system for building intelligent agents with built-in monitoring, task management, and API capabilities.
Key Features
- 🎯 Event-Driven Architecture: Type-safe event system with automatic TTL management
- 🔧 Controller-Based Design: Modular controllers (Pumps, Reactors, Iterators, Consumers)
- 📊 Built-in Monitoring: Real-time status tracking and influence path analysis
- ⚡ Task Management: BullMQ-based distributed task processing with Redis fallback
- 🌐 API Mode: Built-in RESTful API server for external monitoring
- 🔍 Influence Path Analysis: Comprehensive pump → consumer transmission path analysis
- 🏭 Factory Pattern: Type-safe event and task definitions with Zod validation
Installation
npm install wond-v3
# or
pnpm add wond-v3Quick Start
Basic Agent Setup
import { Agent, ReactorController, defineEvent } from 'wond-v3';
import { z } from 'zod';
// Define events with type safety
const UserRegistered = defineEvent({
type: 'USER_REGISTERED',
name: 'User Registered',
schema: z.object({
userId: z.string(),
email: z.string().email()
})
});
// Create agent with API mode
const agent = new Agent({
name: 'MyAgent',
apiMode: {
port: 3001,
host: 'localhost',
enableCors: true
}
});
// Create controller
const userProcessor = new ReactorController({
name: 'UserProcessor',
inputEventTypes: [UserRegistered],
processEvents: async (events, emitter) => {
for (const event of events) {
console.log('Processing user:', event.payload.userId);
// Process user registration logic here
}
}
});
// Add controller and start
agent.addController(userProcessor);
await agent.start();Pump Controllers (Event Sources)
import { TimerPump, HookPump, ManualPump } from 'wond-v3';
// Timer-based events
const timerPump = new TimerPump()
.interval(5000) // Every 5 seconds
.emit(HealthCheck, { timestamp: Date.now() });
// Cron-based events
const cronPump = new TimerPump()
.cron('0 */15 * * * *') // Every 15 minutes
.emit(PeriodicReport, { reportType: 'status' });
// Hook-based events
const hookPump = new HookPump({
name: 'FileWatcher',
check: async (emitter) => {
const files = await checkForNewFiles();
if (files.length > 0) {
emitter.event(FilesDetected).emit({ files });
}
}
});
// Manual control
const manualPump = new ManualPump({ name: 'ManualTrigger' });
// Later: manualPump.emitter.event(CustomEvent).emit({ data });Architecture
Controller Types
Pump Controllers: External signal sources → internal events
- TimerPump: Time-based triggers (interval/cron)
- HookPump: Custom check function triggers
- ManualPump: Direct event emission control
Reactor Controllers: Event processing → new events
- Immediate event transformation
- Real-time response handling
Iterator Controllers: Batch event processing
- Time-windowed event aggregation
- Bulk data processing
Consumer Controllers: Terminal event processing
- No output events (automatic detection)
- Or manually marked with
isConsumer: true
Event Flow
External Sources → Pumps → Events → Reactors/Iterators → Events → ConsumersInfluence Path Analysis
The framework provides comprehensive analysis of pump → consumer influence paths:
// Get complete influence analysis
const analysis = agent.monitor.getInfluencePaths();
console.log(`
Theoretical paths: ${analysis.statistics.theoreticalPathCount}
Actual paths: ${analysis.statistics.actualPathCount}
Missing paths: ${analysis.statistics.missingPathCount}
Connectivity: ${(analysis.statistics.connectivityRate * 100).toFixed(1)}%
`);
// Analyze specific pump's influence
const pumpPaths = agent.monitor.getPathsByPump('my-pump-id');
console.log(`Pump influences ${pumpPaths.length} consumers`);Path Analysis Concepts
- Controller-Event Network: Controllers connected by event input/output types
- Theoretical Paths: n pumps × m consumers (all possible combinations)
- Actual Paths: Searchable paths found via event flow analysis
- Missing Paths: Pump-consumer pairs with no influence channel (normal)
- Cycle Detection: Identifies circular dependencies in event flows
API Endpoints
When apiMode is enabled, the agent exposes RESTful endpoints:
Overview
GET /api/overview- Complete agent status
Controllers
GET /api/controllers- All controller detailsGET /api/controllers/:id- Specific controller info
Influence Paths
GET /api/influence-paths- Complete influence path analysisGET /api/influence-paths/pump/:id- Paths from specific pumpGET /api/influence-paths/consumer/:id- Paths to specific consumerGET /api/influence-paths/cycles- Cycle detection and statistics
Events & Tasks
GET /api/events/overview- Event pool statusGET /api/tasks- Task queue status
Type Safety
The framework enforces type safety through factory functions:
// Define events with schemas
const OrderCreated = defineEvent({
type: 'ORDER_CREATED',
name: 'Order Created',
schema: z.object({
orderId: z.string(),
customerId: z.string(),
amount: z.number().positive()
})
});
// Define tasks with schemas
const ProcessPayment = defineTask({
type: 'PROCESS_PAYMENT',
name: 'Process Payment',
schema: z.object({
paymentId: z.string(),
amount: z.number(),
currency: z.string().length(3)
})
});
// Usage with full type inference
emitter.event(OrderCreated).emit({
orderId: 'ord-123', // ✅ Typed
customerId: 'cust-456', // ✅ Typed
amount: 29.99 // ✅ Typed
});Advanced Features
Task Processing with Callbacks
emitter.task(SendEmail).create(
{
to: '[email protected]',
subject: 'Welcome!',
body: 'Welcome message'
},
async (payload) => {
// Actual email implementation
const result = await emailService.send(payload);
return { messageId: result.id, sent: true };
}
);Custom Pump Implementation
class WebhookPump extends BasePump {
async initialize() {
// Setup webhook listener
this.server.post('/webhook', (req, res) => {
this.emitter.event(WebhookReceived).emit(req.body);
res.status(200).send('OK');
});
}
}Requirements
- Node.js >= 18
- TypeScript >= 5.0
- Redis (optional, uses mock for development)
License
MIT
