export class ACodeHookBus {
    constructor(options) {
        this.options = options;
        this.handlers = [];
    }
    register(handler) {
        this.handlers.push(handler);
    }
    /**
     * 分发 ACode 生命周期 Hook。
     * 主流程：按注册顺序执行 handler -> fail-open 记录错误 -> 遇到 deny 立即返回。
     */
    async dispatch(name, data) {
        const event = {
            name,
            sessionId: this.options.sessionId,
            timestamp: this.options.now?.() ?? new Date().toISOString(),
            data,
        };
        const results = [];
        for (const handler of this.handlers) {
            try {
                const result = await handler(event);
                if (result) {
                    results.push(result);
                    if (result.decision === 'deny') {
                        return results;
                    }
                }
            }
            catch (error) {
                this.options.onError?.(event, error);
            }
        }
        return results;
    }
}
export function findDeniedHookResult(results) {
    return results.find((result) => result.decision === 'deny');
}
