/** * Background Task Manager * * Manages background task delegation for the multi-agent swarm system. * Queues tasks, enforces concurrency limits per agent, tracks lifecycle, * stores results, and emits events on completion/failure. * * Features: * - Per-agent concurrency limits (configurable) * - Global concurrency cap * - Task lifecycle: pending → running → completed → failed * - Result storage with recent-completed retention (last 50) * - EventEmitter for task-started / task-completed / task-failed * - Stale task detection with configurable timeout * - Queue size limits to prevent unbounded growth * * @module background-task-manager * @version 1.0 */ import { EventEmitter } from 'events'; /** * Task status lifecycle */ export type BackgroundTaskStatus = 'pending' | 'running' | 'completed' | 'failed'; /** * A background task tracked by the manager */ export interface BackgroundTask { /** Unique task ID with bg_ prefix (e.g. bg_a1b2c3d4) */ id: string; /** Current lifecycle status */ status: BackgroundTaskStatus; /** Human-readable task description */ description: string; /** Full prompt to send to the executing agent */ prompt: string; /** Agent ID that executes this task */ agentId: string; /** Agent ID that requested this task */ requestedBy: string; /** Source channel ID */ channelId: string; /** Platform source */ source: 'discord' | 'slack'; /** Timestamp when task was queued */ queuedAt: number; /** Timestamp when task started executing */ startedAt?: number; /** Timestamp when task completed or failed */ completedAt?: number; /** Agent response on success */ result?: string; /** Error message on failure */ error?: string; /** Execution duration in milliseconds */ duration?: number; /** Number of retry attempts due to busy process */ retryCount?: number; } /** * Options for submitting a new background task */ export interface BackgroundTaskSubmitOptions { /** Human-readable task description */ description: string; /** Full prompt to send to the executing agent */ prompt: string; /** Agent ID that executes this task */ agentId: string; /** Agent ID that requested this task */ requestedBy: string; /** Source channel ID */ channelId: string; /** Platform source */ source: 'discord' | 'slack'; } /** * Configuration options for BackgroundTaskManager */ export interface BackgroundTaskManagerOptions { /** Maximum concurrent tasks per agent (default: 2) */ maxConcurrentPerAgent?: number; /** Maximum total concurrent tasks across all agents (default: 5) */ maxTotalConcurrent?: number; /** Timeout in ms after which a running task is considered stale (default: 300000 = 5min) */ staleTimeoutMs?: number; /** Maximum number of pending tasks in the queue (default: 20) */ maxQueueSize?: number; } /** * Aggregate task statistics */ export interface BackgroundTaskStats { /** Number of tasks waiting to execute */ pending: number; /** Number of tasks currently running */ running: number; /** Number of successfully completed tasks */ completed: number; /** Number of failed tasks */ failed: number; /** Total tasks submitted since manager creation */ totalSubmitted: number; } /** * Event payload emitted on task lifecycle transitions */ export interface BackgroundTaskEvent { /** The task that triggered the event */ task: BackgroundTask; } /** * Background Task Manager * * Manages background task execution for the multi-agent swarm. * Tasks are queued, executed respecting concurrency limits, and * results are stored for later retrieval. * * @example * ```typescript * const manager = new BackgroundTaskManager( * async (agentId, prompt) => { * const response = await agentProcess.sendMessage(prompt); * return response.text; * }, * { maxConcurrentPerAgent: 2, maxTotalConcurrent: 5 } * ); * * const task = manager.submit({ * description: 'Analyze auth module', * prompt: 'Review the auth module for security issues', * agentId: 'reviewer', * requestedBy: 'conductor', * channelId: '123456789', * source: 'discord', * }); * * manager.on('task-completed', ({ task }) => { * console.log(`Task ${task.id} done: ${task.result}`); * }); * ``` */ export declare class BackgroundTaskManager extends EventEmitter { private tasks; private pendingQueue; private runningSet; private completedList; private totalSubmitted; private options; private executeTask; constructor(executeTask: (agentId: string, prompt: string) => Promise, options?: BackgroundTaskManagerOptions); /** * Submit a new background task * * Creates a task with status='pending' and schedules queue processing. * * @param opts - Task submission options * @returns The created BackgroundTask with status='pending' * @throws Error if the queue is full * * @example * ```typescript * const task = manager.submit({ * description: 'Fix auth bug', * prompt: 'Find and fix the JWT validation bug in auth.ts', * agentId: 'developer', * requestedBy: 'conductor', * channelId: '999888777', * source: 'discord', * }); * console.log(task.id); // "bg_a1b2c3d4" * ``` */ submit(opts: BackgroundTaskSubmitOptions): BackgroundTask; /** * Get a task by ID * * @param taskId - Task ID to look up * @returns The task or undefined if not found */ getTask(taskId: string): BackgroundTask | undefined; /** * Get the result string of a completed task * * @param taskId - Task ID to look up * @returns The result string or undefined if not found/not completed */ getResult(taskId: string): string | undefined; /** * Cancel a pending or running task * * Pending tasks are removed from the queue. * Running tasks are marked as failed with a cancellation error. * * @param taskId - Task ID to cancel * @returns true if the task was cancelled, false if not found or already terminal */ cancelTask(taskId: string): boolean; /** * Get all pending tasks (ordered by queue position) * * @returns Array of pending BackgroundTask objects */ getQueuedTasks(): BackgroundTask[]; /** * Get all currently running tasks * * @returns Array of running BackgroundTask objects */ getRunningTasks(): BackgroundTask[]; /** * Get recently completed tasks (last 50) * * Includes both completed and failed tasks, ordered newest first. * * @returns Array of completed/failed BackgroundTask objects */ getCompletedTasks(): BackgroundTask[]; /** * Get aggregate task statistics * * @returns Task counts by status and total submitted */ getStats(): BackgroundTaskStats; /** * Clean up stale running tasks * * Marks running tasks that have exceeded the stale timeout as failed. * Call this periodically (e.g., every 60 seconds). * * @returns Number of stale tasks cleaned up */ cleanupStale(): number; private _processQueue; private _startTask; /** * Mark a task as completed with result * * @param task - The task to complete * @param result - Agent response string */ private _completeTask; private _failTask; private _addToCompleted; private _getRunningCountForAgent; destroy(): void; } //# sourceMappingURL=background-task-manager.d.ts.map