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";
import { getAutoGLMPlanPrompt } from "./prompt.mjs";
const debug = getDebug('auto-glm-planning');
async function autoGLMPlanning(userInstruction, options) {
    const { conversationHistory, context, modelConfig, actionContext } = options;
    const systemPrompt = getAutoGLMPlanPrompt(modelConfig.modelFamily) + (actionContext ? `<high_priority_knowledge>${actionContext}</high_priority_knowledge>` : '');
    const imagePayloadBase64 = context.screenshot.base64;
    conversationHistory.append({
        role: 'user',
        content: [
            {
                type: 'text',
                text: userInstruction
            }
        ]
    });
    conversationHistory.append({
        role: 'user',
        content: [
            {
                type: 'image_url',
                image_url: {
                    url: imagePayloadBase64
                }
            }
        ]
    });
    const msgs = [
        {
            role: 'system',
            content: systemPrompt
        },
        ...conversationHistory.snapshot(1)
    ];
    const { content: rawResponse, usage } = await callAIWithStringResponse(msgs, modelConfig);
    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);
        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);
    }
    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)
    };
}
export { autoGLMPlanning };

//# sourceMappingURL=planning.mjs.map