@midscene/core 1.12.4-beta-20260904041024.0 → 1.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/es/agent/agent.mjs +72 -25
  2. package/dist/es/agent/agent.mjs.map +1 -1
  3. package/dist/es/agent/index.mjs +2 -1
  4. package/dist/es/agent/insight.mjs +26 -10
  5. package/dist/es/agent/insight.mjs.map +1 -1
  6. package/dist/es/agent/prompt-context.mjs +12 -7
  7. package/dist/es/agent/prompt-context.mjs.map +1 -1
  8. package/dist/es/agent/run-gherkin-scenario.mjs +1 -1
  9. package/dist/es/agent/run-gherkin-scenario.mjs.map +1 -1
  10. package/dist/es/agent/tasks.mjs +2 -1
  11. package/dist/es/agent/tasks.mjs.map +1 -1
  12. package/dist/es/agent/test-runner-nodes.mjs +274 -0
  13. package/dist/es/agent/test-runner-nodes.mjs.map +1 -0
  14. package/dist/es/agent/utils.mjs +1 -1
  15. package/dist/es/ai-model/prompt/insight/user-prompt.mjs +1 -1
  16. package/dist/es/ai-model/prompt/insight/user-prompt.mjs.map +1 -1
  17. package/dist/es/ai-model/workflows/insight/extraction.mjs +3 -1
  18. package/dist/es/ai-model/workflows/insight/extraction.mjs.map +1 -1
  19. package/dist/es/ai-model/workflows/planning/custom-planning.mjs +3 -3
  20. package/dist/es/ai-model/workflows/planning/custom-planning.mjs.map +1 -1
  21. package/dist/es/ai-model/workflows/planning/standard-planning.mjs +1 -1
  22. package/dist/es/ai-model/workflows/planning/standard-planning.mjs.map +1 -1
  23. package/dist/es/report-html-template.mjs +1 -1
  24. package/dist/es/types.mjs.map +1 -1
  25. package/dist/es/utils.mjs +1 -1
  26. package/dist/es/yaml/player.mjs +0 -5
  27. package/dist/es/yaml/player.mjs.map +1 -1
  28. package/dist/es/yaml.mjs.map +1 -1
  29. package/dist/lib/agent/agent.js +72 -25
  30. package/dist/lib/agent/agent.js.map +1 -1
  31. package/dist/lib/agent/index.js +57 -8
  32. package/dist/lib/agent/insight.js +26 -10
  33. package/dist/lib/agent/insight.js.map +1 -1
  34. package/dist/lib/agent/prompt-context.js +16 -8
  35. package/dist/lib/agent/prompt-context.js.map +1 -1
  36. package/dist/lib/agent/run-gherkin-scenario.js +1 -1
  37. package/dist/lib/agent/run-gherkin-scenario.js.map +1 -1
  38. package/dist/lib/agent/tasks.js +2 -1
  39. package/dist/lib/agent/tasks.js.map +1 -1
  40. package/dist/lib/agent/test-runner-nodes.js +353 -0
  41. package/dist/lib/agent/test-runner-nodes.js.map +1 -0
  42. package/dist/lib/agent/utils.js +1 -1
  43. package/dist/lib/ai-model/prompt/insight/user-prompt.js +1 -1
  44. package/dist/lib/ai-model/prompt/insight/user-prompt.js.map +1 -1
  45. package/dist/lib/ai-model/workflows/insight/extraction.js +3 -1
  46. package/dist/lib/ai-model/workflows/insight/extraction.js.map +1 -1
  47. package/dist/lib/ai-model/workflows/planning/custom-planning.js +3 -3
  48. package/dist/lib/ai-model/workflows/planning/custom-planning.js.map +1 -1
  49. package/dist/lib/ai-model/workflows/planning/standard-planning.js +1 -1
  50. package/dist/lib/ai-model/workflows/planning/standard-planning.js.map +1 -1
  51. package/dist/lib/report-html-template.js +1 -1
  52. package/dist/lib/types.js.map +1 -1
  53. package/dist/lib/utils.js +1 -1
  54. package/dist/lib/yaml/player.js +0 -5
  55. package/dist/lib/yaml/player.js.map +1 -1
  56. package/dist/lib/yaml.js.map +1 -1
  57. package/dist/types/agent/agent.d.ts +26 -3
  58. package/dist/types/agent/index.d.ts +3 -1
  59. package/dist/types/agent/insight.d.ts +5 -1
  60. package/dist/types/agent/prompt-context.d.ts +2 -0
  61. package/dist/types/agent/run-gherkin-scenario.d.ts +1 -0
  62. package/dist/types/agent/test-runner-nodes.d.ts +192 -0
  63. package/dist/types/types.d.ts +28 -0
  64. package/dist/types/yaml.d.ts +12 -4
  65. package/package.json +10 -2
