export class QvacScheduler { constructor({ concurrency = 1 } = {}) { this.concurrency = Math.max(1, concurrency); this.running = 0; this.queue = []; this.completed = 0; this.failed = 0; this.totalDurationMs = 0; this.byLane = {}; } 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; const started = Date.now(); Promise.resolve().then(() => job.task(job.signal)).then((value) => { this.completed += 1; job.resolve(value); }, (error) => { this.failed += 1; job.reject(error); }).finally(() => { this.totalDurationMs += Date.now() - started; this.byLane[job.lane] = (this.byLane[job.lane] || 0) + 1; 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) }; } metrics() { return { completed: this.completed, failed: this.failed, total_duration_ms: this.totalDurationMs, by_lane: { ...this.byLane } }; } }