/** * Society Protocol — Proactive Swarm Controller * * Advanced swarm coordination layer inspired by: * - DRAMA (arXiv:2508.04332): Monitor agent + event-driven reallocation * - SwarmSys (arXiv:2510.10047): Pheromone-inspired explorer/worker/validator roles * - TDAG (arXiv:2402.10178): Dynamic task decomposition with skill libraries * - SECP (arXiv:2602.02170): Self-evolving coordination with formal invariants * - Google ADK: Bidirectional streaming + session management * * Provides: * - Time-range scheduling (run swarm within specific time windows) * - Real-time event-driven coordination (not just timer-based cadence) * - Worker health monitoring with heartbeat + auto-reallocation * - Dynamic role assignment (explorer/worker/validator from SwarmSys) * - Pheromone-inspired affinity scoring for task-agent matching * - Mission lifecycle with start/pause/resume/stop + time bounds */ import { EventEmitter } from 'events'; import type { Storage } from '../storage.js'; import type { RoomManager } from '../rooms.js'; import type { SwarmWorkerProfile } from './types.js'; import type { P2PSwarmRegistry } from './swarm-registry.js'; export type SwarmRole = 'explorer' | 'worker' | 'validator'; export interface TimeWindow { /** Start time (ISO 8601 or epoch ms) */ startAt: number; /** End time (ISO 8601 or epoch ms) */ endAt: number; /** Timezone (IANA, e.g. 'America/Sao_Paulo') */ timezone?: string; /** Recurrence pattern */ recurrence?: RecurrencePattern; } export interface RecurrencePattern { /** Recurrence type */ type: 'daily' | 'weekly' | 'interval'; /** For 'interval': repeat every N ms */ intervalMs?: number; /** For 'weekly': day numbers (0=Sun, 1=Mon, ..., 6=Sat) */ daysOfWeek?: number[]; /** For 'daily'/'weekly': start time as "HH:MM" */ startTime?: string; /** For 'daily'/'weekly': end time as "HH:MM" */ endTime?: string; /** Maximum number of occurrences (undefined = infinite) */ maxOccurrences?: number; } export interface SwarmAgentProfile extends SwarmWorkerProfile { /** Current role in the swarm */ role: SwarmRole; /** Affinity scores for different task types (pheromone-inspired) */ affinityScores: Map; /** Epsilon for exploration-exploitation balance */ explorationEpsilon: number; /** Consecutive successful tasks */ successStreak: number; /** Availability window */ availabilityWindow?: TimeWindow; } export interface SwarmEvent { id: string; type: SwarmEventType; missionId: string; roomId: string; timestamp: number; data: Record; } export type SwarmEventType = 'worker:joined' | 'worker:left' | 'worker:failed' | 'worker:overloaded' | 'task:completed' | 'task:failed' | 'task:timeout' | 'mission:window:opened' | 'mission:window:closed' | 'reallocation:triggered' | 'role:changed' | 'consensus:reached'; export interface SwarmControllerConfig { /** Heartbeat interval for liveness checks (ms) */ heartbeatIntervalMs: number; /** Max time without heartbeat before marking unhealthy (ms) */ heartbeatTimeoutMs: number; /** Reallocation cooldown after a reallocation event (ms) */ reallocationCooldownMs: number; /** Min workers for explorer role */ minExplorers: number; /** Min workers for validator role */ minValidators: number; /** Affinity decay factor per tick (0-1) */ affinityDecay: number; /** Affinity boost on successful task completion */ affinityBoost: number; /** Base epsilon for exploration */ baseEpsilon: number; /** Enable time-window scheduling */ enableTimeWindows: boolean; /** Fixed-time consensus bound (ms) — max time to reach consensus */ consensusBoundMs: number; } export declare const DEFAULT_SWARM_CONTROLLER_CONFIG: SwarmControllerConfig; export declare class SwarmController extends EventEmitter { private storage; private rooms; private registry; private config; private agents; private eventLog; private missionWindows; private windowTimers; private monitorTimer?; private lastReallocationAt; constructor(storage: Storage, rooms: RoomManager, registry: P2PSwarmRegistry, config?: Partial); /** * Start the swarm controller's monitor loop. * Acts as the DRAMA Monitor agent — detects state changes and triggers reallocation. */ start(): void; /** * Stop the swarm controller. */ stop(): void; /** * Register a time window for a mission. * The swarm will only be active during this window. */ setMissionTimeWindow(missionId: string, window: TimeWindow): void; /** * Remove a mission's time window. */ removeMissionTimeWindow(missionId: string): void; /** * Check if a mission is currently within its time window. */ isMissionInWindow(missionId: string): boolean; /** * Register an agent with the swarm controller. */ registerAgent(worker: SwarmWorkerProfile, role?: SwarmRole): SwarmAgentProfile; /** * Update agent affinity after task completion (pheromone-inspired). * SwarmSys: Validated contributions reinforce agent-task compatibility. */ recordTaskOutcome(agentDid: string, taskType: string, success: boolean): void; /** * Select the best agent for a task using affinity-based matching. * Combines SwarmSys pheromone matching with epsilon-greedy exploration. */ selectAgent(taskType: string, requirements?: { capabilities?: string[]; minReputation?: number; }): SwarmAgentProfile | null; /** * Dynamically reassign roles based on current swarm state. * Ensures minimum explorers and validators are maintained. */ rebalanceRoles(): { changes: Array<{ did: string; from: SwarmRole; to: SwarmRole; }>; }; /** * Get the current swarm status with roles and affinity info. */ getSwarmStatus(): { agents: Array<{ did: string; role: SwarmRole; health: string; load: number; affinities: Record; epsilon: number; successStreak: number; }>; roleDistribution: Record; activeMissions: number; activeWindows: Array<{ missionId: string; inWindow: boolean; window: TimeWindow; }>; recentEvents: SwarmEvent[]; }; /** * Get recent events (useful for real-time UIs). */ getEvents(since?: number, limit?: number): SwarmEvent[]; private monitorTick; private scheduleWindowEvents; private isInRecurringWindow; private computeNextWindow; private inferRole; private emitEvent; destroy(): void; } //# sourceMappingURL=swarm-controller.d.ts.map