@@ -1,8 +1,13 @@
1
- const buildPromptWithContext = (prompt, context)=>{
1
+ const renderAIContext = (context)=>{
2
2
  const trimmedContext = context?.trim();
3
- if (!trimmedContext) return prompt;
3
+ if (trimmedContext) return `<CONTEXT>\n${trimmedContext}\n</CONTEXT>`;
4
+ return void 0 === context ? void 0 : '';
5
+ };
6
+ const buildPromptWithContext = (prompt, context)=>{
7
+ const renderedContext = renderAIContext(context);
8
+ if (!renderedContext) return prompt;
4
9
  const promptText = 'string' == typeof prompt ? prompt : prompt.prompt;
5
- const promptWithContext = `Context for this request:\n${trimmedContext}\n\n${promptText}`;
10
+ const promptWithContext = `${renderedContext}\n\n${promptText}`;
6
11
  if ('string' == typeof prompt) return promptWithContext;
7
12
  return {
8
13
  ...prompt,
@@ -10,16 +15,16 @@ const buildPromptWithContext = (prompt, context)=>{
10
15
  };
11
16
  };
12
17
  const buildLocatePromptWithContext = (prompt, context)=>{
13
- const trimmedContext = context?.trim();
14
- if (!trimmedContext) return prompt;
18
+ const renderedContext = renderAIContext(context);
19
+ if (!renderedContext) return prompt;
15
20
  const promptText = 'string' == typeof prompt ? prompt : prompt.prompt;
16
- const promptWithContext = `<CONTEXT>\n${trimmedContext}\n</CONTEXT>\n\n<LOCATE_TARGET>\n${promptText}\n</LOCATE_TARGET>`;
21
+ const promptWithContext = `${renderedContext}\n\n<LOCATE_TARGET>\n${promptText}\n</LOCATE_TARGET>`;
17
22
  if ('string' == typeof prompt) return promptWithContext;
18
23
  return {
19
24
  ...prompt,
20
25
  prompt: promptWithContext
21
26
  };
22
27
  };
23
- export { buildLocatePromptWithContext, buildPromptWithContext };
28
+ export { buildLocatePromptWithContext, buildPromptWithContext, renderAIContext };
24
29
 
25
30
  //# sourceMappingURL=prompt-context.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent/prompt-context.mjs","sources":["../../../src/agent/prompt-context.ts"],"sourcesContent":["import type { TUserPrompt } from '@/ai-model';\n\nexport const buildPromptWithContext = (\n prompt: TUserPrompt,\n context: string | undefined,\n): TUserPrompt => {\n const trimmedContext = context?.trim();\n if (!trimmedContext) {\n return prompt;\n }\n\n const promptText = typeof prompt === 'string' ? prompt : prompt.prompt;\n const promptWithContext = `Context for this request:\\n${trimmedContext}\\n\\n${promptText}`;\n\n if (typeof prompt === 'string') {\n return promptWithContext;\n }\n\n return {\n ...prompt,\n prompt: promptWithContext,\n };\n};\n\nexport const buildLocatePromptWithContext = (\n prompt: TUserPrompt,\n context: string | undefined,\n): TUserPrompt => {\n const trimmedContext = context?.trim();\n if (!trimmedContext) {\n return prompt;\n }\n\n const promptText = typeof prompt === 'string' ? prompt : prompt.prompt;\n const promptWithContext = `<CONTEXT>\\n${trimmedContext}\\n</CONTEXT>\\n\\n<LOCATE_TARGET>\\n${promptText}\\n</LOCATE_TARGET>`;\n\n if (typeof prompt === 'string') {\n return promptWithContext;\n }\n\n return {\n ...prompt,\n prompt: promptWithContext,\n };\n};\n"],"names":["buildPromptWithContext","prompt","context","trimmedContext","promptText","promptWithContext","buildLocatePromptWithContext"],"mappings":"AAEO,MAAMA,yBAAyB,CACpCC,QACAC;IAEA,MAAMC,iBAAiBD,SAAS;IAChC,IAAI,CAACC,gBACH,OAAOF;IAGT,MAAMG,aAAa,AAAkB,YAAlB,OAAOH,SAAsBA,SAASA,OAAO,MAAM;IACtE,MAAMI,oBAAoB,CAAC,2BAA2B,EAAEF,eAAe,IAAI,EAAEC,YAAY;IAEzF,IAAI,AAAkB,YAAlB,OAAOH,QACT,OAAOI;IAGT,OAAO;QACL,GAAGJ,MAAM;QACT,QAAQI;IACV;AACF;AAEO,MAAMC,+BAA+B,CAC1CL,QACAC;IAEA,MAAMC,iBAAiBD,SAAS;IAChC,IAAI,CAACC,gBACH,OAAOF;IAGT,MAAMG,aAAa,AAAkB,YAAlB,OAAOH,SAAsBA,SAASA,OAAO,MAAM;IACtE,MAAMI,oBAAoB,CAAC,WAAW,EAAEF,eAAe,iCAAiC,EAAEC,WAAW,kBAAkB,CAAC;IAExH,IAAI,AAAkB,YAAlB,OAAOH,QACT,OAAOI;IAGT,OAAO;QACL,GAAGJ,MAAM;QACT,QAAQI;IACV;AACF"}
1
+ {"version":3,"file":"agent/prompt-context.mjs","sources":["../../../src/agent/prompt-context.ts"],"sourcesContent":["import type { TUserPrompt } from '@/ai-model';\n\n/** Render user-provided AI guidance at the model prompt boundary. */\nexport const renderAIContext = (\n context: string | undefined,\n): string | undefined => {\n const trimmedContext = context?.trim();\n if (trimmedContext) {\n return `<CONTEXT>\\n${trimmedContext}\\n</CONTEXT>`;\n }\n\n return context === undefined ? undefined : '';\n};\n\nexport const buildPromptWithContext = (\n prompt: TUserPrompt,\n context: string | undefined,\n): TUserPrompt => {\n const renderedContext = renderAIContext(context);\n if (!renderedContext) {\n return prompt;\n }\n\n const promptText = typeof prompt === 'string' ? prompt : prompt.prompt;\n const promptWithContext = `${renderedContext}\\n\\n${promptText}`;\n\n if (typeof prompt === 'string') {\n return promptWithContext;\n }\n\n return {\n ...prompt,\n prompt: promptWithContext,\n };\n};\n\nexport const buildLocatePromptWithContext = (\n prompt: TUserPrompt,\n context: string | undefined,\n): TUserPrompt => {\n const renderedContext = renderAIContext(context);\n if (!renderedContext) {\n return prompt;\n }\n\n const promptText = typeof prompt === 'string' ? prompt : prompt.prompt;\n const promptWithContext = `${renderedContext}\\n\\n<LOCATE_TARGET>\\n${promptText}\\n</LOCATE_TARGET>`;\n\n if (typeof prompt === 'string') {\n return promptWithContext;\n }\n\n return {\n ...prompt,\n prompt: promptWithContext,\n };\n};\n"],"names":["renderAIContext","context","trimmedContext","undefined","buildPromptWithContext","prompt","renderedContext","promptText","promptWithContext","buildLocatePromptWithContext"],"mappings":"AAGO,MAAMA,kBAAkB,CAC7BC;IAEA,MAAMC,iBAAiBD,SAAS;IAChC,IAAIC,gBACF,OAAO,CAAC,WAAW,EAAEA,eAAe,YAAY,CAAC;IAGnD,OAAOD,AAAYE,WAAZF,UAAwBE,SAAY;AAC7C;AAEO,MAAMC,yBAAyB,CACpCC,QACAJ;IAEA,MAAMK,kBAAkBN,gBAAgBC;IACxC,IAAI,CAACK,iBACH,OAAOD;IAGT,MAAME,aAAa,AAAkB,YAAlB,OAAOF,SAAsBA,SAASA,OAAO,MAAM;IACtE,MAAMG,oBAAoB,GAAGF,gBAAgB,IAAI,EAAEC,YAAY;IAE/D,IAAI,AAAkB,YAAlB,OAAOF,QACT,OAAOG;IAGT,OAAO;QACL,GAAGH,MAAM;QACT,QAAQG;IACV;AACF;AAEO,MAAMC,+BAA+B,CAC1CJ,QACAJ;IAEA,MAAMK,kBAAkBN,gBAAgBC;IACxC,IAAI,CAACK,iBACH,OAAOD;IAGT,MAAME,aAAa,AAAkB,YAAlB,OAAOF,SAAsBA,SAASA,OAAO,MAAM;IACtE,MAAMG,oBAAoB,GAAGF,gBAAgB,qBAAqB,EAAEC,WAAW,kBAAkB,CAAC;IAElG,IAAI,AAAkB,YAAlB,OAAOF,QACT,OAAOG;IAGT,OAAO;QACL,GAAGH,MAAM;QACT,QAAQG;IACV;AACF"}
@@ -97,7 +97,7 @@ const runGherkinScenario = async (agent, scenarioText, opt)=>{
97
97
  const prompt = buildStepPrompt(step);
98
98
  try {
99
99
  if ('aiAct' === action) await agent.aiAct(prompt, aiActOptions);
100
- else if (opt?.context || opt?.abortSignal) await agent.aiAssert(prompt, void 0, {
100
+ else if (opt?.context !== void 0 || opt?.abortSignal) await agent.aiAssert(prompt, void 0, {
101
101
  context: opt.context,
102
102
  abortSignal: opt.abortSignal
103
103
  });
@@ -1 +1 @@
1
- {"version":3,"file":"agent/run-gherkin-scenario.mjs","sources":["../../../src/agent/run-gherkin-scenario.ts"],"sourcesContent":["import type { AiActOptions } from './agent';\n\nexport type GherkinStepKeyword = 'Given' | 'When' | 'Then' | 'And' | 'But';\n\ntype RunGherkinScenarioStepAction = 'aiAct' | 'aiAssert';\n\nexport type RunGherkinScenarioOptions = AiActOptions & {\n context?: string;\n};\n\ntype GherkinPrimaryKeyword = 'Given' | 'When' | 'Then';\n\ntype ParsedGherkinStep = {\n keyword: GherkinStepKeyword;\n effectiveKeyword: GherkinPrimaryKeyword;\n text: string;\n lineNumber: number;\n};\n\ntype RawGherkinStep = {\n keyword: GherkinStepKeyword;\n text: string;\n lineNumber: number;\n};\n\ntype ParsedGherkinScenario = {\n scenario?: string;\n steps: ParsedGherkinStep[];\n};\n\ntype GherkinScenarioAgent = {\n aiAct: (taskPrompt: string, opt?: AiActOptions) => Promise<unknown>;\n aiAssert: (\n assertion: string,\n msg?: string,\n opt?: { context?: string; abortSignal?: AbortSignal },\n ) => Promise<unknown>;\n};\n\nconst stepKeywordPattern = /^(Given|When|Then|And|But)\\s+(.+)$/i;\nconst headerPattern = /^(Scenario):\\s*(.*)$/i;\nconst unsupportedHeaderPattern =\n /^(Feature|Background|Scenario Outline|Scenario Template|Examples|Rule):/i;\n\nconst normalizeStepKeyword = (keyword: string): GherkinStepKeyword => {\n const lowerKeyword = keyword.toLowerCase();\n if (lowerKeyword === 'given') return 'Given';\n if (lowerKeyword === 'when') return 'When';\n if (lowerKeyword === 'then') return 'Then';\n if (lowerKeyword === 'and') return 'And';\n return 'But';\n};\n\nconst isPrimaryKeyword = (\n keyword: GherkinStepKeyword,\n): keyword is GherkinPrimaryKeyword => {\n return keyword === 'Given' || keyword === 'When' || keyword === 'Then';\n};\n\nconst resolveSteps = (steps: RawGherkinStep[]): ParsedGherkinStep[] => {\n let previousPrimaryKeyword: GherkinPrimaryKeyword | undefined;\n\n return steps.map((step) => {\n const effectiveKeyword = isPrimaryKeyword(step.keyword)\n ? step.keyword\n : previousPrimaryKeyword;\n\n if (!effectiveKeyword) {\n throw new Error(\n `runGherkinScenario cannot resolve \"${step.keyword}\" at line ${step.lineNumber}; use Given, When, or Then before ${step.keyword}.`,\n );\n }\n\n previousPrimaryKeyword = effectiveKeyword;\n\n return {\n ...step,\n effectiveKeyword,\n };\n });\n};\n\nconst throwIfAborted = (abortSignal: AbortSignal | undefined) => {\n if (!abortSignal?.aborted) {\n return;\n }\n\n if (typeof abortSignal.throwIfAborted === 'function') {\n abortSignal.throwIfAborted();\n }\n\n throw new Error(\n `runGherkinScenario aborted: ${abortSignal.reason || 'signal already aborted'}`,\n );\n};\n\nexport const parseGherkinScenario = (\n scenarioText: string,\n): ParsedGherkinScenario => {\n const lines = scenarioText.split(/\\r?\\n/);\n const scenarioSteps: RawGherkinStep[] = [];\n const anonymousSteps: RawGherkinStep[] = [];\n let scenario: string | undefined;\n let scenarioCount = 0;\n let section: 'prelude' | 'scenario' = 'prelude';\n\n for (const [lineIndex, rawLine] of lines.entries()) {\n const lineNumber = lineIndex + 1;\n const line = rawLine.trim();\n\n if (!line || line.startsWith('#') || line.startsWith('@')) {\n continue;\n }\n\n if (line === '\"\"\"' || line === \"'''\") {\n throw new Error(\n `runGherkinScenario does not support doc strings; found one at line ${lineNumber}.`,\n );\n }\n\n if (line.startsWith('|')) {\n throw new Error(\n `runGherkinScenario does not support data tables; found one at line ${lineNumber}.`,\n );\n }\n\n if (unsupportedHeaderPattern.test(line)) {\n throw new Error(\n `runGherkinScenario does not support \"${line}\" at line ${lineNumber}.`,\n );\n }\n\n const headerMatch = line.match(headerPattern);\n if (headerMatch) {\n scenarioCount += 1;\n scenario = headerMatch[2].trim() || undefined;\n section = 'scenario';\n continue;\n }\n\n const stepMatch = line.match(stepKeywordPattern);\n if (stepMatch) {\n const step = {\n keyword: normalizeStepKeyword(stepMatch[1]),\n text: stepMatch[2].trim(),\n lineNumber,\n };\n\n if (section === 'scenario') {\n scenarioSteps.push(step);\n } else {\n anonymousSteps.push(step);\n }\n\n continue;\n }\n\n throw new Error(\n `runGherkinScenario does not support content at line ${lineNumber}: ${line}`,\n );\n }\n\n if (scenarioCount > 1) {\n throw new Error(\n `runGherkinScenario expects exactly one Scenario, but found ${scenarioCount}.`,\n );\n }\n\n if (scenarioCount === 1 && anonymousSteps.length > 0) {\n throw new Error(\n 'runGherkinScenario cannot mix anonymous steps with a Scenario block.',\n );\n }\n\n const rawSteps = scenarioCount === 1 ? scenarioSteps : anonymousSteps;\n\n if (rawSteps.length === 0) {\n throw new Error('runGherkinScenario requires at least one Gherkin step.');\n }\n\n return {\n scenario,\n steps: resolveSteps(rawSteps),\n };\n};\n\nconst buildStepPrompt = (step: ParsedGherkinStep) => {\n if (step.effectiveKeyword === 'Given') {\n return `Set up this precondition: ${step.text}`;\n }\n\n if (step.effectiveKeyword === 'When') {\n return `Perform this user action: ${step.text}`;\n }\n\n return `Verify that ${step.text}`;\n};\n\nconst describeStepExecution = (\n step: ParsedGherkinStep,\n action: RunGherkinScenarioStepAction,\n) => {\n const keywordMapping =\n step.keyword === step.effectiveKeyword\n ? step.keyword\n : `${step.keyword} as ${step.effectiveKeyword}`;\n\n if (step.effectiveKeyword === 'Given') {\n return `setting up the precondition (${keywordMapping} -> ${action})`;\n }\n\n if (step.effectiveKeyword === 'When') {\n return `performing the user action (${keywordMapping} -> ${action})`;\n }\n\n return `verifying the expected result (${keywordMapping} -> ${action})`;\n};\n\nconst describeErrorCause = (error: unknown) => {\n if (error instanceof Error && error.message) {\n return ` Original error: ${error.message}`;\n }\n\n return '';\n};\n\nexport const runGherkinScenario = async (\n agent: GherkinScenarioAgent,\n scenarioText: string,\n opt?: RunGherkinScenarioOptions,\n): Promise<void> => {\n const parsedScenario = parseGherkinScenario(scenarioText);\n const aiActOptions: AiActOptions = {\n ...opt,\n cacheable: false,\n };\n\n for (const step of parsedScenario.steps) {\n throwIfAborted(opt?.abortSignal);\n\n const action: RunGherkinScenarioStepAction =\n step.effectiveKeyword === 'Then' ? 'aiAssert' : 'aiAct';\n const prompt = buildStepPrompt(step);\n\n try {\n if (action === 'aiAct') {\n await agent.aiAct(prompt, aiActOptions);\n } else if (opt?.context || opt?.abortSignal) {\n await agent.aiAssert(prompt, undefined, {\n context: opt.context,\n abortSignal: opt.abortSignal,\n });\n } else {\n await agent.aiAssert(prompt);\n }\n } catch (error) {\n throw new Error(\n `runGherkinScenario failed while ${describeStepExecution(\n step,\n action,\n )} at line ${step.lineNumber}: ${step.keyword} ${step.text}.${describeErrorCause(\n error,\n )}`,\n {\n cause: error,\n },\n );\n }\n }\n};\n"],"names":["stepKeywordPattern","headerPattern","unsupportedHeaderPattern","normalizeStepKeyword","keyword","lowerKeyword","isPrimaryKeyword","resolveSteps","steps","previousPrimaryKeyword","step","effectiveKeyword","Error","throwIfAborted","abortSignal","parseGherkinScenario","scenarioText","lines","scenarioSteps","anonymousSteps","scenario","scenarioCount","section","lineIndex","rawLine","lineNumber","line","headerMatch","undefined","stepMatch","rawSteps","buildStepPrompt","describeStepExecution","action","keywordMapping","describeErrorCause","error","runGherkinScenario","agent","opt","parsedScenario","aiActOptions","prompt"],"mappings":"AAuCA,MAAMA,qBAAqB;AAC3B,MAAMC,gBAAgB;AACtB,MAAMC,2BACJ;AAEF,MAAMC,uBAAuB,CAACC;IAC5B,MAAMC,eAAeD,QAAQ,WAAW;IACxC,IAAIC,AAAiB,YAAjBA,cAA0B,OAAO;IACrC,IAAIA,AAAiB,WAAjBA,cAAyB,OAAO;IACpC,IAAIA,AAAiB,WAAjBA,cAAyB,OAAO;IACpC,IAAIA,AAAiB,UAAjBA,cAAwB,OAAO;IACnC,OAAO;AACT;AAEA,MAAMC,mBAAmB,CACvBF,UAEOA,AAAY,YAAZA,WAAuBA,AAAY,WAAZA,WAAsBA,AAAY,WAAZA;AAGtD,MAAMG,eAAe,CAACC;IACpB,IAAIC;IAEJ,OAAOD,MAAM,GAAG,CAAC,CAACE;QAChB,MAAMC,mBAAmBL,iBAAiBI,KAAK,OAAO,IAClDA,KAAK,OAAO,GACZD;QAEJ,IAAI,CAACE,kBACH,MAAM,IAAIC,MACR,CAAC,mCAAmC,EAAEF,KAAK,OAAO,CAAC,UAAU,EAAEA,KAAK,UAAU,CAAC,kCAAkC,EAAEA,KAAK,OAAO,CAAC,CAAC,CAAC;QAItID,yBAAyBE;QAEzB,OAAO;YACL,GAAGD,IAAI;YACPC;QACF;IACF;AACF;AAEA,MAAME,iBAAiB,CAACC;IACtB,IAAI,CAACA,aAAa,SAChB;IAGF,IA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BAAqB,CAACC;IAC1B,IAAIA,iBAAiBxB,SAASwB,MAAM,OAAO,EACzC,OAAO,CAAC,iBAAiB,EAAEA,MAAM,OAAO,EAAE;IAG5C,OAAO;AACT;AAEO,MAAMC,qBAAqB,OAChCC,OACAtB,cACAuB;IAEA,MAAMC,iBAAiBzB,qBAAqBC;IAC5C,MAAMyB,eAA6B;QACjC,GAAGF,GAAG;QACN,WAAW;IACb;IAEA,KAAK,MAAM7B,QAAQ8B,eAAe,KAAK,CAAE;QACvC3B,eAAe0B,KAAK;QAEpB,MAAMN,SACJvB,AAA0B,WAA1BA,KAAK,gBAAgB,GAAc,aAAa;QAClD,MAAMgC,SAASX,gBAAgBrB;QAE/B,IAAI;YACF,IAAIuB,AAAW,YAAXA,QACF,MAAMK,MAAM,KAAK,CAACI,QAAQD;iBACrB,IAAIF,KAAK,WAAWA,KAAK,aAC9B,MAAMD,MAAM,QAAQ,CAACI,QAAQd,QAAW;gBACtC,SAASW,IAAI,OAAO;gBACpB,aAAaA,IAAI,WAAW;YAC9B;iBAEA,MAAMD,MAAM,QAAQ,CAACI;QAEzB,EAAE,OAAON,OAAO;YACd,MAAM,IAAIxB,MACR,CAAC,gCAAgC,EAAEoB,sBACjCtB,MACAuB,QACA,SAAS,EAAEvB,KAAK,UAAU,CAAC,EAAE,EAAEA,KAAK,OAAO,CAAC,CAAC,EAAEA,KAAK,IAAI,CAAC,CAAC,EAAEyB,mBAC5DC,QACC,EACH;gBACE,OAAOA;YACT;QAEJ;IACF;AACF"}
1
+ {"version":3,"file":"agent/run-gherkin-scenario.mjs","sources":["../../../src/agent/run-gherkin-scenario.ts"],"sourcesContent":["import type { AiActOptions } from './agent';\n\nexport type GherkinStepKeyword = 'Given' | 'When' | 'Then' | 'And' | 'But';\n\ntype RunGherkinScenarioStepAction = 'aiAct' | 'aiAssert';\n\nexport type RunGherkinScenarioOptions = AiActOptions & {\n /** Additional AI guidance applied to every step in this scenario run. */\n context?: string;\n};\n\ntype GherkinPrimaryKeyword = 'Given' | 'When' | 'Then';\n\ntype ParsedGherkinStep = {\n keyword: GherkinStepKeyword;\n effectiveKeyword: GherkinPrimaryKeyword;\n text: string;\n lineNumber: number;\n};\n\ntype RawGherkinStep = {\n keyword: GherkinStepKeyword;\n text: string;\n lineNumber: number;\n};\n\ntype ParsedGherkinScenario = {\n scenario?: string;\n steps: ParsedGherkinStep[];\n};\n\ntype GherkinScenarioAgent = {\n aiAct: (taskPrompt: string, opt?: AiActOptions) => Promise<unknown>;\n aiAssert: (\n assertion: string,\n msg?: string,\n opt?: { context?: string; abortSignal?: AbortSignal },\n ) => Promise<unknown>;\n};\n\nconst stepKeywordPattern = /^(Given|When|Then|And|But)\\s+(.+)$/i;\nconst headerPattern = /^(Scenario):\\s*(.*)$/i;\nconst unsupportedHeaderPattern =\n /^(Feature|Background|Scenario Outline|Scenario Template|Examples|Rule):/i;\n\nconst normalizeStepKeyword = (keyword: string): GherkinStepKeyword => {\n const lowerKeyword = keyword.toLowerCase();\n if (lowerKeyword === 'given') return 'Given';\n if (lowerKeyword === 'when') return 'When';\n if (lowerKeyword === 'then') return 'Then';\n if (lowerKeyword === 'and') return 'And';\n return 'But';\n};\n\nconst isPrimaryKeyword = (\n keyword: GherkinStepKeyword,\n): keyword is GherkinPrimaryKeyword => {\n return keyword === 'Given' || keyword === 'When' || keyword === 'Then';\n};\n\nconst resolveSteps = (steps: RawGherkinStep[]): ParsedGherkinStep[] => {\n let previousPrimaryKeyword: GherkinPrimaryKeyword | undefined;\n\n return steps.map((step) => {\n const effectiveKeyword = isPrimaryKeyword(step.keyword)\n ? step.keyword\n : previousPrimaryKeyword;\n\n if (!effectiveKeyword) {\n throw new Error(\n `runGherkinScenario cannot resolve \"${step.keyword}\" at line ${step.lineNumber}; use Given, When, or Then before ${step.keyword}.`,\n );\n }\n\n previousPrimaryKeyword = effectiveKeyword;\n\n return {\n ...step,\n effectiveKeyword,\n };\n });\n};\n\nconst throwIfAborted = (abortSignal: AbortSignal | undefined) => {\n if (!abortSignal?.aborted) {\n return;\n }\n\n if (typeof abortSignal.throwIfAborted === 'function') {\n abortSignal.throwIfAborted();\n }\n\n throw new Error(\n `runGherkinScenario aborted: ${abortSignal.reason || 'signal already aborted'}`,\n );\n};\n\nexport const parseGherkinScenario = (\n scenarioText: string,\n): ParsedGherkinScenario => {\n const lines = scenarioText.split(/\\r?\\n/);\n const scenarioSteps: RawGherkinStep[] = [];\n const anonymousSteps: RawGherkinStep[] = [];\n let scenario: string | undefined;\n let scenarioCount = 0;\n let section: 'prelude' | 'scenario' = 'prelude';\n\n for (const [lineIndex, rawLine] of lines.entries()) {\n const lineNumber = lineIndex + 1;\n const line = rawLine.trim();\n\n if (!line || line.startsWith('#') || line.startsWith('@')) {\n continue;\n }\n\n if (line === '\"\"\"' || line === \"'''\") {\n throw new Error(\n `runGherkinScenario does not support doc strings; found one at line ${lineNumber}.`,\n );\n }\n\n if (line.startsWith('|')) {\n throw new Error(\n `runGherkinScenario does not support data tables; found one at line ${lineNumber}.`,\n );\n }\n\n if (unsupportedHeaderPattern.test(line)) {\n throw new Error(\n `runGherkinScenario does not support \"${line}\" at line ${lineNumber}.`,\n );\n }\n\n const headerMatch = line.match(headerPattern);\n if (headerMatch) {\n scenarioCount += 1;\n scenario = headerMatch[2].trim() || undefined;\n section = 'scenario';\n continue;\n }\n\n const stepMatch = line.match(stepKeywordPattern);\n if (stepMatch) {\n const step = {\n keyword: normalizeStepKeyword(stepMatch[1]),\n text: stepMatch[2].trim(),\n lineNumber,\n };\n\n if (section === 'scenario') {\n scenarioSteps.push(step);\n } else {\n anonymousSteps.push(step);\n }\n\n continue;\n }\n\n throw new Error(\n `runGherkinScenario does not support content at line ${lineNumber}: ${line}`,\n );\n }\n\n if (scenarioCount > 1) {\n throw new Error(\n `runGherkinScenario expects exactly one Scenario, but found ${scenarioCount}.`,\n );\n }\n\n if (scenarioCount === 1 && anonymousSteps.length > 0) {\n throw new Error(\n 'runGherkinScenario cannot mix anonymous steps with a Scenario block.',\n );\n }\n\n const rawSteps = scenarioCount === 1 ? scenarioSteps : anonymousSteps;\n\n if (rawSteps.length === 0) {\n throw new Error('runGherkinScenario requires at least one Gherkin step.');\n }\n\n return {\n scenario,\n steps: resolveSteps(rawSteps),\n };\n};\n\nconst buildStepPrompt = (step: ParsedGherkinStep) => {\n if (step.effectiveKeyword === 'Given') {\n return `Set up this precondition: ${step.text}`;\n }\n\n if (step.effectiveKeyword === 'When') {\n return `Perform this user action: ${step.text}`;\n }\n\n return `Verify that ${step.text}`;\n};\n\nconst describeStepExecution = (\n step: ParsedGherkinStep,\n action: RunGherkinScenarioStepAction,\n) => {\n const keywordMapping =\n step.keyword === step.effectiveKeyword\n ? step.keyword\n : `${step.keyword} as ${step.effectiveKeyword}`;\n\n if (step.effectiveKeyword === 'Given') {\n return `setting up the precondition (${keywordMapping} -> ${action})`;\n }\n\n if (step.effectiveKeyword === 'When') {\n return `performing the user action (${keywordMapping} -> ${action})`;\n }\n\n return `verifying the expected result (${keywordMapping} -> ${action})`;\n};\n\nconst describeErrorCause = (error: unknown) => {\n if (error instanceof Error && error.message) {\n return ` Original error: ${error.message}`;\n }\n\n return '';\n};\n\nexport const runGherkinScenario = async (\n agent: GherkinScenarioAgent,\n scenarioText: string,\n opt?: RunGherkinScenarioOptions,\n): Promise<void> => {\n const parsedScenario = parseGherkinScenario(scenarioText);\n const aiActOptions: AiActOptions = {\n ...opt,\n cacheable: false,\n };\n\n for (const step of parsedScenario.steps) {\n throwIfAborted(opt?.abortSignal);\n\n const action: RunGherkinScenarioStepAction =\n step.effectiveKeyword === 'Then' ? 'aiAssert' : 'aiAct';\n const prompt = buildStepPrompt(step);\n\n try {\n if (action === 'aiAct') {\n await agent.aiAct(prompt, aiActOptions);\n } else if (opt?.context !== undefined || opt?.abortSignal) {\n await agent.aiAssert(prompt, undefined, {\n context: opt.context,\n abortSignal: opt.abortSignal,\n });\n } else {\n await agent.aiAssert(prompt);\n }\n } catch (error) {\n throw new Error(\n `runGherkinScenario failed while ${describeStepExecution(\n step,\n action,\n )} at line ${step.lineNumber}: ${step.keyword} ${step.text}.${describeErrorCause(\n error,\n )}`,\n {\n cause: error,\n },\n );\n }\n }\n};\n"],"names":["stepKeywordPattern","headerPattern","unsupportedHeaderPattern","normalizeStepKeyword","keyword","lowerKeyword","isPrimaryKeyword","resolveSteps","steps","previousPrimaryKeyword","step","effectiveKeyword","Error","throwIfAborted","abortSignal","parseGherkinScenario","scenarioText","lines","scenarioSteps","anonymousSteps","scenario","scenarioCount","section","lineIndex","rawLine","lineNumber","line","headerMatch","undefined","stepMatch","rawSteps","buildStepPrompt","describeStepExecution","action","keywordMapping","describeErrorCause","error","runGherkinScenario","agent","opt","parsedScenario","aiActOptions","prompt"],"mappings":"AAwCA,MAAMA,qBAAqB;AAC3B,MAAMC,gBAAgB;AACtB,MAAMC,2BACJ;AAEF,MAAMC,uBAAuB,CAACC;IAC5B,MAAMC,eAAeD,QAAQ,WAAW;IACxC,IAAIC,AAAiB,YAAjBA,cAA0B,OAAO;IACrC,IAAIA,AAAiB,WAAjBA,cAAyB,OAAO;IACpC,IAAIA,AAAiB,WAAjBA,cAAyB,OAAO;IACpC,IAAIA,AAAiB,UAAjBA,cAAwB,OAAO;IACnC,OAAO;AACT;AAEA,MAAMC,mBAAmB,CACvBF,UAEOA,AAAY,YAAZA,WAAuBA,AAAY,WAAZA,WAAsBA,AAAY,WAAZA;AAGtD,MAAMG,eAAe,CAACC;IACpB,IAAIC;IAEJ,OAAOD,MAAM,GAAG,CAAC,CAACE;QAChB,MAAMC,mBAAmBL,iBAAiBI,KAAK,OAAO,IAClDA,KAAK,OAAO,GACZD;QAEJ,IAAI,CAACE,kBACH,MAAM,IAAIC,MACR,CAAC,mCAAmC,EAAEF,KAAK,OAAO,CAAC,UAAU,EAAEA,KAAK,UAAU,CAAC,kCAAkC,EAAEA,KAAK,OAAO,CAAC,CAAC,CAAC;QAItID,yBAAyBE;QAEzB,OAAO;YACL,GAAGD,IAAI;YACPC;QAC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CAAC,+BAA+B,EAAEC,eAAe,IAAI,EAAED,OAAO,CAAC,CAAC;AACzE;AAEA,MAAME,qBAAqB,CAACC;IAC1B,IAAIA,iBAAiBxB,SAASwB,MAAM,OAAO,EACzC,OAAO,CAAC,iBAAiB,EAAEA,MAAM,OAAO,EAAE;IAG5C,OAAO;AACT;AAEO,MAAMC,qBAAqB,OAChCC,OACAtB,cACAuB;IAEA,MAAMC,iBAAiBzB,qBAAqBC;IAC5C,MAAMyB,eAA6B;QACjC,GAAGF,GAAG;QACN,WAAW;IACb;IAEA,KAAK,MAAM7B,QAAQ8B,eAAe,KAAK,CAAE;QACvC3B,eAAe0B,KAAK;QAEpB,MAAMN,SACJvB,AAA0B,WAA1BA,KAAK,gBAAgB,GAAc,aAAa;QAClD,MAAMgC,SAASX,gBAAgBrB;QAE/B,IAAI;YACF,IAAIuB,AAAW,YAAXA,QACF,MAAMK,MAAM,KAAK,CAACI,QAAQD;iBACrB,IAAIF,KAAK,YAAYX,UAAaW,KAAK,aAC5C,MAAMD,MAAM,QAAQ,CAACI,QAAQd,QAAW;gBACtC,SAASW,IAAI,OAAO;gBACpB,aAAaA,IAAI,WAAW;YAC9B;iBAEA,MAAMD,MAAM,QAAQ,CAACI;QAEzB,EAAE,OAAON,OAAO;YACd,MAAM,IAAIxB,MACR,CAAC,gCAAgC,EAAEoB,sBACjCtB,MACAuB,QACA,SAAS,EAAEvB,KAAK,UAAU,CAAC,EAAE,EAAEA,KAAK,OAAO,CAAC,CAAC,EAAEA,KAAK,IAAI,CAAC,CAAC,EAAEyB,mBAC5DC,QACC,EACH;gBACE,OAAOA;YACT;QAEJ;IACF;AACF"}
@@ -10,6 +10,7 @@ import { assert } from "@midscene/shared/utils";
10
10
  import { ExecutionSession } from "./execution-session.mjs";
11
11
  import { withFileChooser } from "./file-chooser.mjs";
12
12
  import { createAiActActionReporter, errorMessageForAiAct } from "./progress/index.mjs";
13
+ import { renderAIContext } from "./prompt-context.mjs";
13
14
  import { TaskBuilder, locatePlanForLocate } from "./task-builder.mjs";
14
15
  import { setTimingFieldOnce } from "../task-timing.mjs";
15
16
  import { descriptionOfTree } from "@midscene/shared/extractor";
@@ -260,7 +261,7 @@ class TaskExecutor {
260
261
  setTimingFieldOnce(timing, 'callAiStart');
261
262
  planResult = await planImpl(preparedUserPrompt, {
262
263
  context: planningUiContext,
263
- actionContext: aiActContext,
264
+ actionContext: renderAIContext(aiActContext),
264
265
  actionSpace,
265
266
  modelRuntime: planningModel,
266
267
  conversationHistory,
@@ -1 +1 @@
1
- {"version":3,"file":"agent/tasks.mjs","sources":["../../../src/agent/tasks.ts"],"sourcesContent":["import { AIResponseParseError, ConversationHistory } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { buildTypeQueryDemandValue } from '@/ai-model/prompt/insight';\nimport { prepareUserPrompt } from '@/ai-model/shared/multimodal-prompt';\nimport { standardPlan } from '@/ai-model/workflows/planning';\nimport {\n type TMultimodalPrompt,\n type TUserPrompt,\n getReadableTimeString,\n userPromptToMultimodalPrompt,\n userPromptToString,\n} from '@/common';\nimport type { AbstractInterface } from '@/device';\nimport type Service from '@/service';\nimport type {\n ExecutionReferenceImage,\n TaskRunner,\n TaskRunnerEvent,\n} from '@/task-runner';\nimport { TaskExecutionError } from '@/task-runner';\nimport type {\n AiActEffort,\n AiActProgressData,\n AiActProgressPhase,\n DetailedLocateParam,\n DeviceAction,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightQueryApply,\n ExecutionTaskPlanningApply,\n ExecutionTaskProgressOptions,\n MidsceneYamlFlowItem,\n PlanningAIResponse,\n PlanningAction,\n PlanningActionParamWaitFor,\n ServiceDump,\n ServiceExtractOption,\n ServiceExtractParam,\n UIContext,\n} from '@/types';\nimport { ServiceError, aiActProgressScope } from '@/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport { ExecutionSession } from './execution-session';\nimport { withFileChooser } from './file-chooser';\nimport {\n type AgentProgressPublisher,\n createAiActActionReporter,\n errorMessageForAiAct,\n} from './progress';\nimport { TaskBuilder } from './task-builder';\nimport type { TaskCache } from './task-cache';\nexport { locatePlanForLocate } from './task-builder';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport { descriptionOfTree } from '@midscene/shared/extractor';\nimport { type TaskTitleType, taskTitleStr } from './ui-utils';\nimport { withUsageIntent } from './usage-intent';\nimport { parsePrompt } from './utils';\n\ninterface ExecutionResult<OutputType = any> {\n output: OutputType;\n thought?: string;\n runner: TaskRunner;\n}\n\ninterface TaskExecutorHooks {\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n // Publish onto the agent's progress bus. The bus owns sequencing, so the\n // executor is a pure producer: it names the scope/phase and hands over data.\n onProgress?: AgentProgressPublisher;\n}\n\nexport type ActionReportOptions = {\n type?: TaskTitleType;\n prompt?: string;\n};\n\nconst debug = getDebug('device-task-executor');\nconst warnLog = getDebug('device-task-executor', { console: true });\nconst maxErrorCountAllowedInOnePlanningLoop = 5;\n\n// Cap each task's planning feedback so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. This is the\n// single place that truncates feedback before it is sent to the model; action\n// implementations should hand over the untruncated value.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(feedback: string): string {\n if (feedback.length <= maxPlanningFeedbackLength) {\n return feedback;\n }\n\n return `${feedback.slice(0, maxPlanningFeedbackLength)}\n...[truncated, ${feedback.length - maxPlanningFeedbackLength} more characters]`;\n}\n\nexport { TaskExecutionError };\nexport { withFileChooser } from './file-chooser';\n\nexport class TaskExecutor {\n interface: AbstractInterface;\n\n service: Service;\n\n taskCache?: TaskCache;\n\n private readonly providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\n\n replanningCycleLimit?: number;\n\n waitAfterAction?: number;\n\n useDeviceTime?: boolean;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n constructor(\n interfaceInstance: AbstractInterface,\n service: Service,\n opts: {\n taskCache?: TaskCache;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n actionSpace: DeviceAction[];\n },\n ) {\n this.interface = interfaceInstance;\n this.service = service;\n this.taskCache = opts.taskCache;\n this.onTaskStartCallback = opts?.onTaskStart;\n this.replanningCycleLimit = opts.replanningCycleLimit;\n this.waitAfterAction = opts.waitAfterAction;\n this.useDeviceTime = opts.useDeviceTime;\n this.hooks = opts.hooks;\n this.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n uiContext?: UIContext;\n referenceImages?: readonly ExecutionReferenceImage[];\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n onTaskEvent?: (event: TaskRunnerEvent) => Promise<void> | void;\n },\n ) {\n return new ExecutionSession(\n title,\n () =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn()),\n {\n onTaskStart: this.onTaskStartCallback,\n tasks: options?.tasks,\n referenceImages: options?.referenceImages,\n onSnapshotChange: async (runner, error) => {\n await this.hooks?.onSnapshotChange?.(runner, error);\n await options?.onSnapshotChange?.(runner, error);\n },\n ...(options?.onTaskEvent ? { onTaskEvent: options.onTaskEvent } : {}),\n },\n );\n }\n\n private getActionSpace(): DeviceAction[] {\n return this.providedActionSpace;\n }\n\n /**\n * Publish one event onto the agent's progress bus. The task layer is a pure\n * producer here: it names the scope/phase and forwards the structured\n * payload; the bus stamps the sequence and isolates listener errors. It has\n * no knowledge of how the event is rendered or consumed.\n */\n private async emitProgress(\n scope: string,\n phase: string,\n data: unknown,\n ): Promise<void> {\n await this.hooks?.onProgress?.(scope, phase, data);\n }\n\n /**\n * aiAct-flavored convenience over {@link emitProgress}: aiAct is the first\n * producer (\"pilot\") on the generic bus, so its events are simply tagged with\n * the `aiAct` scope.\n */\n private emitAiActProgress(\n phase: AiActProgressPhase,\n data: AiActProgressData,\n ): Promise<void> {\n return this.emitProgress(aiActProgressScope, phase, data);\n }\n\n /**\n * Set the pending feedback message consumed by the next planning round.\n * The message is always prefixed with the current time. When a body is\n * provided it is appended after the timestamp; otherwise only the time\n * context is recorded. This is the single entry point for writing\n * `pendingFeedbackMessage` so the time prefix stays consistent.\n */\n private setPendingFeedbackMessage(\n conversationHistory: ConversationHistory,\n timeString: string,\n body?: string,\n ) {\n conversationHistory.pendingFeedbackMessage = body\n ? `Time: ${timeString}, ${body}`\n : `Current time: ${timeString}`;\n }\n\n /**\n * Collect feedback produced by executed tasks for the next planning round.\n * Returns undefined when no task reported feedback.\n */\n private collectPlanningFeedback(tasks: ExecutionTask[]): string | undefined {\n const feedbackMessages = tasks.flatMap(({ planningFeedback }) =>\n planningFeedback ? [truncatePlanningFeedback(planningFeedback)] : [],\n );\n return feedbackMessages.length > 0\n ? feedbackMessages.join('\\n\\n')\n : undefined;\n }\n\n /**\n * Get a readable time string. When device time is enabled, use the\n * device-formatted wall-clock time directly so host timezone formatting does\n * not reinterpret a device timestamp.\n * @param format - Optional format string\n * @returns A formatted time string\n */\n private async getTimeString(format?: string): Promise<string> {\n if (this.useDeviceTime) {\n if (this.interface.getDeviceLocalTimeString) {\n try {\n return await this.interface.getDeviceLocalTimeString(format);\n } catch (error) {\n warnLog(\n `Failed to get device time string, falling back to runtime time: ${error}`,\n );\n }\n } else {\n warnLog(\n 'useDeviceTime is enabled but getDeviceLocalTimeString is not implemented, falling back to runtime time.',\n );\n }\n }\n\n return getReadableTimeString(format);\n }\n\n public async convertPlanToExecutable(\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, defaultModel, options);\n }\n\n async loadYamlFlowAsPlanning(\n userInstruction: TUserPrompt,\n yamlString: string,\n reportOptions?: ActionReportOptions,\n ) {\n const session = this.createExecutionSession(\n taskTitleStr(\n reportOptions?.type || 'Act',\n reportOptions?.prompt || userPromptToString(userInstruction),\n ),\n {\n referenceImages: userPromptToMultimodalPrompt(userInstruction)?.images,\n },\n );\n\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'LoadYaml',\n param: {\n userInstruction,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n return {\n output: {\n actions: [],\n shouldContinuePlanning: false,\n log: '',\n yamlString,\n },\n cache: {\n hit: true,\n },\n hitBy: {\n from: 'Cache',\n context: {\n yamlString,\n },\n },\n };\n },\n };\n const runner = session.getRunner();\n await session.appendAndRun(task);\n\n return {\n runner,\n };\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n options?: { uiContext?: UIContext },\n ): Promise<ExecutionResult> {\n const session = this.createExecutionSession(title, options);\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionDefaultModel = { ...defaultModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionDefaultModel,\n );\n const result = await session.appendAndRun(tasks);\n const { output } = result ?? {};\n return {\n output,\n runner,\n };\n }\n\n async action(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n fileChooserAccept?: string[],\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n defaultModel,\n aiActContext,\n cacheable,\n replanningCycleLimitOverride,\n effort,\n deepLocate,\n abortSignal,\n reportOptions,\n );\n });\n }\n\n /**\n * Called when the task is about to replan. Marks every cache-hit locate task\n * in the just-run batch (tasks at index >= fromIndex) as stale: that batch\n * did not finish the task, so the element each cache hit produced is suspect.\n * The upcoming re-locate of the same prompt then replaces the bad entry in\n * place instead of appending a duplicate that would re-poison the cache on the\n * next run (#2529).\n *\n * Marking a locate that was actually fine is harmless: the step is only ever\n * replaced if the same prompt is located again (i.e. the step is redone),\n * which does not happen for a locate that already succeeded.\n */\n private invalidateFailedCacheHitLocates(\n runner: TaskRunner,\n fromIndex: number,\n ) {\n if (!this.taskCache) {\n return;\n }\n for (let i = fromIndex; i < runner.tasks.length; i++) {\n const task = runner.tasks[i];\n if (\n task.type === 'Planning' &&\n task.subType === 'Locate' &&\n task.hitBy?.from === 'Cache'\n ) {\n const prompt = (task.param as DetailedLocateParam | undefined)?.prompt;\n if (prompt) {\n this.taskCache.markLocateCacheStale(prompt);\n }\n }\n }\n }\n\n private async runAction(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n const conversationHistory = new ConversationHistory();\n const promptDisplay =\n reportOptions?.prompt || userPromptToString(userPrompt);\n\n // Per-call reporter that maps the runner's native task events to aiAct\n // action progress for the action batch currently running. Kept local (not\n // on the instance) so concurrent aiAct() calls on the same executor stay\n // isolated; it is set while a planned batch runs and cleared afterwards.\n let activeActionReporter:\n | ((event: TaskRunnerEvent) => Promise<void>)\n | undefined;\n\n const session = this.createExecutionSession(\n taskTitleStr(reportOptions?.type || 'Act', promptDisplay),\n {\n referenceImages: userPromptToMultimodalPrompt(userPrompt)?.images,\n onTaskEvent: async (event) => {\n await activeActionReporter?.(event);\n },\n },\n );\n const runner = session.getRunner();\n planningModel = { ...planningModel, executionId: runner.id };\n defaultModel = { ...defaultModel, executionId: runner.id };\n\n const noIndividualLocateModel = planningModel.config.slot === 'default';\n const includeLocateInPlanning =\n effort !== 'deepThink' && noIndividualLocateModel;\n const imagesIncludeCount = effort === 'deepThink' ? 2 : 1;\n\n debug('setting includeLocateInPlanning to', includeLocateInPlanning, {\n effort,\n noIndividualLocateModel,\n });\n\n let replanCount = 0;\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n const replanningCycleLimit =\n replanningCycleLimitOverride ?? this.replanningCycleLimit;\n if (replanningCycleLimit === undefined) {\n throw new Error(\n 'replanningCycleLimit is required for TaskExecutor.action',\n );\n }\n\n await this.emitAiActProgress('start', {\n prompt: promptDisplay,\n planLimit: replanningCycleLimit,\n });\n\n const appendFailedPlan = async (\n errorMsg: string,\n planIndex?: number,\n ): Promise<{\n output: undefined;\n runner: TaskRunner;\n }> => {\n await this.emitAiActProgress('failed', {\n ...(planIndex ? { planIndex } : {}),\n planLimit: replanningCycleLimit,\n error: errorMsg,\n });\n return session.appendErrorPlan(errorMsg);\n };\n\n let errorCountInOnePlanningLoop = 0; // count the number of errors in one planning loop\n let outputString: string | undefined;\n let latestPlanResult: PlanningAIResponse | undefined;\n let latestPlanIndex = 0;\n\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n );\n }\n const getPreparedUserPrompt = (() => {\n let promise: ReturnType<typeof prepareUserPrompt> | undefined;\n\n return () => {\n promise ??= prepareUserPrompt(userPrompt);\n return promise;\n };\n })();\n\n // Main planning loop - unified plan/replan logic\n while (true) {\n const planIndex = replanCount + 1;\n latestPlanIndex = planIndex;\n\n // Check abort signal before each planning cycle\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // Get sub-goal status text if available\n const subGoalStatus = conversationHistory.subGoalsToText() || undefined;\n\n // Get memories text if available\n const memoriesStatus = conversationHistory.memoriesToText() || undefined;\n\n const result = await session.appendAndRun(\n {\n type: 'Planning',\n subType: 'Plan',\n param: {\n userInstruction: userPrompt,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n replanningCycleLimit,\n aiActContext,\n imagesIncludeCount,\n effort,\n ...(subGoalStatus ? { subGoalStatus } : {}),\n ...(memoriesStatus ? { memoriesStatus } : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n const planningUiContext = uiContext as UIContext;\n const timing = executorContext.task.timing;\n await this.emitAiActProgress('plan_thinking', {\n planIndex,\n planLimit: replanningCycleLimit,\n screenshot: planningUiContext.screenshot,\n });\n\n const actionSpace = this.getActionSpace();\n debug(\n 'actionSpace for this interface is:',\n actionSpace.map((action) => action.name).join(', '),\n );\n assert(Array.isArray(actionSpace), 'actionSpace must be an array');\n if (actionSpace.length === 0) {\n console.warn(\n `ActionSpace for ${this.interface.interfaceType} is empty. This may lead to unexpected behavior.`,\n );\n }\n\n const planImpl =\n planningModel.adapter.planning.kind === 'custom'\n ? planningModel.adapter.planning.planFn\n : standardPlan;\n\n let planResult: Awaited<ReturnType<typeof planImpl>>;\n try {\n const preparedUserPrompt = await getPreparedUserPrompt();\n\n setTimingFieldOnce(timing, 'callAiStart');\n planResult = await planImpl(preparedUserPrompt, {\n context: planningUiContext,\n actionContext: aiActContext,\n actionSpace,\n modelRuntime: planningModel,\n conversationHistory,\n includeLocateInPlanning,\n imagesIncludeCount,\n effort,\n abortSignal,\n });\n } catch (planError) {\n if (planError instanceof AIResponseParseError) {\n // Record usage and rawResponse even when parsing fails\n executorContext.task.usage = withUsageIntent(\n planError.usage,\n 'planning',\n );\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse: planError.rawResponse,\n rawChoiceMessage: planError.rawChoiceMessage,\n };\n }\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessageForAiAct(planError),\n });\n throw planError;\n } finally {\n setTimingFieldOnce(timing, 'callAiEnd');\n }\n debug('planResult', JSON.stringify(planResult, null, 2));\n\n const {\n actions,\n thought,\n log,\n memory,\n error,\n usage,\n rawResponse,\n rawChoiceMessage,\n reasoning_content,\n finalizeSuccess,\n finalizeMessage,\n updateSubGoals,\n markFinishedIndexes,\n } = planResult;\n outputString = finalizeMessage;\n\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse,\n rawChoiceMessage,\n };\n executorContext.task.usage = withUsageIntent(usage, 'planning');\n executorContext.task.reasoning_content = reasoning_content;\n executorContext.task.output = {\n actions: actions || [],\n log,\n thought,\n memory,\n yamlFlow: planResult.yamlFlow,\n output: finalizeMessage,\n shouldContinuePlanning: planResult.shouldContinuePlanning,\n updateSubGoals,\n markFinishedIndexes,\n };\n executorContext.uiContext = planningUiContext;\n\n // Forward the raw in-progress reasoning the model produced; the\n // consumer decides which field to surface and how to format it.\n // `finalizeMessage` is intentionally left for the `complete` event.\n if (log || thought) {\n await this.emitAiActProgress('plan_planned', {\n planIndex,\n planLimit: replanningCycleLimit,\n ...(log ? { log } : {}),\n ...(thought ? { thought } : {}),\n });\n }\n\n if (error) {\n const errorMessage = `Failed to continue: ${error}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n }\n\n assert(!error, `Failed to continue: ${error}\\n${log || ''}`);\n\n // Check if task was finalized with failure\n if (finalizeSuccess === false) {\n const errorMessage = `Task failed: ${finalizeMessage || 'No error message provided'}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n assert(false, errorMessage);\n }\n\n return {\n cache: {\n hit: false,\n },\n } as any;\n },\n },\n {\n allowWhenError: true,\n },\n );\n\n const planResult = result?.output as PlanningAIResponse | undefined;\n latestPlanResult = planResult;\n\n // Execute planned actions\n const plans = planResult?.actions || [];\n yamlFlow.push(...(planResult?.yamlFlow || []));\n\n let executables: Awaited<ReturnType<typeof this.convertPlanToExecutable>>;\n try {\n executables = await this.convertPlanToExecutable(\n plans,\n planningModel,\n defaultModel,\n {\n cacheable,\n deepLocate,\n abortSignal,\n },\n );\n } catch (error) {\n return appendFailedPlan(\n `Error converting plans to executable tasks: ${errorMessageForAiAct(error)}, plans: ${JSON.stringify(\n plans,\n )}`,\n planIndex,\n );\n }\n if (conversationHistory.pendingFeedbackMessage) {\n console.warn(\n 'unconsumed pending feedback message detected, this may lead to unexpected planning result:',\n conversationHistory.pendingFeedbackMessage,\n );\n }\n\n // Capture the time context for the next planning call before running.\n const initialTimeString = await this.getTimeString();\n\n const taskCountBeforeRun = runner.tasks.length;\n // Scope a reporter to this replanning round so native task events from the\n // runner are mapped to aiAct progress with the right plan context; cleared\n // in `finally` so events fired between batches are ignored.\n activeActionReporter = createAiActActionReporter(\n planIndex,\n replanningCycleLimit,\n (phase, data) => this.emitAiActProgress(phase, data),\n );\n try {\n await session.appendAndRun(executables.tasks);\n this.setPendingFeedbackMessage(\n conversationHistory,\n initialTimeString,\n this.collectPlanningFeedback(runner.tasks.slice(taskCountBeforeRun)),\n );\n } catch (error: any) {\n // errorFlag = true;\n errorCountInOnePlanningLoop++;\n const timeString = await this.getTimeString();\n this.setPendingFeedbackMessage(\n conversationHistory,\n timeString,\n `Error executing running tasks: ${error?.message || String(error)}`,\n );\n debug(\n 'error when executing running tasks, but continue to run if it is not too many errors:',\n error instanceof Error ? error.message : String(error),\n 'current error count in one planning loop:',\n errorCountInOnePlanningLoop,\n );\n } finally {\n activeActionReporter = undefined;\n }\n\n if (errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop) {\n return appendFailedPlan(\n 'Too many errors in one planning loop',\n planIndex,\n );\n }\n\n // Check abort signal after executing actions\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // // Check if task is complete\n if (!planResult?.shouldContinuePlanning) {\n break;\n }\n\n // We are about to replan, which means the batch we just ran did not finish\n // the task. Any locate task in that batch that was served from cache\n // produced an element that failed to complete the step (the action threw,\n // or it clicked the wrong element and the goal was not reached). Mark those\n // cache entries stale so the re-locate of the same prompt replaces them in\n // place instead of appending a poisoning duplicate that would be matched\n // first on the next run (#2529).\n this.invalidateFailedCacheHitLocates(runner, taskCountBeforeRun);\n\n // Increment replan count for next iteration\n ++replanCount;\n\n if (replanCount > replanningCycleLimit) {\n const errorMsg = `Replanned ${replanningCycleLimit} times, exceeding the limit. Please configure a larger value for replanningCycleLimit (or use MIDSCENE_REPLANNING_CYCLE_LIMIT) to handle more complex tasks.`;\n return appendFailedPlan(errorMsg, planIndex);\n }\n\n if (!conversationHistory.pendingFeedbackMessage) {\n const timeString = await this.getTimeString();\n conversationHistory.pendingFeedbackMessage = `Time: ${timeString}, I have finished the action previously planned.`;\n }\n }\n\n // Carry the raw final text; the consumer formats it. `outputString` is the\n // model's finalize message, with the latest plan's log/thought as fallback\n // context for consumers that want to show why the run completed.\n await this.emitAiActProgress('complete', {\n planIndex: latestPlanIndex,\n planLimit: replanningCycleLimit,\n ...((outputString ?? latestPlanResult?.output)\n ? { output: outputString ?? latestPlanResult?.output }\n : {}),\n ...(latestPlanResult?.log ? { log: latestPlanResult.log } : {}),\n ...(latestPlanResult?.thought\n ? { thought: latestPlanResult.thought }\n : {}),\n });\n\n return {\n output: {\n yamlFlow,\n output: outputString,\n },\n runner,\n };\n }\n\n private createTypeQueryTask(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert' | 'WaitFor',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n },\n ) {\n const queryTask: ExecutionTaskInsightQueryApply = {\n type: 'Insight',\n subType: type,\n param: {\n domIncluded: opt?.domIncluded,\n ...(opt?.context !== undefined ? { context: opt.context } : {}),\n dataDemand: multimodalPrompt\n ? ({\n demand,\n multimodalPrompt,\n } as never)\n : demand, // for user param presentation in report right sidebar\n },\n executor: async (taskContext) => {\n const { task } = taskContext;\n let queryDump: ServiceDump | undefined;\n const applyDump = (dump: ServiceDump) => {\n queryDump = dump;\n task.log = {\n dump,\n rawResponse: dump.taskInfo?.rawResponse,\n rawChoiceMessage: dump.taskInfo?.rawChoiceMessage,\n searchAreaRawChoiceMessage:\n dump.taskInfo?.searchAreaRawChoiceMessage,\n };\n task.usage = withUsageIntent(dump.taskInfo?.usage, 'insight');\n if (dump.taskInfo?.reasoning_content) {\n task.reasoning_content = dump.taskInfo.reasoning_content;\n }\n };\n\n // Get context for query operations\n const uiContext = taskContext.uiContext;\n assert(uiContext, 'uiContext is required for Query task');\n\n const ifTypeRestricted = type !== 'Query';\n let demandInput = demand;\n let keyOfResult = 'result';\n if (ifTypeRestricted && (type === 'Assert' || type === 'WaitFor')) {\n keyOfResult = 'StatementIsTruthy';\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n } else if (ifTypeRestricted) {\n keyOfResult = type;\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n }\n\n let extractResult;\n\n let extraPageDescription = '';\n if (opt?.domIncluded && this.interface.getElementsNodeTree) {\n debug('appending tree info for page');\n const tree = await this.interface.getElementsNodeTree();\n extraPageDescription = await descriptionOfTree(\n tree,\n 200,\n false,\n opt?.domIncluded === 'visible-only',\n );\n }\n\n try {\n extractResult = await this.service.extract<any>(\n demandInput,\n modelRuntime,\n opt,\n extraPageDescription,\n multimodalPrompt,\n uiContext,\n executionOptions,\n );\n } catch (error) {\n if (error instanceof ServiceError) {\n applyDump(error.dump);\n }\n throw error;\n } finally {\n // Surface the captured screenshot sequence in the report, then release\n // it from the UIContext so its base64 is not retained twice.\n recordAndReleaseScreenshotSequence(task, uiContext);\n }\n\n const { data, thought, dump } = extractResult;\n applyDump(dump);\n\n let outputResult = data;\n if (ifTypeRestricted) {\n // If AI returned a plain string instead of structured format, use it directly\n if (typeof data === 'string') {\n outputResult = data;\n } else if (type === 'WaitFor') {\n if (data === null || data === undefined) {\n outputResult = false;\n } else {\n outputResult = (data as any)[keyOfResult];\n }\n } else if (data === null || data === undefined) {\n outputResult = null;\n } else {\n // AI model may return {result: ...} instead of {[keyOfResult]: ...}\n if (data?.[keyOfResult] !== undefined) {\n outputResult = (data as any)[keyOfResult];\n } else if (data?.result !== undefined) {\n outputResult = (data as any).result;\n } else {\n assert(false, 'No result in query data');\n }\n }\n }\n\n // Keep assertion failures in the task result so TaskRunner can persist\n // the model dump before aiAssert turns the result into a thrown error.\n if (type === 'Assert') {\n outputResult = Boolean(outputResult);\n }\n\n return {\n output: outputResult,\n log: queryDump,\n thought,\n };\n },\n };\n\n return queryTask;\n }\n async createTypeQueryExecution<T>(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n },\n ): Promise<ExecutionResult<T>> {\n const session = this.createExecutionSession(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n {\n ...(executionOptions?.uiContext\n ? { uiContext: executionOptions.uiContext }\n : {}),\n referenceImages: multimodalPrompt?.images,\n },\n );\n\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const queryTask = await this.createTypeQueryTask(\n type,\n demand,\n executionModelRuntime,\n opt,\n multimodalPrompt,\n executionOptions,\n );\n\n const result = await session.appendAndRun(queryTask);\n\n if (!result) {\n throw new Error(\n 'result of taskExecutor.flush() is undefined in function createTypeQueryTask',\n );\n }\n\n const { output, thought } = result;\n\n return {\n output,\n thought,\n runner,\n };\n }\n\n async waitFor(\n assertion: TUserPrompt,\n opt: PlanningActionParamWaitFor,\n modelRuntime: ModelRuntime,\n ): Promise<ExecutionResult<void>> {\n const { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n\n const description = `waitFor: ${textPrompt}`;\n const session = this.createExecutionSession(\n taskTitleStr('WaitFor', description),\n { referenceImages: multimodalPrompt?.images },\n );\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const {\n timeoutMs,\n checkIntervalMs,\n domIncluded,\n screenshotIncluded,\n ...restOpt\n } = opt;\n const serviceExtractOpt: ServiceExtractOption = {\n domIncluded,\n screenshotIncluded,\n ...restOpt,\n };\n\n assert(assertion, 'No assertion for waitFor');\n assert(timeoutMs, 'No timeoutMs for waitFor');\n assert(checkIntervalMs, 'No checkIntervalMs for waitFor');\n\n assert(\n checkIntervalMs <= timeoutMs,\n `wrong config for waitFor: checkIntervalMs must be less than timeoutMs, config: {checkIntervalMs: ${checkIntervalMs}, timeoutMs: ${timeoutMs}}`,\n );\n\n const overallStartTime = Date.now();\n let lastCheckStart = overallStartTime;\n let errorThought = '';\n // Continue checking as long as the previous iteration began within the timeout window.\n while (lastCheckStart - overallStartTime <= timeoutMs) {\n const currentCheckStart = Date.now();\n lastCheckStart = currentCheckStart;\n const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\n );\n\n const result = (await session.appendAndRun(queryTask)) as\n | {\n output: boolean;\n thought?: string;\n }\n | undefined;\n\n if (result?.output) {\n return {\n output: undefined,\n runner,\n };\n }\n\n errorThought =\n result?.thought ||\n (!result && `No result from assertion: ${textPrompt}`) ||\n `unknown error when waiting for assertion: ${textPrompt}`;\n const now = Date.now();\n if (now - currentCheckStart < checkIntervalMs) {\n const elapsed = now - currentCheckStart;\n const timeRemaining = checkIntervalMs - elapsed;\n const thought = `Check interval is ${checkIntervalMs}ms, ${elapsed}ms elapsed since last check, sleeping for ${timeRemaining}ms`;\n const { tasks: sleepTasks } = await this.convertPlanToExecutable(\n [{ type: 'Sleep', param: { timeMs: timeRemaining }, thought }],\n modelRuntime,\n modelRuntime,\n );\n if (sleepTasks[0]) {\n await session.appendAndRun(sleepTasks[0]);\n }\n }\n }\n\n return session.appendErrorPlan(`waitFor timeout: ${errorThought}`);\n }\n}\n/**\n * Surface a captured screenshot sequence in the report timeline, then release\n * it from the UIContext.\n *\n * When a UIObservation insight runs, the observed frames live on\n * `uiContext.screenshotSequence` only as a transient model input. This attaches\n * them to the task recorder so the report renders the full sequence the model\n * saw (the report timeline builds one screenshot per recorder item), then drops\n * the field from the UIContext so its base64 is not retained twice for the\n * lifetime of the dump.\n *\n * The last frame is the representative `uiContext.screenshot`, already shown in\n * the report, so only the earlier frames are recorded to avoid duplication.\n * Observed frames are PREPENDED to `task.recorder` (rather than appended) so\n * array order matches chronological order — they were captured before the\n * assertion's before/after screenshots.\n */\nexport function recordAndReleaseScreenshotSequence(\n task: ExecutionTask,\n uiContext: UIContext | undefined,\n): void {\n const frames = uiContext?.screenshotSequence;\n if (frames && frames.length > 1) {\n const recorderItems: ExecutionRecorderItem[] = [];\n for (let i = 0; i < frames.length - 1; i++) {\n const frame = frames[i];\n recorderItems.push({\n type: 'screenshot',\n ts: frame.capturedAt,\n screenshot: frame,\n description: `Observed frame ${i + 1}/${frames.length}`,\n timing: 'observed-frame',\n });\n }\n // Prepend observed frames so they appear before the task's own\n // before/after screenshots in array order. Observed frames have earlier\n // timestamps than the assertion task itself, so this keeps array order\n // aligned with chronological order for consumers that iterate in-place.\n task.recorder = task.recorder\n ? [...recorderItems, ...task.recorder]\n : recorderItems;\n }\n if (uiContext?.screenshotSequence) {\n uiContext.screenshotSequence = undefined;\n }\n}\n"],"names":["debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","TaskExecutor","title","options","ExecutionSession","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","undefined","format","getReadableTimeString","plans","planningModel","defaultModel","userInstruction","yamlString","reportOptions","session","taskTitleStr","userPromptToString","userPromptToMultimodalPrompt","task","executorContext","uiContext","assert","executionPlanningModel","executionDefaultModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","abortSignal","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","noIndividualLocateModel","includeLocateInPlanning","imagesIncludeCount","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","getPreparedUserPrompt","promise","prepareUserPrompt","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","action","Array","console","planImpl","standardPlan","planResult","preparedUserPrompt","setTimingFieldOnce","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","JSON","actions","thought","log","memory","usage","rawResponse","rawChoiceMessage","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","String","type","demand","modelRuntime","opt","multimodalPrompt","executionOptions","queryTask","taskContext","queryDump","applyDump","dump","ifTypeRestricted","demandInput","keyOfResult","buildTypeQueryDemandValue","extractResult","extraPageDescription","tree","descriptionOfTree","ServiceError","recordAndReleaseScreenshotSequence","outputResult","Boolean","executionModelRuntime","assertion","textPrompt","parsePrompt","description","timeoutMs","checkIntervalMs","domIncluded","screenshotIncluded","restOpt","serviceExtractOpt","overallStartTime","Date","lastCheckStart","errorThought","currentCheckStart","now","elapsed","timeRemaining","sleepTasks","interfaceInstance","service","opts","TaskBuilder","frames","recorderItems","frame"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,UAAUD,SAAS,wBAAwB;IAAE,SAAS;AAAK;AACjE,MAAME,wCAAwC;AAM9C,MAAMC,4BAA4B;AAElC,SAASC,yBAAyBC,QAAgB;IAChD,IAAIA,SAAS,MAAM,IAAIF,2BACrB,OAAOE;IAGT,OAAO,GAAGA,SAAS,KAAK,CAAC,GAAGF,2BAA2B;eAC1C,EAAEE,SAAS,MAAM,GAAGF,0BAA0B,iBAAiB,CAAC;AAC/E;AAKO,MAAMG;IAsBX,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,SAAS;IACvB;IAiCQ,uBACNC,KAAa,EACbC,OASC,EACD;QACA,OAAO,IAAIC,iBACTF,OACA,IACEC,SAAS,YACLE,QAAQ,OAAO,CAACF,QAAQ,SAAS,IACjCE,QAAQ,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,kBAAkB,KACrD;YACE,aAAa,IAAI,CAAC,mBAAmB;YACrC,OAAOF,SAAS;YAChB,iBAAiBA,SAAS;YAC1B,kBAAkB,OAAOG,QAAQC;gBAC/B,MAAM,IAAI,CAAC,KAAK,EAAE,mBAAmBD,QAAQC;gBAC7C,MAAMJ,SAAS,mBAAmBG,QAAQC;YAC5C;YACA,GAAIJ,SAAS,cAAc;gBAAE,aAAaA,QAAQ,WAAW;YAAC,IAAI,CAAC,CAAC;QACtE;IAEJ;IAEQ,iBAAiC;QACvC,OAAO,IAAI,CAAC,mBAAmB;IACjC;IAQA,MAAc,aACZK,KAAa,EACbC,KAAa,EACbC,IAAa,EACE;QACf,MAAM,I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AAM,EAAE;gBACvD,QAAQ;YACV;QACF;QAKA5H,KAAK,QAAQ,GAAGA,KAAK,QAAQ,GACzB;eAAI6H;eAAkB7H,KAAK,QAAQ;SAAC,GACpC6H;IACN;IACA,IAAI3H,WAAW,oBACbA,UAAU,kBAAkB,GAAGf;AAEnC"}
1
+ {"version":3,"file":"agent/tasks.mjs","sources":["../../../src/agent/tasks.ts"],"sourcesContent":["import { AIResponseParseError, ConversationHistory } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { buildTypeQueryDemandValue } from '@/ai-model/prompt/insight';\nimport { prepareUserPrompt } from '@/ai-model/shared/multimodal-prompt';\nimport { standardPlan } from '@/ai-model/workflows/planning';\nimport {\n type TMultimodalPrompt,\n type TUserPrompt,\n getReadableTimeString,\n userPromptToMultimodalPrompt,\n userPromptToString,\n} from '@/common';\nimport type { AbstractInterface } from '@/device';\nimport type Service from '@/service';\nimport type {\n ExecutionReferenceImage,\n TaskRunner,\n TaskRunnerEvent,\n} from '@/task-runner';\nimport { TaskExecutionError } from '@/task-runner';\nimport type {\n AiActEffort,\n AiActProgressData,\n AiActProgressPhase,\n DetailedLocateParam,\n DeviceAction,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightQueryApply,\n ExecutionTaskPlanningApply,\n ExecutionTaskProgressOptions,\n MidsceneYamlFlowItem,\n PlanningAIResponse,\n PlanningAction,\n PlanningActionParamWaitFor,\n ServiceDump,\n ServiceExtractOption,\n ServiceExtractParam,\n UIContext,\n} from '@/types';\nimport { ServiceError, aiActProgressScope } from '@/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport { ExecutionSession } from './execution-session';\nimport { withFileChooser } from './file-chooser';\nimport {\n type AgentProgressPublisher,\n createAiActActionReporter,\n errorMessageForAiAct,\n} from './progress';\nimport { renderAIContext } from './prompt-context';\nimport { TaskBuilder } from './task-builder';\nimport type { TaskCache } from './task-cache';\nexport { locatePlanForLocate } from './task-builder';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport { descriptionOfTree } from '@midscene/shared/extractor';\nimport { type TaskTitleType, taskTitleStr } from './ui-utils';\nimport { withUsageIntent } from './usage-intent';\nimport { parsePrompt } from './utils';\n\ninterface ExecutionResult<OutputType = any> {\n output: OutputType;\n thought?: string;\n runner: TaskRunner;\n}\n\ninterface TaskExecutorHooks {\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n // Publish onto the agent's progress bus. The bus owns sequencing, so the\n // executor is a pure producer: it names the scope/phase and hands over data.\n onProgress?: AgentProgressPublisher;\n}\n\nexport type ActionReportOptions = {\n type?: TaskTitleType;\n prompt?: string;\n};\n\nconst debug = getDebug('device-task-executor');\nconst warnLog = getDebug('device-task-executor', { console: true });\nconst maxErrorCountAllowedInOnePlanningLoop = 5;\n\n// Cap each task's planning feedback so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. This is the\n// single place that truncates feedback before it is sent to the model; action\n// implementations should hand over the untruncated value.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(feedback: string): string {\n if (feedback.length <= maxPlanningFeedbackLength) {\n return feedback;\n }\n\n return `${feedback.slice(0, maxPlanningFeedbackLength)}\n...[truncated, ${feedback.length - maxPlanningFeedbackLength} more characters]`;\n}\n\nexport { TaskExecutionError };\nexport { withFileChooser } from './file-chooser';\n\nexport class TaskExecutor {\n interface: AbstractInterface;\n\n service: Service;\n\n taskCache?: TaskCache;\n\n private readonly providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\n\n replanningCycleLimit?: number;\n\n waitAfterAction?: number;\n\n useDeviceTime?: boolean;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n constructor(\n interfaceInstance: AbstractInterface,\n service: Service,\n opts: {\n taskCache?: TaskCache;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n actionSpace: DeviceAction[];\n },\n ) {\n this.interface = interfaceInstance;\n this.service = service;\n this.taskCache = opts.taskCache;\n this.onTaskStartCallback = opts?.onTaskStart;\n this.replanningCycleLimit = opts.replanningCycleLimit;\n this.waitAfterAction = opts.waitAfterAction;\n this.useDeviceTime = opts.useDeviceTime;\n this.hooks = opts.hooks;\n this.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n uiContext?: UIContext;\n referenceImages?: readonly ExecutionReferenceImage[];\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n onTaskEvent?: (event: TaskRunnerEvent) => Promise<void> | void;\n },\n ) {\n return new ExecutionSession(\n title,\n () =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn()),\n {\n onTaskStart: this.onTaskStartCallback,\n tasks: options?.tasks,\n referenceImages: options?.referenceImages,\n onSnapshotChange: async (runner, error) => {\n await this.hooks?.onSnapshotChange?.(runner, error);\n await options?.onSnapshotChange?.(runner, error);\n },\n ...(options?.onTaskEvent ? { onTaskEvent: options.onTaskEvent } : {}),\n },\n );\n }\n\n private getActionSpace(): DeviceAction[] {\n return this.providedActionSpace;\n }\n\n /**\n * Publish one event onto the agent's progress bus. The task layer is a pure\n * producer here: it names the scope/phase and forwards the structured\n * payload; the bus stamps the sequence and isolates listener errors. It has\n * no knowledge of how the event is rendered or consumed.\n */\n private async emitProgress(\n scope: string,\n phase: string,\n data: unknown,\n ): Promise<void> {\n await this.hooks?.onProgress?.(scope, phase, data);\n }\n\n /**\n * aiAct-flavored convenience over {@link emitProgress}: aiAct is the first\n * producer (\"pilot\") on the generic bus, so its events are simply tagged with\n * the `aiAct` scope.\n */\n private emitAiActProgress(\n phase: AiActProgressPhase,\n data: AiActProgressData,\n ): Promise<void> {\n return this.emitProgress(aiActProgressScope, phase, data);\n }\n\n /**\n * Set the pending feedback message consumed by the next planning round.\n * The message is always prefixed with the current time. When a body is\n * provided it is appended after the timestamp; otherwise only the time\n * context is recorded. This is the single entry point for writing\n * `pendingFeedbackMessage` so the time prefix stays consistent.\n */\n private setPendingFeedbackMessage(\n conversationHistory: ConversationHistory,\n timeString: string,\n body?: string,\n ) {\n conversationHistory.pendingFeedbackMessage = body\n ? `Time: ${timeString}, ${body}`\n : `Current time: ${timeString}`;\n }\n\n /**\n * Collect feedback produced by executed tasks for the next planning round.\n * Returns undefined when no task reported feedback.\n */\n private collectPlanningFeedback(tasks: ExecutionTask[]): string | undefined {\n const feedbackMessages = tasks.flatMap(({ planningFeedback }) =>\n planningFeedback ? [truncatePlanningFeedback(planningFeedback)] : [],\n );\n return feedbackMessages.length > 0\n ? feedbackMessages.join('\\n\\n')\n : undefined;\n }\n\n /**\n * Get a readable time string. When device time is enabled, use the\n * device-formatted wall-clock time directly so host timezone formatting does\n * not reinterpret a device timestamp.\n * @param format - Optional format string\n * @returns A formatted time string\n */\n private async getTimeString(format?: string): Promise<string> {\n if (this.useDeviceTime) {\n if (this.interface.getDeviceLocalTimeString) {\n try {\n return await this.interface.getDeviceLocalTimeString(format);\n } catch (error) {\n warnLog(\n `Failed to get device time string, falling back to runtime time: ${error}`,\n );\n }\n } else {\n warnLog(\n 'useDeviceTime is enabled but getDeviceLocalTimeString is not implemented, falling back to runtime time.',\n );\n }\n }\n\n return getReadableTimeString(format);\n }\n\n public async convertPlanToExecutable(\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, defaultModel, options);\n }\n\n async loadYamlFlowAsPlanning(\n userInstruction: TUserPrompt,\n yamlString: string,\n reportOptions?: ActionReportOptions,\n ) {\n const session = this.createExecutionSession(\n taskTitleStr(\n reportOptions?.type || 'Act',\n reportOptions?.prompt || userPromptToString(userInstruction),\n ),\n {\n referenceImages: userPromptToMultimodalPrompt(userInstruction)?.images,\n },\n );\n\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'LoadYaml',\n param: {\n userInstruction,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n return {\n output: {\n actions: [],\n shouldContinuePlanning: false,\n log: '',\n yamlString,\n },\n cache: {\n hit: true,\n },\n hitBy: {\n from: 'Cache',\n context: {\n yamlString,\n },\n },\n };\n },\n };\n const runner = session.getRunner();\n await session.appendAndRun(task);\n\n return {\n runner,\n };\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n options?: { uiContext?: UIContext },\n ): Promise<ExecutionResult> {\n const session = this.createExecutionSession(title, options);\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionDefaultModel = { ...defaultModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionDefaultModel,\n );\n const result = await session.appendAndRun(tasks);\n const { output } = result ?? {};\n return {\n output,\n runner,\n };\n }\n\n async action(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n fileChooserAccept?: string[],\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n defaultModel,\n aiActContext,\n cacheable,\n replanningCycleLimitOverride,\n effort,\n deepLocate,\n abortSignal,\n reportOptions,\n );\n });\n }\n\n /**\n * Called when the task is about to replan. Marks every cache-hit locate task\n * in the just-run batch (tasks at index >= fromIndex) as stale: that batch\n * did not finish the task, so the element each cache hit produced is suspect.\n * The upcoming re-locate of the same prompt then replaces the bad entry in\n * place instead of appending a duplicate that would re-poison the cache on the\n * next run (#2529).\n *\n * Marking a locate that was actually fine is harmless: the step is only ever\n * replaced if the same prompt is located again (i.e. the step is redone),\n * which does not happen for a locate that already succeeded.\n */\n private invalidateFailedCacheHitLocates(\n runner: TaskRunner,\n fromIndex: number,\n ) {\n if (!this.taskCache) {\n return;\n }\n for (let i = fromIndex; i < runner.tasks.length; i++) {\n const task = runner.tasks[i];\n if (\n task.type === 'Planning' &&\n task.subType === 'Locate' &&\n task.hitBy?.from === 'Cache'\n ) {\n const prompt = (task.param as DetailedLocateParam | undefined)?.prompt;\n if (prompt) {\n this.taskCache.markLocateCacheStale(prompt);\n }\n }\n }\n }\n\n private async runAction(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n defaultModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n const conversationHistory = new ConversationHistory();\n const promptDisplay =\n reportOptions?.prompt || userPromptToString(userPrompt);\n\n // Per-call reporter that maps the runner's native task events to aiAct\n // action progress for the action batch currently running. Kept local (not\n // on the instance) so concurrent aiAct() calls on the same executor stay\n // isolated; it is set while a planned batch runs and cleared afterwards.\n let activeActionReporter:\n | ((event: TaskRunnerEvent) => Promise<void>)\n | undefined;\n\n const session = this.createExecutionSession(\n taskTitleStr(reportOptions?.type || 'Act', promptDisplay),\n {\n referenceImages: userPromptToMultimodalPrompt(userPrompt)?.images,\n onTaskEvent: async (event) => {\n await activeActionReporter?.(event);\n },\n },\n );\n const runner = session.getRunner();\n planningModel = { ...planningModel, executionId: runner.id };\n defaultModel = { ...defaultModel, executionId: runner.id };\n\n const noIndividualLocateModel = planningModel.config.slot === 'default';\n const includeLocateInPlanning =\n effort !== 'deepThink' && noIndividualLocateModel;\n const imagesIncludeCount = effort === 'deepThink' ? 2 : 1;\n\n debug('setting includeLocateInPlanning to', includeLocateInPlanning, {\n effort,\n noIndividualLocateModel,\n });\n\n let replanCount = 0;\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n const replanningCycleLimit =\n replanningCycleLimitOverride ?? this.replanningCycleLimit;\n if (replanningCycleLimit === undefined) {\n throw new Error(\n 'replanningCycleLimit is required for TaskExecutor.action',\n );\n }\n\n await this.emitAiActProgress('start', {\n prompt: promptDisplay,\n planLimit: replanningCycleLimit,\n });\n\n const appendFailedPlan = async (\n errorMsg: string,\n planIndex?: number,\n ): Promise<{\n output: undefined;\n runner: TaskRunner;\n }> => {\n await this.emitAiActProgress('failed', {\n ...(planIndex ? { planIndex } : {}),\n planLimit: replanningCycleLimit,\n error: errorMsg,\n });\n return session.appendErrorPlan(errorMsg);\n };\n\n let errorCountInOnePlanningLoop = 0; // count the number of errors in one planning loop\n let outputString: string | undefined;\n let latestPlanResult: PlanningAIResponse | undefined;\n let latestPlanIndex = 0;\n\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n );\n }\n const getPreparedUserPrompt = (() => {\n let promise: ReturnType<typeof prepareUserPrompt> | undefined;\n\n return () => {\n promise ??= prepareUserPrompt(userPrompt);\n return promise;\n };\n })();\n\n // Main planning loop - unified plan/replan logic\n while (true) {\n const planIndex = replanCount + 1;\n latestPlanIndex = planIndex;\n\n // Check abort signal before each planning cycle\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // Get sub-goal status text if available\n const subGoalStatus = conversationHistory.subGoalsToText() || undefined;\n\n // Get memories text if available\n const memoriesStatus = conversationHistory.memoriesToText() || undefined;\n\n const result = await session.appendAndRun(\n {\n type: 'Planning',\n subType: 'Plan',\n param: {\n userInstruction: userPrompt,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n replanningCycleLimit,\n aiActContext,\n imagesIncludeCount,\n effort,\n ...(subGoalStatus ? { subGoalStatus } : {}),\n ...(memoriesStatus ? { memoriesStatus } : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n const planningUiContext = uiContext as UIContext;\n const timing = executorContext.task.timing;\n await this.emitAiActProgress('plan_thinking', {\n planIndex,\n planLimit: replanningCycleLimit,\n screenshot: planningUiContext.screenshot,\n });\n\n const actionSpace = this.getActionSpace();\n debug(\n 'actionSpace for this interface is:',\n actionSpace.map((action) => action.name).join(', '),\n );\n assert(Array.isArray(actionSpace), 'actionSpace must be an array');\n if (actionSpace.length === 0) {\n console.warn(\n `ActionSpace for ${this.interface.interfaceType} is empty. This may lead to unexpected behavior.`,\n );\n }\n\n const planImpl =\n planningModel.adapter.planning.kind === 'custom'\n ? planningModel.adapter.planning.planFn\n : standardPlan;\n\n let planResult: Awaited<ReturnType<typeof planImpl>>;\n try {\n const preparedUserPrompt = await getPreparedUserPrompt();\n\n setTimingFieldOnce(timing, 'callAiStart');\n planResult = await planImpl(preparedUserPrompt, {\n context: planningUiContext,\n actionContext: renderAIContext(aiActContext),\n actionSpace,\n modelRuntime: planningModel,\n conversationHistory,\n includeLocateInPlanning,\n imagesIncludeCount,\n effort,\n abortSignal,\n });\n } catch (planError) {\n if (planError instanceof AIResponseParseError) {\n // Record usage and rawResponse even when parsing fails\n executorContext.task.usage = withUsageIntent(\n planError.usage,\n 'planning',\n );\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse: planError.rawResponse,\n rawChoiceMessage: planError.rawChoiceMessage,\n };\n }\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessageForAiAct(planError),\n });\n throw planError;\n } finally {\n setTimingFieldOnce(timing, 'callAiEnd');\n }\n debug('planResult', JSON.stringify(planResult, null, 2));\n\n const {\n actions,\n thought,\n log,\n memory,\n error,\n usage,\n rawResponse,\n rawChoiceMessage,\n reasoning_content,\n finalizeSuccess,\n finalizeMessage,\n updateSubGoals,\n markFinishedIndexes,\n } = planResult;\n outputString = finalizeMessage;\n\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse,\n rawChoiceMessage,\n };\n executorContext.task.usage = withUsageIntent(usage, 'planning');\n executorContext.task.reasoning_content = reasoning_content;\n executorContext.task.output = {\n actions: actions || [],\n log,\n thought,\n memory,\n yamlFlow: planResult.yamlFlow,\n output: finalizeMessage,\n shouldContinuePlanning: planResult.shouldContinuePlanning,\n updateSubGoals,\n markFinishedIndexes,\n };\n executorContext.uiContext = planningUiContext;\n\n // Forward the raw in-progress reasoning the model produced; the\n // consumer decides which field to surface and how to format it.\n // `finalizeMessage` is intentionally left for the `complete` event.\n if (log || thought) {\n await this.emitAiActProgress('plan_planned', {\n planIndex,\n planLimit: replanningCycleLimit,\n ...(log ? { log } : {}),\n ...(thought ? { thought } : {}),\n });\n }\n\n if (error) {\n const errorMessage = `Failed to continue: ${error}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n }\n\n assert(!error, `Failed to continue: ${error}\\n${log || ''}`);\n\n // Check if task was finalized with failure\n if (finalizeSuccess === false) {\n const errorMessage = `Task failed: ${finalizeMessage || 'No error message provided'}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n assert(false, errorMessage);\n }\n\n return {\n cache: {\n hit: false,\n },\n } as any;\n },\n },\n {\n allowWhenError: true,\n },\n );\n\n const planResult = result?.output as PlanningAIResponse | undefined;\n latestPlanResult = planResult;\n\n // Execute planned actions\n const plans = planResult?.actions || [];\n yamlFlow.push(...(planResult?.yamlFlow || []));\n\n let executables: Awaited<ReturnType<typeof this.convertPlanToExecutable>>;\n try {\n executables = await this.convertPlanToExecutable(\n plans,\n planningModel,\n defaultModel,\n {\n cacheable,\n deepLocate,\n abortSignal,\n },\n );\n } catch (error) {\n return appendFailedPlan(\n `Error converting plans to executable tasks: ${errorMessageForAiAct(error)}, plans: ${JSON.stringify(\n plans,\n )}`,\n planIndex,\n );\n }\n if (conversationHistory.pendingFeedbackMessage) {\n console.warn(\n 'unconsumed pending feedback message detected, this may lead to unexpected planning result:',\n conversationHistory.pendingFeedbackMessage,\n );\n }\n\n // Capture the time context for the next planning call before running.\n const initialTimeString = await this.getTimeString();\n\n const taskCountBeforeRun = runner.tasks.length;\n // Scope a reporter to this replanning round so native task events from the\n // runner are mapped to aiAct progress with the right plan context; cleared\n // in `finally` so events fired between batches are ignored.\n activeActionReporter = createAiActActionReporter(\n planIndex,\n replanningCycleLimit,\n (phase, data) => this.emitAiActProgress(phase, data),\n );\n try {\n await session.appendAndRun(executables.tasks);\n this.setPendingFeedbackMessage(\n conversationHistory,\n initialTimeString,\n this.collectPlanningFeedback(runner.tasks.slice(taskCountBeforeRun)),\n );\n } catch (error: any) {\n // errorFlag = true;\n errorCountInOnePlanningLoop++;\n const timeString = await this.getTimeString();\n this.setPendingFeedbackMessage(\n conversationHistory,\n timeString,\n `Error executing running tasks: ${error?.message || String(error)}`,\n );\n debug(\n 'error when executing running tasks, but continue to run if it is not too many errors:',\n error instanceof Error ? error.message : String(error),\n 'current error count in one planning loop:',\n errorCountInOnePlanningLoop,\n );\n } finally {\n activeActionReporter = undefined;\n }\n\n if (errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop) {\n return appendFailedPlan(\n 'Too many errors in one planning loop',\n planIndex,\n );\n }\n\n // Check abort signal after executing actions\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // // Check if task is complete\n if (!planResult?.shouldContinuePlanning) {\n break;\n }\n\n // We are about to replan, which means the batch we just ran did not finish\n // the task. Any locate task in that batch that was served from cache\n // produced an element that failed to complete the step (the action threw,\n // or it clicked the wrong element and the goal was not reached). Mark those\n // cache entries stale so the re-locate of the same prompt replaces them in\n // place instead of appending a poisoning duplicate that would be matched\n // first on the next run (#2529).\n this.invalidateFailedCacheHitLocates(runner, taskCountBeforeRun);\n\n // Increment replan count for next iteration\n ++replanCount;\n\n if (replanCount > replanningCycleLimit) {\n const errorMsg = `Replanned ${replanningCycleLimit} times, exceeding the limit. Please configure a larger value for replanningCycleLimit (or use MIDSCENE_REPLANNING_CYCLE_LIMIT) to handle more complex tasks.`;\n return appendFailedPlan(errorMsg, planIndex);\n }\n\n if (!conversationHistory.pendingFeedbackMessage) {\n const timeString = await this.getTimeString();\n conversationHistory.pendingFeedbackMessage = `Time: ${timeString}, I have finished the action previously planned.`;\n }\n }\n\n // Carry the raw final text; the consumer formats it. `outputString` is the\n // model's finalize message, with the latest plan's log/thought as fallback\n // context for consumers that want to show why the run completed.\n await this.emitAiActProgress('complete', {\n planIndex: latestPlanIndex,\n planLimit: replanningCycleLimit,\n ...((outputString ?? latestPlanResult?.output)\n ? { output: outputString ?? latestPlanResult?.output }\n : {}),\n ...(latestPlanResult?.log ? { log: latestPlanResult.log } : {}),\n ...(latestPlanResult?.thought\n ? { thought: latestPlanResult.thought }\n : {}),\n });\n\n return {\n output: {\n yamlFlow,\n output: outputString,\n },\n runner,\n };\n }\n\n private createTypeQueryTask(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert' | 'WaitFor',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n },\n ) {\n const queryTask: ExecutionTaskInsightQueryApply = {\n type: 'Insight',\n subType: type,\n param: {\n domIncluded: opt?.domIncluded,\n ...(opt?.context !== undefined ? { context: opt.context } : {}),\n dataDemand: multimodalPrompt\n ? ({\n demand,\n multimodalPrompt,\n } as never)\n : demand, // for user param presentation in report right sidebar\n },\n executor: async (taskContext) => {\n const { task } = taskContext;\n let queryDump: ServiceDump | undefined;\n const applyDump = (dump: ServiceDump) => {\n queryDump = dump;\n task.log = {\n dump,\n rawResponse: dump.taskInfo?.rawResponse,\n rawChoiceMessage: dump.taskInfo?.rawChoiceMessage,\n searchAreaRawChoiceMessage:\n dump.taskInfo?.searchAreaRawChoiceMessage,\n };\n task.usage = withUsageIntent(dump.taskInfo?.usage, 'insight');\n if (dump.taskInfo?.reasoning_content) {\n task.reasoning_content = dump.taskInfo.reasoning_content;\n }\n };\n\n // Get context for query operations\n const uiContext = taskContext.uiContext;\n assert(uiContext, 'uiContext is required for Query task');\n\n const ifTypeRestricted = type !== 'Query';\n let demandInput = demand;\n let keyOfResult = 'result';\n if (ifTypeRestricted && (type === 'Assert' || type === 'WaitFor')) {\n keyOfResult = 'StatementIsTruthy';\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n } else if (ifTypeRestricted) {\n keyOfResult = type;\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n }\n\n let extractResult;\n\n let extraPageDescription = '';\n if (opt?.domIncluded && this.interface.getElementsNodeTree) {\n debug('appending tree info for page');\n const tree = await this.interface.getElementsNodeTree();\n extraPageDescription = await descriptionOfTree(\n tree,\n 200,\n false,\n opt?.domIncluded === 'visible-only',\n );\n }\n\n try {\n extractResult = await this.service.extract<any>(\n demandInput,\n modelRuntime,\n opt,\n extraPageDescription,\n multimodalPrompt,\n uiContext,\n executionOptions,\n );\n } catch (error) {\n if (error instanceof ServiceError) {\n applyDump(error.dump);\n }\n throw error;\n } finally {\n // Surface the captured screenshot sequence in the report, then release\n // it from the UIContext so its base64 is not retained twice.\n recordAndReleaseScreenshotSequence(task, uiContext);\n }\n\n const { data, thought, dump } = extractResult;\n applyDump(dump);\n\n let outputResult = data;\n if (ifTypeRestricted) {\n // If AI returned a plain string instead of structured format, use it directly\n if (typeof data === 'string') {\n outputResult = data;\n } else if (type === 'WaitFor') {\n if (data === null || data === undefined) {\n outputResult = false;\n } else {\n outputResult = (data as any)[keyOfResult];\n }\n } else if (data === null || data === undefined) {\n outputResult = null;\n } else {\n // AI model may return {result: ...} instead of {[keyOfResult]: ...}\n if (data?.[keyOfResult] !== undefined) {\n outputResult = (data as any)[keyOfResult];\n } else if (data?.result !== undefined) {\n outputResult = (data as any).result;\n } else {\n assert(false, 'No result in query data');\n }\n }\n }\n\n // Keep assertion failures in the task result so TaskRunner can persist\n // the model dump before aiAssert turns the result into a thrown error.\n if (type === 'Assert') {\n outputResult = Boolean(outputResult);\n }\n\n return {\n output: outputResult,\n log: queryDump,\n thought,\n };\n },\n };\n\n return queryTask;\n }\n async createTypeQueryExecution<T>(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n },\n ): Promise<ExecutionResult<T>> {\n const session = this.createExecutionSession(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n {\n ...(executionOptions?.uiContext\n ? { uiContext: executionOptions.uiContext }\n : {}),\n referenceImages: multimodalPrompt?.images,\n },\n );\n\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const queryTask = await this.createTypeQueryTask(\n type,\n demand,\n executionModelRuntime,\n opt,\n multimodalPrompt,\n executionOptions,\n );\n\n const result = await session.appendAndRun(queryTask);\n\n if (!result) {\n throw new Error(\n 'result of taskExecutor.flush() is undefined in function createTypeQueryTask',\n );\n }\n\n const { output, thought } = result;\n\n return {\n output,\n thought,\n runner,\n };\n }\n\n async waitFor(\n assertion: TUserPrompt,\n opt: PlanningActionParamWaitFor,\n modelRuntime: ModelRuntime,\n ): Promise<ExecutionResult<void>> {\n const { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n\n const description = `waitFor: ${textPrompt}`;\n const session = this.createExecutionSession(\n taskTitleStr('WaitFor', description),\n { referenceImages: multimodalPrompt?.images },\n );\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const {\n timeoutMs,\n checkIntervalMs,\n domIncluded,\n screenshotIncluded,\n ...restOpt\n } = opt;\n const serviceExtractOpt: ServiceExtractOption = {\n domIncluded,\n screenshotIncluded,\n ...restOpt,\n };\n\n assert(assertion, 'No assertion for waitFor');\n assert(timeoutMs, 'No timeoutMs for waitFor');\n assert(checkIntervalMs, 'No checkIntervalMs for waitFor');\n\n assert(\n checkIntervalMs <= timeoutMs,\n `wrong config for waitFor: checkIntervalMs must be less than timeoutMs, config: {checkIntervalMs: ${checkIntervalMs}, timeoutMs: ${timeoutMs}}`,\n );\n\n const overallStartTime = Date.now();\n let lastCheckStart = overallStartTime;\n let errorThought = '';\n // Continue checking as long as the previous iteration began within the timeout window.\n while (lastCheckStart - overallStartTime <= timeoutMs) {\n const currentCheckStart = Date.now();\n lastCheckStart = currentCheckStart;\n const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\n );\n\n const result = (await session.appendAndRun(queryTask)) as\n | {\n output: boolean;\n thought?: string;\n }\n | undefined;\n\n if (result?.output) {\n return {\n output: undefined,\n runner,\n };\n }\n\n errorThought =\n result?.thought ||\n (!result && `No result from assertion: ${textPrompt}`) ||\n `unknown error when waiting for assertion: ${textPrompt}`;\n const now = Date.now();\n if (now - currentCheckStart < checkIntervalMs) {\n const elapsed = now - currentCheckStart;\n const timeRemaining = checkIntervalMs - elapsed;\n const thought = `Check interval is ${checkIntervalMs}ms, ${elapsed}ms elapsed since last check, sleeping for ${timeRemaining}ms`;\n const { tasks: sleepTasks } = await this.convertPlanToExecutable(\n [{ type: 'Sleep', param: { timeMs: timeRemaining }, thought }],\n modelRuntime,\n modelRuntime,\n );\n if (sleepTasks[0]) {\n await session.appendAndRun(sleepTasks[0]);\n }\n }\n }\n\n return session.appendErrorPlan(`waitFor timeout: ${errorThought}`);\n }\n}\n/**\n * Surface a captured screenshot sequence in the report timeline, then release\n * it from the UIContext.\n *\n * When a UIObservation insight runs, the observed frames live on\n * `uiContext.screenshotSequence` only as a transient model input. This attaches\n * them to the task recorder so the report renders the full sequence the model\n * saw (the report timeline builds one screenshot per recorder item), then drops\n * the field from the UIContext so its base64 is not retained twice for the\n * lifetime of the dump.\n *\n * The last frame is the representative `uiContext.screenshot`, already shown in\n * the report, so only the earlier frames are recorded to avoid duplication.\n * Observed frames are PREPENDED to `task.recorder` (rather than appended) so\n * array order matches chronological order — they were captured before the\n * assertion's before/after screenshots.\n */\nexport function recordAndReleaseScreenshotSequence(\n task: ExecutionTask,\n uiContext: UIContext | undefined,\n): void {\n const frames = uiContext?.screenshotSequence;\n if (frames && frames.length > 1) {\n const recorderItems: ExecutionRecorderItem[] = [];\n for (let i = 0; i < frames.length - 1; i++) {\n const frame = frames[i];\n recorderItems.push({\n type: 'screenshot',\n ts: frame.capturedAt,\n screenshot: frame,\n description: `Observed frame ${i + 1}/${frames.length}`,\n timing: 'observed-frame',\n });\n }\n // Prepend observed frames so they appear before the task's own\n // before/after screenshots in array order. Observed frames have earlier\n // timestamps than the assertion task itself, so this keeps array order\n // aligned with chronological order for consumers that iterate in-place.\n task.recorder = task.recorder\n ? [...recorderItems, ...task.recorder]\n : recorderItems;\n }\n if (uiContext?.screenshotSequence) {\n uiContext.screenshotSequence = undefined;\n }\n}\n"],"names":["debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","TaskExecutor","title","options","ExecutionSession","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","undefined","format","getReadableTimeString","plans","planningModel","defaultModel","userInstruction","yamlString","reportOptions","session","taskTitleStr","userPromptToString","userPromptToMultimodalPrompt","task","executorContext","uiContext","assert","executionPlanningModel","executionDefaultModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","abortSignal","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","noIndividualLocateModel","includeLocateInPlanning","imagesIncludeCount","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","getPreparedUserPrompt","promise","prepareUserPrompt","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","action","Array","console","planImpl","standardPlan","planResult","preparedUserPrompt","setTimingFieldOnce","renderAIContext","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","JSON","actions","thought","log","memory","usage","rawResponse","rawChoiceMessage","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","String","type","demand","modelRuntime","opt","multimodalPrompt","executionOptions","queryTask","taskContext","queryDump","applyDump","dump","ifTypeRestricted","demandInput","keyOfResult","buildTypeQueryDemandValue","extractResult","extraPageDescription","tree","descriptionOfTree","ServiceError","recordAndReleaseScreenshotSequence","outputResult","Boolean","executionModelRuntime","assertion","textPrompt","parsePrompt","description","timeoutMs","checkIntervalMs","domIncluded","screenshotIncluded","restOpt","serviceExtractOpt","overallStartTime","Date","lastCheckStart","errorThought","currentCheckStart","now","elapsed","timeRemaining","sleepTasks","interfaceInstance","service","opts","TaskBuilder","frames","recorderItems","frame"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,UAAUD,SAAS,wBAAwB;IAAE,SAAS;AAAK;AACjE,MAAME,wCAAwC;AAM9C,MAAMC,4BAA4B;AAElC,SAASC,yBAAyBC,QAAgB;IAChD,IAAIA,SAAS,MAAM,IAAIF,2BACrB,OAAOE;IAGT,OAAO,GAAGA,SAAS,KAAK,CAAC,GAAGF,2BAA2B;eAC1C,EAAEE,SAAS,MAAM,GAAGF,0BAA0B,iBAAiB,CAAC;AAC/E;AAKO,MAAMG;IAsBX,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,SAAS;IACvB;IAiCQ,uBACNC,KAAa,EACbC,OASC,EACD;QACA,OAAO,IAAIC,iBACTF,OACA,IACEC,SAAS,YACLE,QAAQ,OAAO,CAACF,QAAQ,SAAS,IACjCE,QAAQ,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,kBAAkB,KACrD;YACE,aAAa,IAAI,CAAC,mBAAmB;YACrC,OAAOF,SAAS;YAChB,iBAAiBA,SAAS;YAC1B,kBAAkB,OAAOG,QAAQC;gBAC/B,MAAM,IAAI,CAAC,KAAK,EAAE,mBAAmBD,QAAQC;gBAC7C,MAAMJ,SAAS,mBAAmBG,QAAQC;YAC5C;YACA,GAAIJ,SAAS,cAAc;gBAAE,aAAaA,QAAQ,WAAW;YAAC,IAAI,CAAC,CAAC;QACtE;IAEJ;IAEQ,iBAAiC;QACvC,OAAO,IAAI,CAAC,mBAAmB;IACjC;IAQA,MAAc,aACZK,KAAa,EACbC,KAAa,EACbC,IAAa,EACE;QACf,MAAM,IAAI,CAAC,KAAK,EAAE,aAAaF,OAAOC,OAAOC;IAC/C;IAOQ,kBACND,KAAyB,EACzBC,IAAuB,EACR;QACf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