import { userPromptToString } from "../../../common.mjs";
import { getDebug } from "@midscene/shared/logger";
import { AIResponseParseError, callAIWithStringResponse } from "../../service-caller/index.mjs";
import { transformAutoGLMAction } from "./actions.mjs";
import { parseAction, parseAutoGLMResponse } from "./parser.mjs";
const debug = getDebug('auto-glm-planning');
async function autoGlmPlanning(userInstruction, options, getSystemPrompt) {
    const { conversationHistory, context, actionContext } = options;
    const systemPrompt = getSystemPrompt() + (actionContext ? `<high_priority_knowledge>${actionContext}</high_priority_knowledge>` : '');
    const imagePayloadBase64 = context.screenshot.base64;
    const userInstructionText = userPromptToString(userInstruction);
    const referenceImageMessages = options.referenceImageMessages ?? [];
    const userInstructionMessage = {
        role: 'user',
        content: [
            {
                type: 'text',
                text: userInstructionText
            }
        ]
    };
    conversationHistory.append({
        role: 'user',
        content: [
            {
                type: 'image_url',
                image_url: {
                    url: imagePayloadBase64
                }
            }
        ]
    });
    const msgs = [
        {
            role: 'system',
            content: systemPrompt
        },
        userInstructionMessage,
        ...referenceImageMessages,
        ...conversationHistory.snapshot(1)
    ];
    const { content: rawResponse, usage, rawChoiceMessage } = await callAIWithStringResponse(msgs, options.modelRuntime, {
        abortSignal: options.abortSignal
    });
    debug('autoGLMPlanning rawResponse:', rawResponse);
    let parsedResponse;
    let transformedActions;
    try {
        parsedResponse = parseAutoGLMResponse(rawResponse);
        debug('thinking in response:', parsedResponse.think);
        debug('action in response:', parsedResponse.content);
        const parsedAction = parseAction(parsedResponse);
        debug('Parsed action object:', parsedAction);
        transformedActions = transformAutoGLMAction(parsedAction, context.shotSize, options.actionSpace);
        debug('Transformed actions:', transformedActions);
    } catch (parseError) {
        const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
        throw new AIResponseParseError(`Parse error: ${errorMessage}`, JSON.stringify(rawResponse, void 0, 2), usage, rawChoiceMessage);
    }
    conversationHistory.append({
        role: 'assistant',
        content: `<think>${parsedResponse.think}</think><answer>${parsedResponse.content}</answer>`
    });
    const shouldContinuePlanning = !parsedResponse.content.startsWith('finish(');
    return {
        actions: transformedActions,
        log: rawResponse,
        usage,
        shouldContinuePlanning,
        rawResponse: JSON.stringify(rawResponse, void 0, 2),
        rawChoiceMessage
    };
}
export { autoGlmPlanning };

//# sourceMappingURL=planning.mjs.map