/**
 * src/subagents/events.ts
 *
 * Live progress event bus for subagents. Each running subagent emits
 * structured events (start, thinking, tool_call, tool_done, log, finished)
 * that the dashboard subscribes to via SSE. This is the "visually see
 * what subagents are doing" feature.
 *
 * Events are kept in a ring buffer per subagent (last 200 events), so a
 * client connecting mid-flight sees recent history. They're also
 * persisted to subagent_events table for post-mortem inspection.
 */
import { EventEmitter } from 'node:events';
import { randomUUID } from 'node:crypto';
import { supabase } from '../utils/supabase.js';
class SubagentEventBus {
    emitter = new EventEmitter();
    buffers = new Map();
    BUFFER_CAP = 200;
    constructor() {
        // Permit many SSE subscribers without warnings (each open dashboard
        // listening to one subagent counts as one listener).
        this.emitter.setMaxListeners(50);
    }
    emit(subagentId, type, message, data) {
        const ev = {
            id: randomUUID(),
            subagent_id: subagentId,
            type, message,
            data,
            timestamp: new Date().toISOString(),
        };
        const buf = this.buffers.get(subagentId) ?? [];
        buf.push(ev);
        if (buf.length > this.BUFFER_CAP)
            buf.splice(0, buf.length - this.BUFFER_CAP);
        this.buffers.set(subagentId, buf);
        this.emitter.emit(subagentId, ev);
        this.emitter.emit('*', ev); // global firehose for "watch all"
        // Best-effort persistence — don't block on it
        void this.persist(ev);
        return ev;
    }
    on(subagentId, listener) {
        this.emitter.on(subagentId, listener);
        return () => this.emitter.off(subagentId, listener);
    }
    onAll(listener) {
        this.emitter.on('*', listener);
        return () => this.emitter.off('*', listener);
    }
    history(subagentId) {
        return [...(this.buffers.get(subagentId) ?? [])];
    }
    async persist(ev) {
        try {
            // Table may not exist yet — auto-create in migrate. Best-effort.
            await supabase.from('subagent_events').insert({
                id: ev.id,
                subagent_id: ev.subagent_id,
                type: ev.type,
                message: ev.message,
                data: JSON.stringify(ev.data ?? {}),
                created_at: ev.timestamp,
            });
        }
        catch { /* table missing or shim — fine */ }
    }
}
export const subagentEvents = new SubagentEventBus();
//# sourceMappingURL=events.js.map