import { AsyncJobManager } from "./job-manager.js";
const STREAMING_DELIVERY_POLL_MS = 10;
function scheduleBoundaryCheck(callback) {
    const timer = setTimeout(callback, STREAMING_DELIVERY_POLL_MS);
    timer.unref?.();
    return timer;
}
function waitForStreamingBoundary(session, isStale) {
    return new Promise((resolve) => {
        let timer;
        const settle = (value) => {
            if (timer)
                clearTimeout(timer);
            resolve(value);
        };
        const check = () => {
            timer = undefined;
            if (isStale()) {
                settle("stale");
                return;
            }
            if (session.isStreaming !== true) {
                settle("ready");
                return;
            }
            timer = scheduleBoundaryCheck(check);
        };
        check();
    });
}
export function createSessionAsyncDeliveryHandler(session, manager, sessionId) {
    return async (message) => {
        const isStale = () => manager?.disposed === true ||
            manager?.isDeliverySuppressed(message.details.jobId) === true ||
            (sessionId !== undefined && manager?.isSessionDisposed(sessionId) === true);
        if (await waitForStreamingBoundary(session, isStale) === "stale")
            return;
        if (isStale())
            return;
        await session.sendCustomMessage(message, { deliverAs: "followUp", triggerTurn: true });
    };
}
export function createSessionAsyncJobManager(session) {
    const existing = AsyncJobManager.instance();
    if (existing)
        return { manager: existing, owns: false, sessionId: existing.registerSession() };
    let manager;
    manager = new AsyncJobManager({
        onJobComplete: (message) => createSessionAsyncDeliveryHandler(session, manager)(message),
    });
    AsyncJobManager.setInstance(manager);
    return { manager, owns: true, sessionId: manager.registerSession() };
}
export function disposeSessionAsyncJobManager(manager, sessionId) {
    if (!manager || !sessionId)
        return;
    manager.releaseSession(sessionId);
    if (manager.disposed && AsyncJobManager.instance() === manager)
        AsyncJobManager.setInstance(undefined);
}
//# sourceMappingURL=session-manager.js.map