"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    descriptionForAction: ()=>descriptionForAction,
    systemPromptToTaskPlanning: ()=>systemPromptToTaskPlanning
});
const zod_schema_utils_namespaceObject = require("@midscene/shared/zod-schema-utils");
const external_common_js_namespaceObject = require("./common.js");
const commonOutputFields = `"error"?: string, // Error messages about unexpected situations, if any. Only think it is an error when the situation is not foreseeable according to the instruction. Use the same language as the user's instruction.
  "more_actions_needed_by_instruction": boolean, // Consider if there is still more action(s) to do after the action in "Log" is done, according to the instruction. If so, set this field to true. Otherwise, set it to false.`;
const vlLocateParam = (vlMode)=>{
    if (vlMode) return `{bbox: [number, number, number, number], prompt: string } // ${(0, external_common_js_namespaceObject.bboxDescription)(vlMode)}`;
    return "{ prompt: string /* description of the target element */ }";
};
const descriptionForAction = (action, locatorSchemaTypeDescription)=>{
    const tab = '  ';
    const fields = [];
    fields.push(`- type: "${action.name}"`);
    if (action.paramSchema) {
        const paramLines = [];
        const schema = action.paramSchema;
        const isZodObject = schema._def?.typeName === 'ZodObject';
        if (isZodObject && schema.shape) {
            const shape = schema.shape;
            for (const [key, field] of Object.entries(shape))if (field && 'object' == typeof field) {
                const isOptional = 'function' == typeof field.isOptional && field.isOptional();
                const keyWithOptional = isOptional ? `${key}?` : key;
                const typeName = (0, zod_schema_utils_namespaceObject.getZodTypeName)(field, locatorSchemaTypeDescription);
                const description = (0, zod_schema_utils_namespaceObject.getZodDescription)(field);
                let paramLine = `${keyWithOptional}: ${typeName}`;
                if (description) paramLine += ` // ${description}`;
                paramLines.push(paramLine);
            }
            if (paramLines.length > 0) {
                fields.push('- param:');
                paramLines.forEach((line)=>{
                    fields.push(`  - ${line}`);
                });
            }
        } else {
            const typeName = (0, zod_schema_utils_namespaceObject.getZodTypeName)(schema);
            const description = (0, zod_schema_utils_namespaceObject.getZodDescription)(schema);
            let paramDescription = `- param: ${typeName}`;
            if (description) paramDescription += ` // ${description}`;
            paramDescription += ' (pass the value directly, not as an object)';
            fields.push(paramDescription);
        }
    }
    return `- ${action.name}, ${action.description || "No description provided"}
${tab}${fields.join(`\n${tab}`)}
`.trim();
};
async function systemPromptToTaskPlanning({ actionSpace, vlMode, includeBbox }) {
    if (includeBbox && !vlMode) throw new Error('vlMode cannot be undefined when includeBbox is true. A valid vlMode is required for bbox-based location.');
    const actionDescriptionList = actionSpace.map((action)=>descriptionForAction(action, vlLocateParam(includeBbox ? vlMode : void 0)));
    const actionList = actionDescriptionList.join('\n');
    const logFieldInstruction = `
## About the \`log\` field (preamble message)

The \`log\` field is a brief preamble message to the user explaining what you’re about to do. It should follow these principles and examples:

- **Use the same language as the user's instruction**
- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words or Chinese characters for quick updates).
- **Build on prior context**: if this is not the first action to be done, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.

**Examples:**
- "Click the login button"
- "Scroll to find the 'Yes' button in popup"
- "Previous actions failed to find the 'Yes' button, i will try again"
- "Go back to find the login button"
`;
    return `
Target: User will give you an instruction, some screenshots and previous logs indicating what have been done. Your task is to plan the next one action according to current situation to accomplish the instruction.

Please tell what the next one action is (or null if no action should be done) to do the tasks the instruction requires. 

## Rules

- Don't give extra actions or plans beyond the instruction. For example, don't try to submit the form if the instruction is only to fill something.
- Give just the next ONE action you should do
- Consider the current screenshot and give the action that is most likely to accomplish the instruction. For example, if the next step is to click a button but it's not visible in the screenshot, you should try to find it first instead of give a click action.
- Make sure the previous actions are completed successfully before performing the next step
- If there are some error messages reported by the previous actions, don't give up, try parse a new action to recover. If the error persists for more than 5 times, you should think this is an error and set the "error" field to the error message.
- If there is nothing to do but waiting, set the "sleep" field to the positive waiting time in milliseconds and null for the "action" field.
- Assertions are also important steps. When getting the assertion instruction, a solid conclusion is required. You should explicitly state your conclusion by calling the "Print_Assert_Result" action.

## Supporting actions
${actionList}

${logFieldInstruction}

## Return format

Return in JSON format:
{
  "log": string, // a brief preamble to the user explaining what you’re about to do
  ${commonOutputFields}
  "action": 
    {
      "type": string, // the type of the action
      "param"?: { // The parameter of the action, if any
         // k-v style parameter fields
      }, 
    } | null,
  ,
  "sleep"?: number, // The sleep time after the action, in milliseconds.
}

For example, if the instruction is to login and the form has already been filled, this is a valid return value:

{
  "log": "Click the login button",
  "more_actions_needed_by_instruction": false,
  "action": {
    "type": "Tap",
    "param": {
      "locate": { 
        "prompt": "The login button"${vlMode ? ', "bbox": [100, 200, 300, 400]' : ''}
      }
    }
  }
`;
}
exports.descriptionForAction = __webpack_exports__.descriptionForAction;
exports.systemPromptToTaskPlanning = __webpack_exports__.systemPromptToTaskPlanning;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "descriptionForAction",
    "systemPromptToTaskPlanning"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});

//# sourceMappingURL=llm-planning.js.map