"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleDoneToolCall = handleDoneToolCall;
const ai_1 = require("ai");
const zod_1 = require("zod");
const ai_2 = require("ai");
const utils_js_1 = require("../../../utils.js");
function buildBaseDoneSchema(factory) {
    return factory.object({
        reasoning: factory
            .string()
            .describe("Brief summary of what actions were taken and the outcome"),
        taskComplete: factory
            .boolean()
            .describe("true if the task was fully completed, false otherwise"),
    });
}
/**
 * Force a done tool call at the end of an agent run.
 * This ensures we always get a structured final response,
 * even if the main loop ended without calling done.
 */
async function handleDoneToolCall(options) {
    const { model, inputMessages, instruction, outputSchema, logger } = options;
    logger({
        category: "agent",
        message: "Agent calling tool: done",
        level: 1,
    });
    // Use the same Zod version as the user's outputSchema to avoid v3/v4 mixing
    const factory = outputSchema
        ? (0, utils_js_1.getZFactory)(outputSchema)
        : zod_1.z;
    const baseDoneSchema = buildBaseDoneSchema(factory);
    // Merge base done schema with user-provided output schema if present
    const doneToolSchema = outputSchema
        ? baseDoneSchema.extend({
            output: outputSchema.describe("The specific data the user requested from this task"),
        })
        : baseDoneSchema;
    const outputInstructions = outputSchema
        ? `\n\nThe user also requested the following information from this task. Provide it in the "output" field:\n${JSON.stringify(Object.fromEntries(Object.entries(outputSchema.shape).map(([key, value]) => [
            key,
            value.description || "no description",
        ])), null, 2)}`
        : "";
    const systemPrompt = `You are a web automation assistant that was tasked with completing a task.

The task was:
"${instruction}"

Review what was accomplished and provide your final assessment in whether the task was completed successfully. you have been provided with the history of the actions taken so far, use this to determine if the task was completed successfully.${outputInstructions}

Call the "done" tool with:
1. A brief summary of what was done
2. Whether the task was completed successfully${outputSchema ? "\n3. The requested output data based on what you found" : ""}`;
    const doneTool = (0, ai_2.tool)({
        description: outputSchema
            ? "Complete the task with your assessment and the requested output data."
            : "Complete the task with your final assessment.",
        inputSchema: doneToolSchema,
        execute: async (params) => {
            return { success: true, ...params };
        },
    });
    const userPrompt = {
        role: "user",
        content: outputSchema
            ? "Provide your final assessment and the requested output data."
            : "Provide your final assessment.",
    };
    const result = await (0, ai_1.generateText)({
        model,
        system: systemPrompt,
        messages: [...inputMessages, userPrompt],
        tools: { done: doneTool },
        toolChoice: { type: "tool", toolName: "done" },
    });
    const doneToolCall = result.toolCalls.find((tc) => tc.toolName === "done");
    const outputMessages = [
        userPrompt,
        ...(result.response?.messages || []),
    ];
    if (!doneToolCall) {
        return {
            reasoning: result.text || "Task execution completed",
            taskComplete: false,
            messages: outputMessages,
        };
    }
    const input = doneToolCall.input;
    logger({
        category: "agent",
        message: `Task completed`,
        level: 1,
    });
    return {
        reasoning: input.reasoning,
        taskComplete: input.taskComplete,
        messages: outputMessages,
        output: input.output,
    };
}
//# sourceMappingURL=handleDoneToolCall.js.map