/** * Background Task Runner * * Manages background task execution for non-blocking agent invocations * and pipeline steps. Supports concurrency limits, cancellation, * progress tracking, and event-based notifications. */ import { EventEmitter } from 'events'; import type { Logger } from '../observability/logger.js'; import type { BackgroundTask, BackgroundTaskConfig, BackgroundTaskType, SubmitTaskOptions, SerializedBackgroundTask } from './types.js'; /** * Manages background task execution with concurrency control. * * Features: * - Queue-based execution with configurable concurrency * - Task cancellation via AbortController * - Progress tracking and notifications * - Event emission for task lifecycle * - Automatic cleanup of old tasks * * @example * ```typescript * const runner = new BackgroundTaskRunner({ maxConcurrent: 3 }, logger); * * // Submit a background task * const taskId = await runner.run( * 'agent_invocation', * 'Review authentication code', * async () => { * return await orchestrator.executeWithFailover('reviewer', messages, options); * }, * { role: 'reviewer', provider: 'openai' } * ); * * // Check status later * const task = runner.getTask(taskId); * if (task?.status === 'completed') { * console.log('Result:', task.result); * } * * // Or wait for completion * const completed = await runner.waitFor(taskId, 60000); * ``` */ export declare class BackgroundTaskRunner extends EventEmitter { private readonly tasks; private readonly queue; private runningCount; private readonly config; private readonly logger; private isEnabled; private isShuttingDown; constructor(config: Partial, logger: Logger); /** * Check if background tasks are enabled. * Respects HARI_SELDON_DISABLE_BACKGROUND_TASKS env var. */ isBackgroundEnabled(): boolean; /** * Enable or disable background task execution. */ setEnabled(enabled: boolean): void; /** * Submit a task to run in the background. * Returns immediately with task ID. * * @param task - Task definition (without id, status, createdAt) * @returns Task ID for tracking */ submit(task: Omit): string; /** * Execute a function as a background task. * * @param type - Task type * @param description - Task description * @param fn - Async function to execute * @param options - Additional options * @returns Task ID for tracking */ run(type: BackgroundTaskType, description: string, fn: () => Promise, options?: SubmitTaskOptions): Promise; /** * Get task by ID. */ getTask(taskId: string): BackgroundTask | undefined; /** * Get all tasks. */ getAllTasks(): BackgroundTask[]; /** * Get running tasks. */ getRunningTasks(): BackgroundTask[]; /** * Get pending tasks in queue. */ getPendingTasks(): BackgroundTask[]; /** * Get completed tasks. */ getCompletedTasks(): BackgroundTask[]; /** * Cancel a running or pending task. * * @param taskId - ID of task to cancel * @returns true if task was cancelled, false if not found or already complete */ cancel(taskId: string): boolean; /** * Wait for a task to complete. * * @param taskId - ID of task to wait for * @param timeout - Maximum time to wait in ms (default: 60000) * @returns The completed task * @throws Error if task not found or timeout exceeded */ waitFor(taskId: string, timeout?: number): Promise; /** * Update task progress. * * @param taskId - ID of task to update * @param progress - Progress percentage (0-100) * @param message - Optional progress message */ updateProgress(taskId: string, progress: number, message?: string): void; /** * Clean up completed/failed tasks older than specified age. * * @param maxAgeMs - Maximum age in ms (default: 1 hour) * @returns Number of tasks cleaned up */ cleanup(maxAgeMs?: number): number; /** * Shutdown the runner - cancel pending tasks and wait for running tasks. * * @param timeout - Maximum time to wait for running tasks in ms (default: 30000) */ shutdown(timeout?: number): Promise; /** * Get statistics about the task runner. */ getStats(): { pending: number; running: number; completed: number; failed: number; cancelled: number; total: number; queueLength: number; maxConcurrent: number; }; /** * Serialize tasks for persistence. * Only serializes metadata, not results or errors. */ serializeTasks(): SerializedBackgroundTask[]; /** * Process the task queue, starting tasks up to maxConcurrent. */ private processQueue; /** * Execute a single task. */ private executeTask; /** * Mark a task as completed. */ private markCompleted; /** * Mark a task as failed. */ private markFailed; /** * Send a notification if enabled. */ private notify; } //# sourceMappingURL=task-runner.d.ts.map