/**
 * Global event bus for Vite-native architecture
 * Replaces the App class event system
 */
import { internal } from './logger/internal';
class GlobalEventBus {
    eventListeners = new Map();
    addEventListener(eventName, callback) {
        let callbacks = this.eventListeners.get(eventName);
        if (!callbacks) {
            callbacks = new Set();
            this.eventListeners.set(eventName, callbacks);
        }
        callbacks.add(callback);
    }
    removeEventListener(eventName, callback) {
        const callbacks = this.eventListeners.get(eventName);
        if (!callbacks)
            return;
        callbacks.delete(callback);
    }
    async fireEvent(eventName, ...args) {
        const callbacks = this.eventListeners.get(eventName);
        if (!callbacks || callbacks.size === 0)
            return;
        for (const callback of callbacks) {
            try {
                await callback(eventName, ...args);
            }
            catch (error) {
                // Log but don't re-throw - event listener errors should not crash the server
                internal.error(`Error in event listener for '${eventName}':`, error);
            }
        }
    }
    clearAllListeners() {
        this.eventListeners.clear();
    }
}
// Global singleton instance
const globalEventBus = new GlobalEventBus();
/**
 * Register an event listener for application lifecycle events.
 *
 * Available events:
 * - `agent.started` - Fired when an agent begins execution
 * - `agent.completed` - Fired when an agent completes successfully
 * - `agent.errored` - Fired when an agent throws an error
 * - `session.started` - Fired when a new session starts
 * - `session.completed` - Fired when a session completes
 * - `thread.created` - Fired when a thread is created
 * - `thread.destroyed` - Fired when a thread is destroyed
 *
 * @example
 * ```typescript
 * import { addEventListener } from '@agentuity/runtime';
 *
 * addEventListener('agent.started', (eventName, agent, ctx) => {
 *   console.log(`${agent.metadata.name} started for session ${ctx.sessionId}`);
 * });
 * ```
 */
export function addEventListener(eventName, callback) {
    globalEventBus.addEventListener(eventName, callback);
}
/**
 * Remove a previously registered event listener.
 */
export function removeEventListener(eventName, callback) {
    globalEventBus.removeEventListener(eventName, callback);
}
/**
 * Fire a global application event.
 *
 * @example
 * ```typescript
 * import { fireEvent } from '@agentuity/runtime';
 *
 * await fireEvent('session.started', session);
 * await fireEvent('agent.completed', agent, ctx);
 * ```
 */
export async function fireEvent(eventName, ...args) {
    await globalEventBus.fireEvent(eventName, ...args);
}
/**
 * Clear all event listeners (useful for testing)
 */
export function clearAllEventListeners() {
    globalEventBus.clearAllListeners();
}
//# sourceMappingURL=_events.js.map