export class RuntimeEventBus {
    #listeners = new Set();
    #transcriptStats = new Map();
    #recorder;
    #nextSequence = 1;
    constructor(recorder) {
        this.#recorder = recorder;
    }
    subscribe(listener) {
        this.#listeners.add(listener);
        return () => {
            this.#listeners.delete(listener);
        };
    }
    clear() {
        this.#listeners.clear();
    }
    emit(event) {
        const envelope = this.#recorder?.appendEvent(event) ??
            {
                event,
                sequence: this.#nextSequence++,
            };
        this.#nextSequence = Math.max(this.#nextSequence, envelope.sequence + 1);
        this.#recordTranscriptStats(envelope);
        for (const listener of this.#listeners) {
            listener(envelope);
        }
        return envelope;
    }
    emitTransient(event) {
        const envelope = {
            event,
            sequence: this.#nextSequence++,
        };
        this.#recordTranscriptStats(envelope);
        for (const listener of this.#listeners) {
            listener(envelope);
        }
        return envelope;
    }
    #recordTranscriptStats(envelope) {
        const { event } = envelope;
        if (event.type === "thread.transcript.delta") {
            const state = this.#ensureTranscriptState(event.threadId);
            state.deltaCount += 1;
            state.latestCursor = event.cursor;
            state.latestSequence = envelope.sequence;
        }
    }
    getTranscriptStats(threadId) {
        const state = this.#transcriptStats.get(threadId);
        return {
            deltaCount: state?.deltaCount ?? 0,
            latestCursor: state?.latestCursor ?? 0,
            latestSequence: state?.latestSequence ?? 0,
        };
    }
    #ensureTranscriptState(threadId) {
        let state = this.#transcriptStats.get(threadId);
        if (!state) {
            state = {
                deltaCount: 0,
                latestCursor: 0,
                latestSequence: 0,
            };
            this.#transcriptStats.set(threadId, state);
        }
        return state;
    }
}
//# sourceMappingURL=runtime-events.js.map