export class QvacScheduler { constructor({ concurrency = 1 } = {}) { this.concurrency = Math.max(1, concurrency); this.running = 0; this.queue = []; } run(task, { lane = 'background', signal } = {}) { return new Promise((resolve, reject) => { this.queue.push({ task, lane, signal, resolve, reject, enqueuedAt: Date.now() }); this.queue.sort((a, b) => this.priority(b.lane) - this.priority(a.lane) || a.enqueuedAt - b.enqueuedAt); this.pump(); }); } priority(lane) { return { voice: 3, 'computer-use': 2, background: 1, maintenance: 0 }[lane] ?? 0; } pump() { while (this.running < this.concurrency && this.queue.length) { const job = this.queue.shift(); if (job.signal?.aborted) { job.reject(new Error('QVAC job cancelled before start')); continue; } this.running += 1; Promise.resolve().then(() => job.task(job.signal)).then(job.resolve, job.reject).finally(() => { this.running -= 1; this.pump(); }); } } cancelQueued(predicate = () => true) { const kept = []; for (const job of this.queue) { if (predicate(job)) job.reject(new Error('QVAC job cancelled')); else kept.push(job); } this.queue = kept; } status() { return { running: this.running, queued: this.queue.map((j) => j.lane) }; } }