export function sweepSharedSessions(store, options) {
    const now = Date.now();
    let anyChanged = false;
    for (const [sessionId, session] of store.sessions.entries()) {
        if (session.status === 'closed') {
            const closedAt = session.closedAt ?? session.updatedAt;
            if (now - closedAt >= options.deletionRetentionMs) {
                store.sessions.delete(sessionId);
                store.messages.delete(sessionId);
                store.inputs.delete(sessionId);
                anyChanged = true;
            }
            continue;
        }
        if (!shouldCloseIdleSession(session, now, options))
            continue;
        const reason = idleCloseReason(session, now, options);
        if (!reason)
            continue;
        const closed = {
            ...session,
            status: 'closed',
            activeAgentId: undefined,
            updatedAt: now,
            closedAt: now,
        };
        store.sessions.set(sessionId, closed);
        options.publishUpdate('session-closed', { ...closed, reason });
        anyChanged = true;
    }
    return anyChanged;
}
function shouldCloseIdleSession(session, now, options) {
    return idleCloseReason(session, now, options) !== null;
}
function idleCloseReason(session, now, options) {
    if (session.status !== 'active')
        return null;
    if (session.activeAgentId)
        return null;
    if (session.pendingInputCount > 0)
        return null;
    const idle = now - session.lastActivityAt;
    if (session.messageCount === 0 && idle >= options.idleEmptyMs)
        return 'idle-empty';
    if (session.messageCount > 0 && idle >= options.idleLongMs)
        return 'idle-long';
    return null;
}
