/**
 * Abort-aware async execution utility.
 *
 * Replaces the Promise+async-IIFE anti-pattern used in file tools.
 */
/** Sent back to the LLM as the tool result text when a tool is interrupted. */
export const ABORT_AGENT_MESSAGE = 'User interrupted the operation.';
/**
 * Run an async function with abort signal support.
 * Rejects with ABORT_AGENT_MESSAGE if the signal fires.
 * The `checkAborted` callback throws if abort happened between awaits.
 */
export function withAbort(signal, fn) {
    if (signal?.aborted) {
        return Promise.reject(new Error(ABORT_AGENT_MESSAGE));
    }
    if (!signal) {
        // No signal — just run the function, checkAborted is a no-op
        return fn(() => { });
    }
    return new Promise((resolve, reject) => {
        let settled = false;
        const onAbort = () => {
            if (!settled) {
                settled = true;
                reject(new Error(ABORT_AGENT_MESSAGE));
            }
        };
        signal.addEventListener('abort', onAbort, { once: true });
        const checkAborted = () => {
            if (signal.aborted) {
                throw new Error(ABORT_AGENT_MESSAGE);
            }
        };
        fn(checkAborted).then((result) => {
            signal.removeEventListener('abort', onAbort);
            if (!settled) {
                settled = true;
                resolve(result);
            }
        }, (err) => {
            signal.removeEventListener('abort', onAbort);
            if (!settled) {
                settled = true;
                reject(err);
            }
        });
    });
}
//# sourceMappingURL=abort.js.map