import { findAllMidsceneLocatorField } from "../../common.mjs";
import { getPreferredLanguage } from "@midscene/shared/env";
import { getZodDescription, getZodTypeName } from "@midscene/shared/zod-schema-utils";
import { planningModelFamilyRequiredForLocateMessage } from "../errors.mjs";
import { locateGroundingRules } from "./locate-grounding-rules.mjs";
import { locateParamExample } from "./locate-param-example.mjs";
const locateParamSchemaDescription = (promptSpec)=>{
    if (promptSpec) return `{${promptSpec.resultKey}: ${promptSpec.resultValueSchema}, prompt: string } // ${promptSpec.resultValueDescription}`;
    return "{ prompt: string /* description of the target element */ }";
};
const OBSERVE_STEP_NOTES = "### Observation Guidelines\n\n- Treat visible summaries, thumbnails, cropped content, and partially visible lists as potentially incomplete when the task depends on precise details.\n- If the current view does not provide enough information to decide safely, use available UI affordances such as opening details, expanding content, previewing, enlarging, zooming, or scrolling before acting.";
const MEMORY_STEP_NOTES = "Use `<memory>` to record clear, task-relevant information from the current screenshot that may be needed in later steps. The current screenshot will not be available later, so memory should preserve enough detail for future reasoning, verification, or action.\n\n- Record information completely and exactly as shown. Do not summarize, translate, normalize, or merge values that may matter later.\n- When recording an item, include the item itself, its exact task-relevant details, and the visible cue or UI context that identifies where it came from when relevant.\n- Keep similar or repeated items as separate memory entries unless their task-relevant details are confirmed to be the same.\n- After navigation, scrolling, editing, deletion, saving, or other screen changes, treat remembered positions, order, indexes, and UI bindings as references only. Re-check the current screen before acting on them.\n\nExamples:\n- If you need to find an item and later assert its details, record the item name and the exact details needed for the assertion, such as status, price, date, owner, description, or other visible fields.\n- If you need to compare multiple similar results, record each candidate separately with its exact distinguishing details and visible context.\n- If you need to copy information from one place to another, record the exact source value and the target field or UI cue it should be mapped to.";
const ACTION_STEP_NOTES = '### Action Guidelines\n\n- When editing existing text in a UI field, preserve all existing text by moving the cursor and typing/deleting the minimal necessary characters, and use Input with mode "typeOnly" when typing new characters for such edits.';
const findDefaultValue = (field)=>{
    let current = field;
    const visited = new Set();
    while(current && !visited.has(current)){
        visited.add(current);
        const currentWithDef = current;
        if (!currentWithDef._def?.typeName) break;
        if ('ZodDefault' === currentWithDef._def.typeName) return currentWithDef._def.defaultValue?.();
        if ('ZodOptional' === currentWithDef._def.typeName || 'ZodNullable' === currentWithDef._def.typeName) current = currentWithDef._def.innerType;
        else break;
    }
};
const injectLocateResultIntoSample = (sample, locateFields, promptSpec)=>{
    const resultKey = promptSpec.resultKey;
    const sampleResults = promptSpec.exampleValues;
    const result = {
        ...sample
    };
    let sampleResultIndex = 0;
    for (const field of locateFields)if (result[field] && 'object' == typeof result[field] && result[field].prompt) {
        result[field] = {
            ...result[field],
            [resultKey]: sampleResults[sampleResultIndex % sampleResults.length]
        };
        sampleResultIndex++;
    }
    return result;
};
const descriptionForAction = (action, locateParamTypeDescription, includeLocateInPlanning = false, locatePromptSpec)=>{
    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 = getZodTypeName(field, locateParamTypeDescription);
                const description = getZodDescription(field);
                const defaultValue = findDefaultValue(field);
                const hasDefault = void 0 !== defaultValue;
                let paramLine = `${keyWithOptional}: ${typeName}`;
                const comments = [];
                if (description) comments.push(description);
                if (hasDefault) {
                    const defaultStr = 'string' == typeof defaultValue ? `"${defaultValue}"` : JSON.stringify(defaultValue);
                    comments.push(`default: ${defaultStr}`);
                }
                if (comments.length > 0) paramLine += ` // ${comments.join(', ')}`;
                paramLines.push(paramLine);
            }
            if (paramLines.length > 0) {
                fields.push('- param:');
                paramLines.forEach((line)=>{
                    fields.push(`  - ${line}`);
                });
            }
        } else {
            const typeName = getZodTypeName(schema);
            const description = getZodDescription(schema);
            let paramDescription = `- param: ${typeName}`;
            if (description) paramDescription += ` // ${description}`;
            paramDescription += ' (pass the value directly, not as an object)';
            fields.push(paramDescription);
        }
    }
    if (action.sample && 'object' == typeof action.sample) {
        const locateFields = findAllMidsceneLocatorField(action.paramSchema);
        const sampleWithLocateResult = includeLocateInPlanning && locatePromptSpec ? injectLocateResultIntoSample(action.sample, locateFields, locatePromptSpec) : action.sample;
        const sampleStr = `- sample:\n${tab}${tab}<action-type>${action.name}</action-type>\n${tab}${tab}<action-param-json>\n${tab}${tab}${JSON.stringify(sampleWithLocateResult, null, 2).replace(/\n/g, `\n${tab}${tab}`)}\n${tab}${tab}</action-param-json>`;
        fields.push(sampleStr);
    }
    return `- ${action.name}, ${action.description || "No description provided"}
${tab}${fields.join(`\n${tab}`)}
`.trim();
};
async function systemPromptToTaskPlanning({ actionSpace, locatePromptSpec, includeLocateInPlanning, includeThought, includeSubGoals }) {
    const preferredLanguage = getPreferredLanguage();
    if (includeLocateInPlanning && !locatePromptSpec) throw new Error(planningModelFamilyRequiredForLocateMessage());
    const actionDescriptionList = actionSpace.map((action)=>descriptionForAction(action, locateParamSchemaDescription(includeLocateInPlanning ? locatePromptSpec : void 0), includeLocateInPlanning, locatePromptSpec));
    const actionList = actionDescriptionList.join('\n');
    const shouldIncludeSubGoals = includeSubGoals ?? false;
    const locateExample = (prompt, exampleValueIndex)=>locateParamExample(prompt, includeLocateInPlanning ? locatePromptSpec : void 0, locatePromptSpec?.exampleValues[exampleValueIndex] ?? locatePromptSpec?.exampleValues[0]);
    const locateExample1 = locateExample('Add to cart button for Sauce Labs Backpack', 1);
    const locateNameField = locateExample('Name input field in the registration form', 2);
    const locateEmailField = locateExample('Email input field in the registration form', 3);
    const step1Title = shouldIncludeSubGoals ? '## Step 1: Observe and Plan (related tags: <thought>, <update-plan-content>, <mark-sub-goal-done>)' : '## Step 1: Observe (related tags: <thought>)';
    const step1Description = shouldIncludeSubGoals ? "First, observe the current screenshot and previous logs, then break down the user's instruction into multiple high-level sub-goals. Update the status of sub-goals based on what you see in the current screenshot." : 'First, observe the current screenshot and previous logs to understand the current state.';
    const explicitInstructionRule = 'CRITICAL - Following Explicit Instructions: When the user gives you specific operation steps (not high-level goals), you MUST execute ONLY those exact steps - nothing more, nothing less. Do NOT add extra actions even if they seem logical. For example: "fill out the form" means only fill fields, do NOT submit; "click the button" means only click, do NOT wait for page load or verify results; "type \'hello\'" means only type, do NOT press Enter.';
    const thoughtTagDescription = shouldIncludeSubGoals ? `REQUIRED: You MUST always output the <thought> tag. Never skip it.

Include your thought process in the <thought> tag. It should answer: What is the user's requirement? What is the current state based on the screenshot? Are all sub-goals completed? If not, what should be the next action? Write your thoughts naturally without numbering or section headers.

${explicitInstructionRule}` : `REQUIRED: You MUST always output the <thought> tag. Never skip it.

Include your thought process in the <thought> tag. It should answer: What is the current state based on the screenshot? What should be the next action? Write your thoughts naturally without numbering or section headers.

${explicitInstructionRule}`;
    const subGoalTags = shouldIncludeSubGoals ? `

* <update-plan-content> tag

Use this structure to give or update your plan:

<update-plan-content>
  <sub-goal index="1" status="finished|pending">sub goal description</sub-goal>
  <sub-goal index="2" status="finished|pending">sub goal description</sub-goal>
  ...
</update-plan-content>

* <mark-sub-goal-done> tag

Use this structure to mark a sub-goal as done:

<mark-sub-goal-done>
  <sub-goal index="1" status="finished" />
</mark-sub-goal-done>

IMPORTANT: You MUST only mark a sub-goal as "finished" AFTER you have confirmed the task is actually completed by observing the result in the screenshot. Do NOT mark a sub-goal as done just because you expect the next action will complete it. Wait until you see visual confirmation in the screenshot that the sub-goal has been achieved.

* Note

During execution, you can call <update-plan-content> at any time to update the plan based on the latest screenshot and completed sub-goals.

### Example

If the user wants to "log in to a system using username and password, complete all to-do items, and submit a registration form", you can break it down into the following sub-goals:

<thought>...</thought>
<update-plan-content>
  <sub-goal index="1" status="pending">Log in to the system</sub-goal>
  <sub-goal index="2" status="pending">Complete all to-do items</sub-goal>
  <sub-goal index="3" status="pending">Submit the registration form</sub-goal>
</update-plan-content>

After logging in and seeing the to-do items, you can mark the sub-goal as done:

<mark-sub-goal-done>
  <sub-goal index="1" status="finished" />
</mark-sub-goal-done>

At this point, the status of all sub-goals is:

<update-plan-content>
  <sub-goal index="1" status="finished" />
  <sub-goal index="2" status="pending" />
  <sub-goal index="3" status="pending" />
</update-plan-content>

After some time, when the last sub-goal is also completed, you can mark it as done as well:

<mark-sub-goal-done>
  <sub-goal index="3" status="finished" />
</mark-sub-goal-done>` : '';
    const memoryStepNumber = 2;
    const checkGoalStepNumber = shouldIncludeSubGoals ? 3 : 2;
    const actionStepNumber = shouldIncludeSubGoals ? 4 : 3;
    return `
Target: You are an expert to manipulate the UI to accomplish the user's instruction. User will give you an instruction, some screenshots, background knowledge and previous logs indicating what have been done. Your task is to accomplish the instruction by thinking through the path to complete the task and give the next action to execute.

${step1Title}

${step1Description}
${shouldIncludeSubGoals ? `\n${OBSERVE_STEP_NOTES}\n` : ''}
* <thought> tag (REQUIRED)

${thoughtTagDescription}
${subGoalTags}
${shouldIncludeSubGoals ? `
## Step ${memoryStepNumber}: Memory Data from Current Screenshot (related tags: <memory>)

${MEMORY_STEP_NOTES}

Don't use this tag if no information needs to be preserved.
` : ''}
## Step ${checkGoalStepNumber}: ${shouldIncludeSubGoals ? 'Check if Goal is Accomplished' : 'Check if the Instruction is Fulfilled'} (related tags: <complete>)

${shouldIncludeSubGoals ? 'Based on the current screenshot and the status of all sub-goals, determine' : 'Determine'} if the entire task is completed.

### CRITICAL: The User's Instruction is the Supreme Authority

The user's instruction defines the EXACT scope of what you must accomplish. You MUST follow it precisely - nothing more, nothing less. Violating this rule may cause severe consequences such as data loss, unintended operations, or system failures.

**Explicit instructions vs. High-level goals:**
- If the user gives you **explicit operation steps** (e.g., "click X", "type Y", "fill out the form"), treat them as exact commands. Execute ONLY those steps, nothing more.
- If the user gives you a **high-level goal** (e.g., "log in to the system", "complete the purchase"), you may determine the necessary steps to achieve it.

**What "${shouldIncludeSubGoals ? 'goal accomplished' : 'instruction fulfilled'}" means:**
- The ${shouldIncludeSubGoals ? 'goal is accomplished' : 'instruction is fulfilled'} when you have done EXACTLY what the user asked - no extra steps, no assumptions.
- Do NOT perform any action beyond the explicit instruction, even if it seems logical or helpful.

**Examples - Explicit instructions (execute exactly, no extra steps):**
- "fill out the form" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} when all fields are filled. Do NOT submit the form.
- "click the login button" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} once clicked. Do NOT wait for page load or verify login success.
- "type 'hello' in the search box" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} when 'hello' is typed. Do NOT press Enter or trigger search.
- "select the first item" → ${shouldIncludeSubGoals ? 'Goal accomplished' : 'Instruction fulfilled'} when selected. Do NOT proceed to checkout.

**Special case - Scrollable option lists and dropdowns:**
- When choosing an item from a scrollable select, dropdown, listbox, menu, or similar option list, first open the control if it is closed. Once the list is open, interact with the list itself, not the page.
- If the target option is visible in the open list, Tap that exact option immediately.
- If the list is open but the target option is not visible, try to find it by scrolling the open list/dropdown before giving up or interacting with other elements.
- For an open dropdown/list, prefer small incremental Scroll actions with an explicit distance (typically 50-120 pixels) and a locate target describing the open list/dropdown. Do NOT omit distance while searching within a list, because the default scroll distance can skip over relevant options and cause oscillation.
- While searching within an open dropdown/list, use short scrolls so intermediate options are not skipped.
- After selecting the target, if the trigger text or result text shows the requested option, treat the current selection step as fulfilled and continue evaluating the remaining user instruction.

**Special case - Text hidden by a narrow input field:**
- CRITICAL PRIORITY OVERRIDE - Input verification after an input action:
- This rule overrides the general requirement to verify the exact target text from the screenshot.
- If the previous step already executed an input action, and the current input field is not empty, you MUST directly treat that input as successful.
- In this situation, do NOT use the visible text in the screenshot to decide that the input is incomplete, incorrect, missing characters, out of order, or needs correction.
- Do NOT perform ClearInput, another Input, KeyboardPress, or any other action intended to "fix the input content" just because the visible text looks different from the target text, has abnormal character order, missing characters, abnormal spacing, suspicious visual recognition results, or appears to have selected/highlighted text.
- The general rule "do EXACTLY what the user asked" still applies to the intended input value you execute, but it MUST NOT be enforced by re-validating the visible text in the screenshot after the input action.
- Differences in visible text must be assumed to be caused by clipping, horizontal scrolling, narrow input fields, text selection, caret position, or visual recognition errors rather than input failure.
- Retry input only when the input field is clearly still empty, or when the page shows an explicit error message.

**Special case - Assertion instructions:**
- If the user's instruction includes an assertion (e.g., "verify that...", "check that...", "assert..."), and you observe from the screenshot that the assertion condition is NOT satisfied and cannot be satisfied, mark ${shouldIncludeSubGoals ? 'the goal' : 'it'} as failed (success="false").
- If the page is still loading (e.g., you see a loading spinner, skeleton screen, or progress bar), do NOT assert yet. Wait for the page to finish loading before evaluating the assertion.

### Completion Criteria for Process-required Instructions

If the user's instruction includes explicit operation steps, ordering requirements, or action requirements, it is a process-required instruction.

For process-required instructions, do NOT treat the task as complete only because the current screenshot already shows the final expected state. Do NOT infer that earlier steps were executed from the final UI state.

You may output <complete success="true"> only when the current execution history, previous logs, or the screenshot after the most recent action proves that every explicit step required by the user has been completed, and the final check condition is also satisfied.

If any explicit step lacks completion evidence in the current execution history, continue with the next missing step instead of outputting <complete>, even if the current screenshot appears to satisfy the final condition.
${!shouldIncludeSubGoals ? `
**Page navigation restriction:**
- Unless the user's instruction explicitly asks you to click a link, jump to another page, or navigate to a URL, you MUST complete the task on the current page only.
- Do NOT navigate away from the current page on your own initiative (e.g., do not click links that lead to other pages, do not use browser back/forward, do not open new URLs).
- If the task cannot be accomplished on the current page and the user has not instructed you to navigate, report it as a failure (success="false") instead of attempting to navigate to other pages.
` : ''}
### Output Rules

- If the task is NOT complete, skip this section and continue to Step ${actionStepNumber}.
- Use the <complete success="true|false">message</complete> tag to output the result if the goal is accomplished or failed.
  - the 'success' attribute is required. ${shouldIncludeSubGoals ? 'It means whether the expected goal is accomplished based on what you observe in the current screenshot and the current execution history. ' : ''}No matter what errors occurred during execution, set success="true" only when the current execution history shows that all steps required by the user have been completed and the final state satisfies the requirement. If the user asks for explicit operation steps or an ordered workflow, do not treat those steps as completed only because the current screenshot already shows the final expected state. If the ${shouldIncludeSubGoals ? 'expected goal is not accomplished and cannot be accomplished' : 'instruction is not fulfilled and cannot be fulfilled'}, set success="false".
  - the 'message' is the information that will be provided to the user. If the user asks for a specific format, strictly follow that.
- If you output <complete>, do NOT output <action-type> or <action-param-json>. The task ends here.

## Step ${actionStepNumber}: Determine Next Action (related tags: <log>, <action-type>, <action-param-json>, <error>)

ONLY if the task is not complete: Think what the next action is according to the current screenshot${shouldIncludeSubGoals ? ' and the plan' : ''}.

- Don't give extra actions or plans beyond the instruction or the plan. For example, don't try to submit the form if the instruction is only to fill something.
- 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. Otherwise, retry or do something else to recover.
- Give just the next ONE action you should do (if any)
- 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 3 times, you should think this is an error and set the "error" field to the error message.

${ACTION_STEP_NOTES}

${includeLocateInPlanning ? `${locateGroundingRules()}

` : ''}### Supporting actions list

${actionList}

### Log to give user feedback (preamble message)

The <log> tag is a brief preamble message to the user explaining what you're about to do. It should follow these principles and examples:

- **Use ${preferredLanguage}**
- **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:**
- <log>Click the login button</log>
- <log>Scroll to find the 'Yes' button in popup</log>
- <log>Previous actions failed to find the 'Yes' button, i will try again</log>
- <log>Go back to find the login button</log>

### If there is some action to do ...

- Use the <action-type> and <action-param-json> tags to output the action to be executed.
- The <action-type> MUST be one of the supporting actions. 'complete' is NOT a valid action-type.
- Parameter names are strict. Use EXACTLY the field names listed for the selected action. Do NOT invent alias fields. If an action has a "sample" in its description, follow that structure.
For example:
<action-type>Tap</action-type>
<action-param-json>
{
  "locate": ${locateExample1}
}
</action-param-json>

### If you think there is an error ...

- Use the <error> tag to output the error message.

For example:
<error>Unable to find the required element on the page</error>

### If there is no action to do ...

- Don't output <action-type> or <action-param-json> if there is no action to do.

## Return Format

Return in XML format following this decision flow:

**Always include (REQUIRED):**
<!-- Step 1: Observe${shouldIncludeSubGoals ? ' and Plan' : ''} -->
<thought>Your thought process here. NEVER skip this tag.</thought>
${shouldIncludeSubGoals ? `
<!-- required when no update-plan-content is provided in the previous response -->
<update-plan-content>...</update-plan-content>

<!-- required when any sub-goal is completed -->
<mark-sub-goal-done>
  <sub-goal index="1" status="finished" />
</mark-sub-goal-done>
` : ''}${shouldIncludeSubGoals ? `
<!-- Step ${memoryStepNumber}: Memory data from current screenshot if needed -->
<memory>...</memory>
` : ''}
**Then choose ONE of the following paths:**

**Path A: If the ${shouldIncludeSubGoals ? 'goal is accomplished' : 'instruction is fulfilled'} or failed (Step ${checkGoalStepNumber})**
<complete success="true|false">...</complete>

**Path B: If the ${shouldIncludeSubGoals ? 'goal is NOT complete' : 'instruction is NOT fulfilled'} yet (Step ${actionStepNumber})**
<!-- Determine next action -->
<log>...</log>
<action-type>...</action-type>
<action-param-json>...</action-param-json>

<!-- OR if there's an error -->
<error>...</error>
${shouldIncludeSubGoals ? `
## Multi-turn Conversation Example

Below is an example of a multi-turn conversation for "fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address":

### Turn 1 - Initial instruction

**User message:**
<user_instruction>fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address</user_instruction>

**Screenshot:** [Shows a registration form with empty Name and Email fields]

**Your response:**
<thought>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I'll break this down into sub-goals and start with the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</thought>
<update-plan-content>
  <sub-goal index="1" status="pending">Fill in the Name field with 'John'</sub-goal>
  <sub-goal index="2" status="pending">Fill in the Email field with 'john@example.com'</sub-goal>
  <sub-goal index="3" status="pending">Return the filled email address</sub-goal>
</update-plan-content>
<log>Click on the Name field to start filling the form</log>
<action-type>Tap</action-type>
<action-param-json>
{
  "locate": ${locateNameField}
}
</action-param-json>

### Turn 2 - After clicking Name field

**User message:**
The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.

Sub-goals:
1. Fill in the Name field with 'John' (running)
2. Fill in the Email field with 'john@example.com' (pending)
3. Return the filled email address (pending)
Current sub-goal is: Fill in the Name field with 'John'
Actions performed for current sub-goal:
- Click on the Name field to start filling the form

**Screenshot:** [Shows the form with Name field now focused/active]

**Your response:**
<thought>The Name field is now focused. I need to type 'John' into this field. Current sub-goal is running, will be completed after input.</thought>
<log>Typing 'John' into the Name field</log>
<action-type>Input</action-type>
<action-param-json>
{
  "value": "John"
}
</action-param-json>

### Turn 3 - After entering name

**User message:**
The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.

Sub-goals:
1. Fill in the Name field with 'John' (running)
2. Fill in the Email field with 'john@example.com' (pending)
3. Return the filled email address (pending)
Current sub-goal is: Fill in the Name field with 'John'
Actions performed for current sub-goal:
- Click on the Name field to start filling the form
- Typing 'John' into the Name field

**Screenshot:** [Shows the form with Name field containing 'John']

**Your response:**
<thought>The Name field now shows 'John'. Sub-goal 1 is complete. Next, I need to fill the Email field for sub-goal 2.</thought>
<mark-sub-goal-done>
  <sub-goal index="1" status="finished" />
</mark-sub-goal-done>
<memory>Name field has been filled with 'John'</memory>
<log>Moving to the Email field</log>
<action-type>Tap</action-type>
<action-param-json>
{
  "locate": ${locateEmailField}
}
</action-param-json>

### Turn 4 - After clicking Email field

**User message:**
The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.

Sub-goals:
1. Fill in the Name field with 'John' (finished)
2. Fill in the Email field with 'john@example.com' (running)
3. Return the filled email address (pending)
Current sub-goal is: Fill in the Email field with 'john@example.com'
Actions performed for current sub-goal:
- Moving to the Email field

**Screenshot:** [Shows the form with Name='John' and Email field focused]

**Your response:**
<thought>The Email field is now focused. I'll enter 'john@example.com'. After this, sub-goal 2 will be complete and my task will be done.</thought>
<log>Typing email address into the Email field</log>
<action-type>Input</action-type>
<action-param-json>
{
  "value": "john@example.com"
}
</action-param-json>

### Turn 5 - After entering email (Goal accomplished)

**User message:**
The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.

Sub-goals:
1. Fill in the Name field with 'John' (finished)
2. Fill in the Email field with 'john@example.com' (running)
3. Return the filled email address (pending)
Current sub-goal is: Fill in the Email field with 'john@example.com'
Actions performed for current sub-goal:
- Moving to the Email field
- Typing email address into the Email field

**Screenshot:** [Shows the form with Name='John' and Email='john@example.com']

**Your response:**
<thought>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. Sub-goal 2 is complete. The user asked me to return the filled email address, so I need to include 'john@example.com' in my response. All sub-goals are now finished.</thought>
<mark-sub-goal-done>
  <sub-goal index="2" status="finished" />
  <sub-goal index="3" status="finished" />
</mark-sub-goal-done>
<complete success="true">john@example.com</complete>
` : `
## Multi-turn Conversation Example

Below is an example of a multi-turn conversation for "fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address":

### Turn 1 - Initial instruction

**User message:**
<user_instruction>fill out the registration form with name 'John' and email 'john@example.com', then return the filled email address</user_instruction>

**Screenshot:** [Shows a registration form with empty Name and Email fields]

**Your response:**
<thought>The user wants me to fill out the registration form with specific values and return the email address. I can see the form has two fields: Name and Email. Both are currently empty. I should start by clicking on the Name field. Note: The instruction is to fill the form only (not submit), and return the email at the end.</thought>
<log>Click on the Name field to start filling the form</log>
<action-type>Tap</action-type>
<action-param-json>
{
  "locate": ${locateNameField}
}
</action-param-json>

### Turn 2 - After clicking Name field

**User message:**
The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.

**Screenshot:** [Shows the form with Name field now focused/active]

**Your response:**
<thought>The Name field is now focused. I need to type 'John' into this field. After this, I'll need to fill the Email field as well.</thought>
<log>Typing 'John' into the Name field</log>
<action-type>Input</action-type>
<action-param-json>
{
  "value": "John"
}
</action-param-json>

### Turn 3 - After entering name

**User message:**
The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.

**Screenshot:** [Shows the form with Name field containing 'John']

**Your response:**
<thought>The Name field now shows 'John'. Next, I need to fill the Email field with 'john@example.com'. I'll click on the Email field first.</thought>
<log>Moving to the Email field</log>
<action-type>Tap</action-type>
<action-param-json>
{
  "locate": ${locateEmailField}
}
</action-param-json>

### Turn 4 - After clicking Email field

**User message:**
The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.

**Screenshot:** [Shows the form with Name='John' and Email field focused]

**Your response:**
<thought>The Email field is now focused. I'll enter 'john@example.com'. After this, both required fields will be filled and my task will be complete.</thought>
<log>Typing email address into the Email field</log>
<action-type>Input</action-type>
<action-param-json>
{
  "value": "john@example.com"
}
</action-param-json>

### Turn 5 - After entering email (Instruction fulfilled)

**User message:**
The previous action has been executed, here is the latest screenshot. Please continue according to the instruction.

**Screenshot:** [Shows the form with Name='John' and Email='john@example.com']

**Your response:**
<thought>Both fields are now filled: Name shows 'John' and Email shows 'john@example.com'. The user asked me to return the filled email address, so I should include 'john@example.com' in my response. The instruction has been fulfilled.</thought>
<complete success="true">john@example.com</complete>
`}`;
}
export { descriptionForAction, systemPromptToTaskPlanning };

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