/**
 * Helper to execute middleware chains in order.
 * @internal
 */
export async function runMiddleware(middlewares, hookName, context, ...args) {
    if (!middlewares || middlewares.length === 0)
        return undefined;
    // Response and error hooks run in reverse order (stack model)
    const isReverse = ["onResponse", "onError", "onToolCallEnd", "onToolCallError"].includes(hookName);
    const chain = isReverse ? [...middlewares].reverse() : middlewares;
    let finalResult;
    for (const middleware of chain) {
        if (typeof middleware[hookName] === "function") {
            // @ts-ignore
            const result = await middleware[hookName](context, ...args);
            // Capture the first non-void result (for directives)
            if (result !== undefined && finalResult === undefined) {
                finalResult = result;
            }
        }
    }
    return finalResult;
}
