export const RUN_HANDLE_TERMINATION_GRACE_MS = 1_000;
export async function terminateRunHandle(handle, graceMs = RUN_HANDLE_TERMINATION_GRACE_MS) {
    killQuietly(handle, "SIGTERM");
    if (await waitForRunHandle(handle, graceMs)) {
        return { escalated: false, exited: true };
    }
    killQuietly(handle, "SIGKILL");
    return {
        escalated: true,
        exited: await waitForRunHandle(handle, graceMs)
    };
}
function killQuietly(handle, signal) {
    try {
        handle.kill(signal);
    }
    catch {
        // Best effort: callers still continue through the bounded wait/escalation path.
    }
}
function waitForRunHandle(handle, timeoutMs) {
    let timeout = null;
    return Promise.race([
        handle.result.then(() => true, () => true),
        new Promise((resolve) => {
            timeout = setTimeout(() => {
                resolve(false);
            }, timeoutMs);
        })
    ]).finally(() => {
        if (timeout !== null) {
            clearTimeout(timeout);
        }
    });
}
