import { useCallback } from "react";
import { rejectAgentSessionToolCall } from "./useAgentSessionSync";
function isStaleToolCallError(error) {
    const message = error instanceof Error ? error.message : error == null ? "" : String(error);
    return /tool call (reference '.*' )?not found|not found in memory or database/i.test(message);
}
export function useAgentToolApprovalSupersede(input) {
    const { agentId, pendingApprovals, setError } = input;
    const supersedePendingApprovals = useCallback(async () => {
        if (pendingApprovals.length === 0) {
            return true;
        }
        if (!agentId) {
            console.error("[AgentTerminal] handleSubmit blocked: cannot supersede pending approvals; no agentId");
            setError("Agent not ready. Please try again.");
            return false;
        }
        try {
            await Promise.all(pendingApprovals.map(async (pending) => {
                try {
                    await rejectAgentSessionToolCall({
                        agentId,
                        messageId: pending.dbMessageId || pending.messageId,
                        toolCallId: pending.toolCallId,
                        note: "Superseded by new user instructions",
                    });
                }
                catch (error) {
                    if (!isStaleToolCallError(error)) {
                        throw error;
                    }
                    console.warn("[AgentTerminal] Pending tool call was already resolved while superseding:", error);
                }
                window.dispatchEvent(new CustomEvent("agent:toolApprovalResolved", {
                    detail: {
                        agentId,
                        messageId: pending.dbMessageId || pending.messageId,
                        toolCallId: pending.toolCallId,
                        approved: false,
                    },
                }));
            }));
            return true;
        }
        catch (error) {
            console.error("[AgentTerminal] Failed to supersede pending tool calls:", error);
            setError(`Failed to cancel pending tool call: ${error?.message || String(error)}`);
            return false;
        }
    }, [agentId, pendingApprovals, setError]);
    return { supersedePendingApprovals };
}
//# sourceMappingURL=useAgentToolApprovalSupersede.js.map