import { useCallback } from "react";
export function useAgentRunDeltaSocketHandler(input) {
    const { agent, isStoppingRef, currentRunIdRef, lastResyncedMessageIdsRef, messagesRef, lastNonHeartbeatUpdateAtRef, normalizeRunId, noteMissingRunId, appendToolUiEvent, acceptRunSequenceFrame, routeRunDelta, } = input;
    return useCallback((messageType, payload) => {
        if (messageType !== "agent:run:delta") {
            return false;
        }
        if (!agent || isStoppingRef.current) {
            return true;
        }
        const deltaRunId = normalizeRunId(payload?.runId);
        if (deltaRunId === null) {
            noteMissingRunId("agent:run:delta");
        }
        else if (currentRunIdRef.current !== null &&
            deltaRunId !== currentRunIdRef.current) {
            appendToolUiEvent("ui:stream-runid-dropped", `agent:run:delta runId=${deltaRunId} currentRunId=${currentRunIdRef.current}`);
            return true;
        }
        const { seq, type, data, cost } = payload;
        if ((!seq || seq === 0) && data?.messageId) {
            const replayMessageId = String(data.messageId).toLowerCase();
            if (lastResyncedMessageIdsRef.current.has(replayMessageId)) {
                appendToolUiEvent("ui:stream-resync-skip-delta", `agent:run:delta messageId=${data.messageId} reason=already-resynced`);
                return true;
            }
        }
        const isContextUpdate = type === "ContextUpdate" || type === "contextUpdate";
        const isHeartbeat = type === "Heartbeat" || type === "heartbeat";
        const isRunning = agent.status === "running" || agent.status === 1;
        const hasStreaming = messagesRef.current.some((message) => !message.isCompleted && message.messageType === "streaming");
        const hasMessageId = !!data?.messageId;
        if (!isContextUpdate &&
            !isHeartbeat &&
            !isRunning &&
            !hasStreaming &&
            !hasMessageId) {
            return true;
        }
        if (!acceptRunSequenceFrame({
            eventName: "agent:run:delta",
            runId: payload?.runId,
            seq,
        })) {
            return true;
        }
        if (!isHeartbeat) {
            lastNonHeartbeatUpdateAtRef.current = Date.now();
        }
        routeRunDelta({ type, data, cost, seq });
        return true;
    }, [
        acceptRunSequenceFrame,
        agent,
        appendToolUiEvent,
        currentRunIdRef,
        isStoppingRef,
        lastNonHeartbeatUpdateAtRef,
        lastResyncedMessageIdsRef,
        messagesRef,
        normalizeRunId,
        noteMissingRunId,
        routeRunDelta,
    ]);
}
//# sourceMappingURL=useAgentRunDeltaSocketHandler.js.map