import { ToolExecutionMode } from "../constants.js";
import { ToolError } from "../errors/index.js";
import { ToolHalt } from "./Tool.js";
export class ToolHandler {
    static shouldExecuteTools(toolCalls, mode) {
        if (!toolCalls || toolCalls.length === 0)
            return false;
        if (mode === ToolExecutionMode.DRY_RUN)
            return false;
        return true;
    }
    static async requestToolConfirmation(toolCall, onConfirm) {
        if (!onConfirm)
            return true;
        const confirmed = await onConfirm(toolCall);
        return confirmed !== false;
    }
    static async execute(toolCall, tools, onStart, onEnd) {
        if (onStart)
            onStart(toolCall);
        const tool = tools?.find((t) => t.function.name === toolCall.function.name);
        if (tool?.handler) {
            const args = JSON.parse(toolCall.function.arguments);
            const result = await tool.handler(args);
            // Check if this is a halt signal
            const isHalt = typeof result === "object" && result !== null && result instanceof ToolHalt;
            const content = isHalt
                ? result.content
                : typeof result === "string"
                    ? result
                    : JSON.stringify(result);
            if (onEnd)
                onEnd(toolCall, result);
            return {
                role: "tool",
                tool_call_id: toolCall.id,
                content,
                halted: isHalt
            };
        }
        else {
            throw new ToolError("Tool not found or no handler provided", toolCall.function?.name ?? "unknown");
        }
    }
}
