import type { IAgentRuntime } from "../types/runtime.js"; import { type RetryConfig } from "./retry.js"; export interface DrainStats { batchSize: number; remaining: number; durationMs: number; } export interface BatchQueueOptions { /** Task worker name and repeat task name (e.g. `EMBEDDING_DRAIN`). */ name: string; batchSize: number; drainIntervalMs: number; /** Cadence while idle; defaults to max(5 s, 5 × drainIntervalMs). See TaskDrainOptions.idleIntervalMs. */ idleDrainIntervalMs?: number; getPriority: (item: T) => QueuePriority; process: (item: T) => Promise; /** * Optional batched processor. When provided, a drain calls this ONCE with the * whole dequeued slice (so a provider that supports a batched request — e.g. * embeddings — sends one call instead of N). If it throws, every item falls * back to the per-item {@link process} path; failed item outcomes it returns * fall back the same way, so retry / `onExhausted` semantics are preserved. * Without a batch processor, items use the per-item path. */ processBatch?: (items: T[]) => Promise[]>; /** Re-evaluate live capability before each drain; absence uses the normal per-item path. */ canProcessBatch?: () => boolean; maxParallel?: number; maxRetriesAfterFailure?: number; retryPolicy?: RetryConfig; maxSize?: number; onPressure?: (queue: PriorityQueue, item: T) => boolean; onOverflowWarning?: (sizeAfter: number, maxSize: number) => void; onExhausted?: (item: T, error: Error) => void | Promise; /** Called after a non-empty batch finishes `processBatch` (includes per-item success/failure). */ onDrainBatchOutcomes?: (outcomes: BatchItemOutcome[]) => void; onDrainComplete?: (stats: DrainStats) => void; shouldRetry?: (item: T, error: Error, attempt: number) => boolean; /** * When true, skips registering the task worker and only registers the repeat task — caller must * register `name` with TaskService (e.g. `BATCHER_DRAIN`). Default false. */ skipRegisterWorker?: boolean; /** Merged into repeat task metadata (e.g. `{ affinityKey: "room:x" }`). */ taskMetadata?: Record; /** Optional repeat task description in the task store. */ taskDescription?: string; drainHighPriorityOnStop?: boolean; } /** * End-to-end queue for “enqueue work, drain on a schedule, process with backpressure.” * * **Why `isDraining`:** Repeat tasks can fire while a drain is still running; we skip re-entry so * two batches don’t process the same logical slice or overlap `process` side effects. * * **Why `dispose` flushes high priority optionally:** Matches embedding shutdown: best-effort * completion for urgent items before deleting the repeat task and clearing the queue. * * **Flush path:** By default the high-priority shutdown slice runs through a dedicated * {@link BatchProcessor} (serial, one attempt per item) so behavior stays aligned with bounded * concurrency. */ export declare class BatchQueue { private readonly priorityQueue; private readonly batchProcessor; private taskDrain; private runtime?; private isDraining; private disposed; private readonly batchSize; private readonly options; constructor(options: BatchQueueOptions); enqueue(item: T): boolean; /** * Run one drain cycle (typically from the repeat task worker). * Resolves to the number of items processed (0 when idle, disposed, or * already draining) so callers and the idle-backoff worker share one count. */ drain(): Promise; /** * Route failed `processBatch` items through the per-item processor, honoring * `shouldRetry` for the failed batched attempt. Outcomes keep batch order. */ private retryBatchFailures; /** Wire `TaskDrain` (worker + repeat task unless `skipRegisterWorker`). */ start(runtime: IAgentRuntime): Promise; updateDrainInterval(runtime: IAgentRuntime, ms: number): Promise; dispose(runtime: IAgentRuntime, opts?: { flushHighPriority?: boolean; }): Promise; get size(): number; stats(): PriorityQueueStats; clear(): void; } export type QueuePriority = "high" | "normal" | "low"; export type PriorityQueueStats = { high: number; normal: number; low: number; total: number; }; export interface PriorityQueueOptions { getPriority: (item: T) => QueuePriority; /** When set and length >= maxSize before enqueue, see {@link onPressure} / overflow behavior. */ maxSize?: number; /** * Called when maxSize is reached before adding `item`. Return true after making room (e.g. dequeue) * so the new item can be inserted; return false to reject `item` (not enqueued). */ onPressure?: (queue: PriorityQueue, item: T) => boolean; /** When maxSize exceeded and no onPressure: still enqueue but notify (queue grows past maxSize). */ onOverflowWarning?: (sizeAfter: number, maxSize: number) => void; } export declare class PriorityQueue { private invalidPriorityWarned; private readonly highItems; private readonly normalItems; private readonly lowItems; private readonly getPriority; private readonly maxSize?; private readonly onPressure?; private readonly onOverflowWarning?; constructor(options: PriorityQueueOptions); /** * Insert by priority. Returns false if rejected (onPressure returned false). */ enqueue(item: T): boolean; private insertByPriority; /** Remove up to `n` items from the front (highest priority first). */ dequeueBatch(n: number): T[]; /** Remove and return all items matching `filter`. */ drain(filter?: (item: T) => boolean): T[]; get size(): number; clear(): void; stats(): PriorityQueueStats; } export interface BatchItemOutcome { item: T; success: boolean; error?: Error; retryCount: number; } export interface BatchProcessorOptions { /** Max concurrent `process` calls across the batch. */ maxParallel: number; /** * After a failed attempt, re-try up to this many times (embedding-style). * Total attempts = maxRetriesAfterFailure + 1. Default 3 → 4 total tries. * * **Interaction with per-item `_batchMaxAttempts`:** If the item is an object with numeric * `_batchMaxAttempts`, that value is used as total attempts (unless `maxAttemptsCap` applies). */ maxRetriesAfterFailure?: number; retryPolicy?: RetryConfig; /** * Upper bound on attempts per item after resolving per-item `maxRetries` and global retry config. * Use for shutdown-style paths where items may carry large `maxRetries` but only one try is wanted. */ maxAttemptsCap?: number; process: (item: T) => Promise; onExhausted?: (item: T, error: Error) => void | Promise; shouldRetry?: (item: T, error: Error, attempt: number) => boolean; } export declare class BatchProcessor { private readonly defaultMaxAttempts; private readonly maxAttemptsCap?; private readonly policy; private readonly process; private readonly onExhausted?; private readonly shouldRetry; private readonly semaphore; constructor(options: BatchProcessorOptions); processBatch(items: T[]): Promise[]>; private processOne; }