@midscene/core 1.16.5 → 1.17.0

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 (252) hide show
  1. package/dist/es/agent/agent.mjs +11 -11
  2. package/dist/es/agent/agent.mjs.map +1 -1
  3. package/dist/es/agent/insight.mjs.map +1 -1
  4. package/dist/es/agent/tasks.mjs +72 -39
  5. package/dist/es/agent/tasks.mjs.map +1 -1
  6. package/dist/es/agent/utils.mjs +1 -1
  7. package/dist/es/ai-model/connectivity/run-connectivity-test.mjs +27 -22
  8. package/dist/es/ai-model/connectivity/run-connectivity-test.mjs.map +1 -1
  9. package/dist/es/ai-model/index.mjs +2 -2
  10. package/dist/es/ai-model/model-adapter/resolve.mjs +4 -2
  11. package/dist/es/ai-model/model-adapter/resolve.mjs.map +1 -1
  12. package/dist/es/ai-model/models/jev/adapter.mjs +6 -110
  13. package/dist/es/ai-model/models/jev/adapter.mjs.map +1 -1
  14. package/dist/es/ai-model/models/jev/boolean.mjs +48 -0
  15. package/dist/es/ai-model/models/jev/boolean.mjs.map +1 -0
  16. package/dist/es/ai-model/models/jev/image.mjs +39 -36
  17. package/dist/es/ai-model/models/jev/image.mjs.map +1 -1
  18. package/dist/es/ai-model/models/jev/locate.mjs +48 -0
  19. package/dist/es/ai-model/models/jev/locate.mjs.map +1 -0
  20. package/dist/es/ai-model/models/jev/planning-action.mjs +35 -0
  21. package/dist/es/ai-model/models/jev/planning-action.mjs.map +1 -0
  22. package/dist/es/ai-model/models/jev/planning-context.mjs +38 -0
  23. package/dist/es/ai-model/models/jev/planning-context.mjs.map +1 -0
  24. package/dist/es/ai-model/models/jev/planning-decision.mjs +68 -0
  25. package/dist/es/ai-model/models/jev/planning-decision.mjs.map +1 -0
  26. package/dist/es/ai-model/models/jev/planning.mjs +19 -131
  27. package/dist/es/ai-model/models/jev/planning.mjs.map +1 -1
  28. package/dist/es/ai-model/models/model-fallback.mjs +28 -0
  29. package/dist/es/ai-model/models/model-fallback.mjs.map +1 -0
  30. package/dist/es/ai-model/service-caller/call-ai.mjs +27 -24
  31. package/dist/es/ai-model/service-caller/call-ai.mjs.map +1 -1
  32. package/dist/es/ai-model/service-caller/codex/call-codex.mjs.map +1 -1
  33. package/dist/es/ai-model/service-caller/index.mjs +2 -2
  34. package/dist/es/ai-model/service-caller/model-call.mjs +3 -3
  35. package/dist/es/ai-model/service-caller/model-call.mjs.map +1 -1
  36. package/dist/es/ai-model/service-caller/openai/call-openai.mjs +1 -1
  37. package/dist/es/ai-model/service-caller/openai/call-openai.mjs.map +1 -1
  38. package/dist/es/ai-model/service-caller/openai/chat-completion/chat-completion.mjs.map +1 -1
  39. package/dist/es/ai-model/service-caller/openai/openai-client.mjs.map +1 -1
  40. package/dist/es/ai-model/service-caller/openai/responses/responses.mjs.map +1 -1
  41. package/dist/es/ai-model/service-caller/system-one/call-system-one.mjs +69 -0
  42. package/dist/es/ai-model/service-caller/system-one/call-system-one.mjs.map +1 -0
  43. package/dist/es/ai-model/service-caller/system-one/index.mjs +3 -0
  44. package/dist/es/ai-model/service-caller/system-one/prepare-system-one.mjs +44 -0
  45. package/dist/es/ai-model/service-caller/system-one/prepare-system-one.mjs.map +1 -0
  46. package/dist/es/ai-model/service-caller/system-one/schema.mjs +32 -0
  47. package/dist/es/ai-model/service-caller/system-one/schema.mjs.map +1 -0
  48. package/dist/es/ai-model/service-caller/system-one/utils.mjs +34 -0
  49. package/dist/es/ai-model/service-caller/system-one/utils.mjs.map +1 -0
  50. package/dist/es/ai-model/service-caller/utils.mjs +2 -2
  51. package/dist/es/ai-model/service-caller/utils.mjs.map +1 -1
  52. package/dist/es/ai-model/shared/model-locate-result/factory.mjs +7 -3
  53. package/dist/es/ai-model/shared/model-locate-result/factory.mjs.map +1 -1
  54. package/dist/es/ai-model/shared/model-locate-result/pixel-mapper.mjs +10 -4
  55. package/dist/es/ai-model/shared/model-locate-result/pixel-mapper.mjs.map +1 -1
  56. package/dist/es/ai-model/shared/model-locate-result/types.mjs.map +1 -1
  57. package/dist/es/ai-model/shared/model-locate-result/validation.mjs +4 -0
  58. package/dist/es/ai-model/shared/model-locate-result/validation.mjs.map +1 -1
  59. package/dist/es/ai-model/workflows/grounding/locate.mjs +2 -2
  60. package/dist/es/ai-model/workflows/grounding/locate.mjs.map +1 -1
  61. package/dist/es/ai-model/workflows/grounding/section-locate.mjs +2 -2
  62. package/dist/es/ai-model/workflows/grounding/section-locate.mjs.map +1 -1
  63. package/dist/es/ai-model/workflows/insight/boolean.mjs +1 -1
  64. package/dist/es/ai-model/workflows/insight/boolean.mjs.map +1 -1
  65. package/dist/es/ai-model/workflows/insight/extraction.mjs +3 -3
  66. package/dist/es/ai-model/workflows/insight/extraction.mjs.map +1 -1
  67. package/dist/es/ai-model/workflows/planning/standard-planning.mjs +4 -3
  68. package/dist/es/ai-model/workflows/planning/standard-planning.mjs.map +1 -1
  69. package/dist/es/ai-model/workflows/recorder-generation/playwright.mjs +2 -2
  70. package/dist/es/ai-model/workflows/recorder-generation/playwright.mjs.map +1 -1
  71. package/dist/es/ai-model/workflows/recorder-generation/yaml.mjs +2 -2
  72. package/dist/es/ai-model/workflows/recorder-generation/yaml.mjs.map +1 -1
  73. package/dist/es/device/index.mjs +7 -0
  74. package/dist/es/device/index.mjs.map +1 -1
  75. package/dist/es/report-html-template.mjs +1 -1
  76. package/dist/es/service/index.mjs +2 -1
  77. package/dist/es/service/index.mjs.map +1 -1
  78. package/dist/es/types.mjs.map +1 -1
  79. package/dist/es/utils.mjs +1 -1
  80. package/dist/lib/agent/agent.js +11 -11
  81. package/dist/lib/agent/agent.js.map +1 -1
  82. package/dist/lib/agent/insight.js.map +1 -1
  83. package/dist/lib/agent/tasks.js +72 -39
  84. package/dist/lib/agent/tasks.js.map +1 -1
  85. package/dist/lib/agent/utils.js +1 -1
  86. package/dist/lib/ai-model/connectivity/run-connectivity-test.js +27 -22
  87. package/dist/lib/ai-model/connectivity/run-connectivity-test.js.map +1 -1
  88. package/dist/lib/ai-model/index.js +6 -3
  89. package/dist/lib/ai-model/model-adapter/resolve.js +4 -2
  90. package/dist/lib/ai-model/model-adapter/resolve.js.map +1 -1
  91. package/dist/lib/ai-model/models/jev/adapter.js +6 -110
  92. package/dist/lib/ai-model/models/jev/adapter.js.map +1 -1
  93. package/dist/lib/ai-model/models/jev/boolean.js +82 -0
  94. package/dist/lib/ai-model/models/jev/boolean.js.map +1 -0
  95. package/dist/lib/ai-model/models/jev/image.js +41 -35
  96. package/dist/lib/ai-model/models/jev/image.js.map +1 -1
  97. package/dist/lib/ai-model/models/jev/locate.js +82 -0
  98. package/dist/lib/ai-model/models/jev/locate.js.map +1 -0
  99. package/dist/lib/ai-model/models/jev/planning-action.js +69 -0
  100. package/dist/lib/ai-model/models/jev/planning-action.js.map +1 -0
  101. package/dist/lib/ai-model/models/jev/planning-context.js +72 -0
  102. package/dist/lib/ai-model/models/jev/planning-context.js.map +1 -0
  103. package/dist/lib/ai-model/models/jev/planning-decision.js +102 -0
  104. package/dist/lib/ai-model/models/jev/planning-decision.js.map +1 -0
  105. package/dist/lib/ai-model/models/jev/planning.js +19 -131
  106. package/dist/lib/ai-model/models/jev/planning.js.map +1 -1
  107. package/dist/lib/ai-model/models/{task-routing.js → model-fallback.js} +11 -11
  108. package/dist/lib/ai-model/models/model-fallback.js.map +1 -0
  109. package/dist/lib/ai-model/service-caller/call-ai.js +32 -26
  110. package/dist/lib/ai-model/service-caller/call-ai.js.map +1 -1
  111. package/dist/lib/ai-model/service-caller/codex/call-codex.js.map +1 -1
  112. package/dist/lib/ai-model/service-caller/index.js +6 -3
  113. package/dist/lib/ai-model/service-caller/model-call.js +2 -2
  114. package/dist/lib/ai-model/service-caller/model-call.js.map +1 -1
  115. package/dist/lib/ai-model/service-caller/openai/call-openai.js +1 -1
  116. package/dist/lib/ai-model/service-caller/openai/call-openai.js.map +1 -1
  117. package/dist/lib/ai-model/service-caller/openai/chat-completion/chat-completion.js.map +1 -1
  118. package/dist/lib/ai-model/service-caller/openai/openai-client.js.map +1 -1
  119. package/dist/lib/ai-model/service-caller/openai/responses/responses.js.map +1 -1
  120. package/dist/lib/ai-model/service-caller/system-one/call-system-one.js +103 -0
  121. package/dist/lib/ai-model/service-caller/system-one/call-system-one.js.map +1 -0
  122. package/dist/lib/ai-model/service-caller/system-one/index.js +42 -0
  123. package/dist/lib/ai-model/service-caller/system-one/index.js.map +1 -0
  124. package/dist/lib/ai-model/service-caller/system-one/prepare-system-one.js +78 -0
  125. package/dist/lib/ai-model/service-caller/system-one/prepare-system-one.js.map +1 -0
  126. package/dist/lib/ai-model/service-caller/system-one/schema.js +69 -0
  127. package/dist/lib/ai-model/service-caller/system-one/schema.js.map +1 -0
  128. package/dist/lib/ai-model/service-caller/system-one/utils.js +68 -0
  129. package/dist/lib/ai-model/service-caller/system-one/utils.js.map +1 -0
  130. package/dist/lib/ai-model/service-caller/utils.js +2 -2
  131. package/dist/lib/ai-model/service-caller/utils.js.map +1 -1
  132. package/dist/lib/ai-model/shared/model-locate-result/factory.js +7 -3
  133. package/dist/lib/ai-model/shared/model-locate-result/factory.js.map +1 -1
  134. package/dist/lib/ai-model/shared/model-locate-result/pixel-mapper.js +10 -4
  135. package/dist/lib/ai-model/shared/model-locate-result/pixel-mapper.js.map +1 -1
  136. package/dist/lib/ai-model/shared/model-locate-result/types.js.map +1 -1
  137. package/dist/lib/ai-model/shared/model-locate-result/validation.js +4 -0
  138. package/dist/lib/ai-model/shared/model-locate-result/validation.js.map +1 -1
  139. package/dist/lib/ai-model/workflows/grounding/locate.js +1 -1
  140. package/dist/lib/ai-model/workflows/grounding/locate.js.map +1 -1
  141. package/dist/lib/ai-model/workflows/grounding/section-locate.js +1 -1
  142. package/dist/lib/ai-model/workflows/grounding/section-locate.js.map +1 -1
  143. package/dist/lib/ai-model/workflows/insight/boolean.js +1 -1
  144. package/dist/lib/ai-model/workflows/insight/boolean.js.map +1 -1
  145. package/dist/lib/ai-model/workflows/insight/extraction.js +2 -2
  146. package/dist/lib/ai-model/workflows/insight/extraction.js.map +1 -1
  147. package/dist/lib/ai-model/workflows/planning/standard-planning.js +3 -2
  148. package/dist/lib/ai-model/workflows/planning/standard-planning.js.map +1 -1
  149. package/dist/lib/ai-model/workflows/recorder-generation/playwright.js +1 -1
  150. package/dist/lib/ai-model/workflows/recorder-generation/playwright.js.map +1 -1
  151. package/dist/lib/ai-model/workflows/recorder-generation/yaml.js +1 -1
  152. package/dist/lib/ai-model/workflows/recorder-generation/yaml.js.map +1 -1
  153. package/dist/lib/device/index.js +7 -0
  154. package/dist/lib/device/index.js.map +1 -1
  155. package/dist/lib/report-html-template.js +1 -1
  156. package/dist/lib/service/index.js +2 -1
  157. package/dist/lib/service/index.js.map +1 -1
  158. package/dist/lib/types.js.map +1 -1
  159. package/dist/lib/utils.js +1 -1
  160. package/dist/types/agent/agent.d.ts.map +1 -1
  161. package/dist/types/agent/insight.d.ts +2 -2
  162. package/dist/types/agent/insight.d.ts.map +1 -1
  163. package/dist/types/agent/tasks.d.ts.map +1 -1
  164. package/dist/types/ai-model/connectivity/run-connectivity-test.d.ts.map +1 -1
  165. package/dist/types/ai-model/index.d.ts +1 -1
  166. package/dist/types/ai-model/index.d.ts.map +1 -1
  167. package/dist/types/ai-model/model-adapter/resolve.d.ts +2 -1
  168. package/dist/types/ai-model/model-adapter/resolve.d.ts.map +1 -1
  169. package/dist/types/ai-model/model-adapter/types.d.ts +8 -5
  170. package/dist/types/ai-model/model-adapter/types.d.ts.map +1 -1
  171. package/dist/types/ai-model/models/gpt.d.ts +2 -2
  172. package/dist/types/ai-model/models/jev/adapter.d.ts +4 -5
  173. package/dist/types/ai-model/models/jev/adapter.d.ts.map +1 -1
  174. package/dist/types/ai-model/models/jev/boolean.d.ts +3 -0
  175. package/dist/types/ai-model/models/jev/boolean.d.ts.map +1 -0
  176. package/dist/types/ai-model/models/jev/image.d.ts +11 -11
  177. package/dist/types/ai-model/models/jev/image.d.ts.map +1 -1
  178. package/dist/types/ai-model/models/jev/locate.d.ts +3 -0
  179. package/dist/types/ai-model/models/jev/locate.d.ts.map +1 -0
  180. package/dist/types/ai-model/models/jev/planning-action.d.ts +6 -0
  181. package/dist/types/ai-model/models/jev/planning-action.d.ts.map +1 -0
  182. package/dist/types/ai-model/models/jev/planning-context.d.ts +23 -0
  183. package/dist/types/ai-model/models/jev/planning-context.d.ts.map +1 -0
  184. package/dist/types/ai-model/models/jev/planning-decision.d.ts +35 -0
  185. package/dist/types/ai-model/models/jev/planning-decision.d.ts.map +1 -0
  186. package/dist/types/ai-model/models/jev/planning.d.ts.map +1 -1
  187. package/dist/types/ai-model/models/model-fallback.d.ts +6 -0
  188. package/dist/types/ai-model/models/model-fallback.d.ts.map +1 -0
  189. package/dist/types/ai-model/models/registry.d.ts +4 -3
  190. package/dist/types/ai-model/models/registry.d.ts.map +1 -1
  191. package/dist/types/ai-model/service-caller/call-ai.d.ts +3 -1
  192. package/dist/types/ai-model/service-caller/call-ai.d.ts.map +1 -1
  193. package/dist/types/ai-model/service-caller/codex/call-codex.d.ts +5 -3
  194. package/dist/types/ai-model/service-caller/codex/call-codex.d.ts.map +1 -1
  195. package/dist/types/ai-model/service-caller/index.d.ts +1 -1
  196. package/dist/types/ai-model/service-caller/index.d.ts.map +1 -1
  197. package/dist/types/ai-model/service-caller/model-call.d.ts +2 -2
  198. package/dist/types/ai-model/service-caller/model-call.d.ts.map +1 -1
  199. package/dist/types/ai-model/service-caller/openai/call-openai.d.ts +2 -2
  200. package/dist/types/ai-model/service-caller/openai/call-openai.d.ts.map +1 -1
  201. package/dist/types/ai-model/service-caller/openai/chat-completion/chat-completion.d.ts +4 -2
  202. package/dist/types/ai-model/service-caller/openai/chat-completion/chat-completion.d.ts.map +1 -1
  203. package/dist/types/ai-model/service-caller/openai/responses/responses.d.ts +4 -2
  204. package/dist/types/ai-model/service-caller/openai/responses/responses.d.ts.map +1 -1
  205. package/dist/types/ai-model/service-caller/system-one/call-system-one.d.ts +4 -0
  206. package/dist/types/ai-model/service-caller/system-one/call-system-one.d.ts.map +1 -0
  207. package/dist/types/ai-model/service-caller/system-one/index.d.ts +3 -0
  208. package/dist/types/ai-model/service-caller/system-one/index.d.ts.map +1 -0
  209. package/dist/types/ai-model/service-caller/system-one/prepare-system-one.d.ts +21 -0
  210. package/dist/types/ai-model/service-caller/system-one/prepare-system-one.d.ts.map +1 -0
  211. package/dist/types/ai-model/service-caller/{system-one.d.ts → system-one/schema.d.ts} +1 -22
  212. package/dist/types/ai-model/service-caller/system-one/schema.d.ts.map +1 -0
  213. package/dist/types/ai-model/service-caller/system-one/utils.d.ts +6 -0
  214. package/dist/types/ai-model/service-caller/system-one/utils.d.ts.map +1 -0
  215. package/dist/types/ai-model/service-caller/types.d.ts +0 -3
  216. package/dist/types/ai-model/service-caller/types.d.ts.map +1 -1
  217. package/dist/types/ai-model/service-caller/utils.d.ts +3 -3
  218. package/dist/types/ai-model/shared/model-locate-result/factory.d.ts.map +1 -1
  219. package/dist/types/ai-model/shared/model-locate-result/index.d.ts +1 -1
  220. package/dist/types/ai-model/shared/model-locate-result/index.d.ts.map +1 -1
  221. package/dist/types/ai-model/shared/model-locate-result/pixel-mapper.d.ts +3 -3
  222. package/dist/types/ai-model/shared/model-locate-result/pixel-mapper.d.ts.map +1 -1
  223. package/dist/types/ai-model/shared/model-locate-result/types.d.ts +4 -0
  224. package/dist/types/ai-model/shared/model-locate-result/types.d.ts.map +1 -1
  225. package/dist/types/ai-model/shared/model-locate-result/validation.d.ts.map +1 -1
  226. package/dist/types/ai-model/workflows/grounding/locate.d.ts.map +1 -1
  227. package/dist/types/ai-model/workflows/grounding/section-locate.d.ts.map +1 -1
  228. package/dist/types/ai-model/workflows/insight/boolean.d.ts.map +1 -1
  229. package/dist/types/ai-model/workflows/insight/extraction.d.ts +2 -0
  230. package/dist/types/ai-model/workflows/insight/extraction.d.ts.map +1 -1
  231. package/dist/types/ai-model/workflows/planning/standard-planning.d.ts.map +1 -1
  232. package/dist/types/ai-model/workflows/planning/types.d.ts +2 -1
  233. package/dist/types/ai-model/workflows/planning/types.d.ts.map +1 -1
  234. package/dist/types/ai-model/workflows/recorder-generation/playwright.d.ts.map +1 -1
  235. package/dist/types/ai-model/workflows/recorder-generation/yaml.d.ts.map +1 -1
  236. package/dist/types/device/index.d.ts +1 -0
  237. package/dist/types/device/index.d.ts.map +1 -1
  238. package/dist/types/service/index.d.ts +1 -1
  239. package/dist/types/service/index.d.ts.map +1 -1
  240. package/dist/types/types.d.ts +14 -3
  241. package/dist/types/types.d.ts.map +1 -1
  242. package/package.json +2 -2
  243. package/dist/es/ai-model/models/task-routing.mjs +0 -28
  244. package/dist/es/ai-model/models/task-routing.mjs.map +0 -1
  245. package/dist/es/ai-model/service-caller/system-one.mjs +0 -163
  246. package/dist/es/ai-model/service-caller/system-one.mjs.map +0 -1
  247. package/dist/lib/ai-model/models/task-routing.js.map +0 -1
  248. package/dist/lib/ai-model/service-caller/system-one.js +0 -206
  249. package/dist/lib/ai-model/service-caller/system-one.js.map +0 -1
  250. package/dist/types/ai-model/models/task-routing.d.ts +0 -6
  251. package/dist/types/ai-model/models/task-routing.d.ts.map +0 -1
  252. package/dist/types/ai-model/service-caller/system-one.d.ts.map +0 -1
@@ -252,7 +252,11 @@ class TaskExecutor {
252
252
  executionId: runner.id
253
253
  };
254
254
  const noIndividualLocateModel = 'default' === planningModel.config.slot && 'default' === locateModel.config.slot;
255
- const includeLocateInPlanning = 'deepThink' !== effort && noIndividualLocateModel;
255
+ const planningConfig = planningModel.config;
256
+ const locateConfig = locateModel.config;
257
+ const sameSystemOneModel = 'system-one' === planningModel.adapter.modelType && 'system-one' === locateModel.adapter.modelType && planningConfig.modelName === locateConfig.modelName && planningConfig.openaiBaseURL === locateConfig.openaiBaseURL;
258
+ const bothJev = 'jev' === planningConfig.modelFamily && 'jev' === locateConfig.modelFamily;
259
+ const includeLocateInPlanning = 'deepThink' !== effort && (noIndividualLocateModel || sameSystemOneModel && bothJev);
256
260
  const imagesIncludeCount = 'deepThink' === effort ? 2 : 1;
257
261
  debug('setting includeLocateInPlanning to', includeLocateInPlanning, {
258
262
  effort,
@@ -289,6 +293,7 @@ class TaskExecutor {
289
293
  };
290
294
  })();
291
295
  while(true){
296
+ const delegation = latestPlanResult?.delegation;
292
297
  const planIndex = replanCount + 1;
293
298
  latestPlanIndex = planIndex;
294
299
  if (abortSignal?.aborted) return appendFailedPlan(`Task aborted: ${abortSignal.reason || 'abort signal received'}`, planIndex);
@@ -327,7 +332,32 @@ class TaskExecutor {
327
332
  debug('actionSpace for this interface is:', actionSpace.map((action)=>action.name).join(', '));
328
333
  (0, utils_namespaceObject.assert)(Array.isArray(actionSpace), 'actionSpace must be an array');
329
334
  if (0 === actionSpace.length) console.warn(`ActionSpace for ${this.interface.interfaceType} is empty. This may lead to unexpected behavior.`);
330
- const planImpl = 'custom' === planningModel.adapter.planning.kind ? planningModel.adapter.planning.planFn : planning_index_js_namespaceObject.standardPlan;
335
+ const modelRuntime = (()=>{
336
+ if (!delegation) return planningModel;
337
+ const base = this.getDefaultModelRuntime();
338
+ (0, utils_namespaceObject.assert)('jev' !== base.config.modelFamily, 'The default planner cannot use the Jev model family');
339
+ return {
340
+ ...base,
341
+ config: {
342
+ ...base.config,
343
+ intent: 'planning'
344
+ },
345
+ executionId: planningModel.executionId,
346
+ onUsage: base.onUsage ? (usage)=>base.onUsage?.({
347
+ ...usage,
348
+ intent: 'planning'
349
+ }) : void 0,
350
+ modelFallback: {
351
+ requestedModel: planningModel.config.modelName,
352
+ requestedSlot: planningModel.config.slot,
353
+ taskType: 'planning',
354
+ reason: delegation.reason
355
+ }
356
+ };
357
+ })();
358
+ const suggestedAction = delegation?.suggestedAction;
359
+ const planningAdvice = suggestedAction ? `The preceding planner suggested that the next step may require action ${JSON.stringify(suggestedAction)}. This suggestion has NOT been executed and is advisory only. Independently determine the next step from the original goal, current screenshot, history and execution feedback. You may choose a different action or finish the task.` : void 0;
360
+ const planImpl = 'custom' === modelRuntime.adapter.planning.kind ? modelRuntime.adapter.planning.planFn : planning_index_js_namespaceObject.standardPlan;
331
361
  let planResult;
332
362
  try {
333
363
  const preparedUserPrompt = await getPreparedUserPrompt();
@@ -336,11 +366,11 @@ class TaskExecutor {
336
366
  context: planningUiContext,
337
367
  actionContext: (0, external_prompt_context_js_namespaceObject.renderAIContext)(aiActContext),
338
368
  actionSpace,
339
- modelRuntime: planningModel,
340
- locateModelRuntime: locateModel,
369
+ modelRuntime,
370
+ planningAdvice,
341
371
  getDefaultModelRuntime: this.getDefaultModelRuntime,
342
372
  conversationHistory,
343
- includeLocateInPlanning,
373
+ includeLocateInPlanning: !delegation && includeLocateInPlanning,
344
374
  imagesIncludeCount,
345
375
  effort,
346
376
  abortSignal
@@ -375,6 +405,7 @@ class TaskExecutor {
375
405
  executorContext.task.reasoning_content = reasoning_content;
376
406
  executorContext.task.output = {
377
407
  actions: actions || [],
408
+ delegation: planResult.delegation,
378
409
  log,
379
410
  thought,
380
411
  memory,
@@ -424,45 +455,47 @@ class TaskExecutor {
424
455
  });
425
456
  const planResult = result?.output;
426
457
  latestPlanResult = planResult;
427
- const plans = planResult?.actions || [];
428
- yamlFlow.push(...planResult?.yamlFlow || []);
429
- let executables;
430
- try {
431
- executables = await this.convertPlanToExecutable(plans, planningModel, locateModel, {
432
- cacheable,
433
- multimodalPrompt: (0, external_common_js_namespaceObject.userPromptToMultimodalPrompt)(userPrompt),
434
- deepLocate,
435
- abortSignal
436
- });
437
- } catch (error) {
438
- return appendFailedPlan(`Error converting plans to executable tasks: ${(0, external_progress_index_js_namespaceObject.errorMessageForAiAct)(error)}, plans: ${JSON.stringify(plans)}`, planIndex);
439
- }
440
- if (conversationHistory.pendingFeedbackMessage) console.warn('unconsumed pending feedback message detected, this may lead to unexpected planning result:', conversationHistory.pendingFeedbackMessage);
441
- const initialTimeString = await this.getTimeString();
442
- const taskCountBeforeRun = runner.tasks.length;
443
- activeActionReporter = (0, external_progress_index_js_namespaceObject.createAiActActionReporter)(planIndex, replanningCycleLimit, (phase, data)=>this.emitAiActProgress(phase, data));
444
- try {
445
- await session.appendAndRun(executables.tasks);
446
- this.setPendingFeedbackMessage(conversationHistory, initialTimeString, this.collectPlanningFeedback(runner.tasks.slice(taskCountBeforeRun)));
447
- } catch (error) {
448
- if ((0, external_action_readiness_js_namespaceObject.isActionReadinessError)(error)) throw error;
449
- errorCountInOnePlanningLoop++;
450
- const timeString = await this.getTimeString();
451
- this.setPendingFeedbackMessage(conversationHistory, timeString, `Error executing running tasks: ${error?.message || String(error)}`);
452
- debug('error when executing running tasks, but continue to run if it is not too many errors:', error instanceof Error ? error.message : String(error), 'current error count in one planning loop:', errorCountInOnePlanningLoop);
453
- } finally{
454
- activeActionReporter = void 0;
458
+ if (!planResult?.delegation) {
459
+ const plans = planResult?.actions || [];
460
+ yamlFlow.push(...planResult?.yamlFlow || []);
461
+ let executables;
462
+ try {
463
+ executables = await this.convertPlanToExecutable(plans, planningModel, locateModel, {
464
+ cacheable,
465
+ multimodalPrompt: (0, external_common_js_namespaceObject.userPromptToMultimodalPrompt)(userPrompt),
466
+ deepLocate,
467
+ abortSignal
468
+ });
469
+ } catch (error) {
470
+ return appendFailedPlan(`Error converting plans to executable tasks: ${(0, external_progress_index_js_namespaceObject.errorMessageForAiAct)(error)}, plans: ${JSON.stringify(plans)}`, planIndex);
471
+ }
472
+ if (conversationHistory.pendingFeedbackMessage) console.warn('unconsumed pending feedback message detected, this may lead to unexpected planning result:', conversationHistory.pendingFeedbackMessage);
473
+ const initialTimeString = await this.getTimeString();
474
+ const taskCountBeforeRun = runner.tasks.length;
475
+ activeActionReporter = (0, external_progress_index_js_namespaceObject.createAiActActionReporter)(planIndex, replanningCycleLimit, (phase, data)=>this.emitAiActProgress(phase, data));
476
+ try {
477
+ await session.appendAndRun(executables.tasks);
478
+ this.setPendingFeedbackMessage(conversationHistory, initialTimeString, this.collectPlanningFeedback(runner.tasks.slice(taskCountBeforeRun)));
479
+ } catch (error) {
480
+ if ((0, external_action_readiness_js_namespaceObject.isActionReadinessError)(error)) throw error;
481
+ errorCountInOnePlanningLoop++;
482
+ const timeString = await this.getTimeString();
483
+ this.setPendingFeedbackMessage(conversationHistory, timeString, `Error executing running tasks: ${error?.message || String(error)}`);
484
+ debug('error when executing running tasks, but continue to run if it is not too many errors:', error instanceof Error ? error.message : String(error), 'current error count in one planning loop:', errorCountInOnePlanningLoop);
485
+ } finally{
486
+ activeActionReporter = void 0;
487
+ }
488
+ if (errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop) return appendFailedPlan('Too many errors in one planning loop', planIndex);
489
+ if (abortSignal?.aborted) return appendFailedPlan(`Task aborted: ${abortSignal.reason || 'abort signal received'}`, planIndex);
490
+ if (!planResult?.shouldContinuePlanning) break;
491
+ this.invalidateFailedCacheHitLocates(runner, taskCountBeforeRun);
455
492
  }
456
- if (errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop) return appendFailedPlan('Too many errors in one planning loop', planIndex);
457
- if (abortSignal?.aborted) return appendFailedPlan(`Task aborted: ${abortSignal.reason || 'abort signal received'}`, planIndex);
458
- if (!planResult?.shouldContinuePlanning) break;
459
- this.invalidateFailedCacheHitLocates(runner, taskCountBeforeRun);
460
493
  ++replanCount;
461
494
  if (replanCount > replanningCycleLimit) {
462
495
  const errorMsg = `Task stopped: the planning cycle limit (${replanningCycleLimit}) has been reached. This limit prevents the model from getting stuck in an endless planning loop. If your task requires more planning cycles, increase replanningCycleLimit or set the environment variable MIDSCENE_REPLANNING_CYCLE_LIMIT to a higher value. See https://midscenejs.com/zh/reference/#common for details.`;
463
496
  return appendFailedPlan(errorMsg, planIndex);
464
497
  }
465
- if (!conversationHistory.pendingFeedbackMessage) {
498
+ if (!planResult?.delegation && !conversationHistory.pendingFeedbackMessage) {
466
499
  const timeString = await this.getTimeString();
467
500
  conversationHistory.pendingFeedbackMessage = `Time: ${timeString}, I have finished the action previously planned.`;
468
501
  }
@@ -540,7 +573,7 @@ class TaskExecutor {
540
573
  extraPageDescription = await (0, extractor_namespaceObject.descriptionOfTree)(tree, 200, false, opt?.domIncluded === 'visible-only');
541
574
  }
542
575
  try {
543
- extractResult = await this.service.extract(demandInput, modelRuntime, opt, extraPageDescription, multimodalPrompt, uiContext, {
576
+ extractResult = await this.service.extract(demandInput, modelRuntime, 'Boolean' === type || 'Assert' === type || 'WaitFor' === type ? 'boolean' : 'extract', opt, extraPageDescription, multimodalPrompt, uiContext, {
544
577
  ...executionOptions,
545
578
  abortSignal: executionOptions?.abortSignal ?? taskContext.signal
546
579
  });
@@ -1 +1 @@
1
- {"version":3,"file":"agent/tasks.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/agent/tasks.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","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, defineActionSleep } 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 {\n type ActionReadiness,\n isActionReadinessError,\n} from './action-readiness';\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 onExecutionCreated?: (runner: TaskRunner) => void;\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 planning feedback by default so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. Actions\n// that require lossless structured feedback can explicitly choose their limit.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(\n feedback: string,\n requestedLimit?: number | 'unlimited',\n): string {\n if (requestedLimit === 'unlimited') {\n return feedback;\n }\n const limit =\n requestedLimit && Number.isFinite(requestedLimit) && requestedLimit > 0\n ? Math.floor(requestedLimit)\n : maxPlanningFeedbackLength;\n if (feedback.length <= limit) {\n return feedback;\n }\n\n return `${feedback.slice(0, limit)}\n...[truncated, ${feedback.length - limit} 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 getDefaultModelRuntime: () => ModelRuntime;\n private readonly providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\n private readonly getAbortSignal?: () => AbortSignal | undefined;\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 getDefaultModelRuntime: () => ModelRuntime;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n actionReadiness?: ActionReadiness;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n getAbortSignal?: () => AbortSignal | undefined;\n operationResource?: object;\n actionSpace: DeviceAction[];\n },\n ) {\n this.getDefaultModelRuntime = opts.getDefaultModelRuntime;\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.getAbortSignal = opts.getAbortSignal;\n this.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n getDefaultModelRuntime: opts.getDefaultModelRuntime,\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n actionReadiness: opts.actionReadiness,\n operationResource: opts.operationResource,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n abortSignal?: AbortSignal;\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 const session = new ExecutionSession(\n title,\n (signal) =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn(signal)),\n {\n abortSignal: options?.abortSignal ?? this.getAbortSignal?.(),\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 this.hooks?.onExecutionCreated?.(session.getRunner());\n return session;\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(\n ({ planningFeedback, planningFeedbackMaxLength }) =>\n planningFeedback\n ? [\n truncatePlanningFeedback(\n planningFeedback,\n planningFeedbackMaxLength,\n ),\n ]\n : [],\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 locateModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n multimodalPrompt?: TMultimodalPrompt;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, locateModel, 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 sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {\n abortSignal ??= this.getAbortSignal?.();\n const session = this.createExecutionSession('Sleep', { abortSignal });\n const action = defineActionSleep(abortSignal);\n await session.appendAndRun({\n type: 'Action Space',\n subType: action.name,\n param: { timeMs: ms },\n executor: async ({ task }) => {\n assert(\n Number.isFinite(ms) && ms > 0,\n `ms for sleep must be a finite number greater than 0, but got ${ms}`,\n );\n setTimingFieldOnce(task.timing, 'callActionStart');\n try {\n await action.call({ timeMs: ms });\n } finally {\n setTimingFieldOnce(task.timing, 'callActionEnd');\n }\n },\n });\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: { uiContext?: UIContext; abortSignal?: AbortSignal },\n ): Promise<ExecutionResult> {\n const abortSignal = options?.abortSignal ?? this.getAbortSignal?.();\n const session = this.createExecutionSession(title, {\n ...options,\n abortSignal,\n });\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionLocateModel = { ...locateModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionLocateModel,\n { abortSignal },\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 locateModel: 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 abortSignal?.throwIfAborted();\n return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n locateModel,\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 locateModel: 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 abortSignal ??= this.getAbortSignal?.();\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 abortSignal,\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 locateModel = { ...locateModel, executionId: runner.id };\n\n const noIndividualLocateModel =\n planningModel.config.slot === 'default' &&\n locateModel.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 locateModelRuntime: locateModel,\n getDefaultModelRuntime: this.getDefaultModelRuntime,\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 rawAssistantOutput: planError.rawAssistantOutput,\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 rawAssistantOutput,\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 rawAssistantOutput,\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 locateModel,\n {\n cacheable,\n multimodalPrompt: userPromptToMultimodalPrompt(userPrompt),\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 // A completed action must not be replayed because readiness failed.\n if (isActionReadinessError(error)) throw error;\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 = `Task stopped: the planning cycle limit (${replanningCycleLimit}) has been reached. This limit prevents the model from getting stuck in an endless planning loop. If your task requires more planning cycles, increase replanningCycleLimit or set the environment variable MIDSCENE_REPLANNING_CYCLE_LIMIT to a higher value. See https://midscenejs.com/zh/reference/#common for details.`;\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 rawAssistantOutput: dump.taskInfo?.rawAssistantOutput,\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 {\n ...executionOptions,\n abortSignal: executionOptions?.abortSignal ?? taskContext.signal,\n },\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 abortSignal =\n executionOptions?.abortSignal ?? this.getAbortSignal?.();\n abortSignal?.throwIfAborted();\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 abortSignal,\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, abortSignal },\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 abortSignal = this.getAbortSignal?.();\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, abortSignal },\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 abortSignal?.throwIfAborted();\n const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\n { abortSignal },\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 { abortSignal },\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":["__webpack_require__","definition","key","Object","obj","prop","Symbol","debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","requestedLimit","limit","Number","Math","TaskExecutor","title","options","session","ExecutionSession","signal","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","planningFeedbackMaxLength","undefined","format","getReadableTimeString","plans","planningModel","locateModel","userInstruction","yamlString","reportOptions","taskTitleStr","userPromptToString","userPromptToMultimodalPrompt","task","executorContext","uiContext","assert","ms","abortSignal","action","defineActionSleep","setTimingFieldOnce","executionPlanningModel","executionLocateModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","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","Array","console","planImpl","standardPlan","planResult","preparedUserPrompt","renderAIContext","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","JSON","actions","thought","log","memory","usage","rawResponse","rawAssistantOutput","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","isActionReadinessError","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":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CA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iI;eAAkBjI,KAAK,QAAQ;SAAC,GACpCiI;IACN;IACA,IAAI/H,WAAW,oBACbA,UAAU,kBAAkB,GAAGd;AAEnC"}
1
+ {"version":3,"file":"agent/tasks.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/agent/tasks.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","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, defineActionSleep } 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 {\n type ActionReadiness,\n isActionReadinessError,\n} from './action-readiness';\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 onExecutionCreated?: (runner: TaskRunner) => void;\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 planning feedback by default so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. Actions\n// that require lossless structured feedback can explicitly choose their limit.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(\n feedback: string,\n requestedLimit?: number | 'unlimited',\n): string {\n if (requestedLimit === 'unlimited') {\n return feedback;\n }\n const limit =\n requestedLimit && Number.isFinite(requestedLimit) && requestedLimit > 0\n ? Math.floor(requestedLimit)\n : maxPlanningFeedbackLength;\n if (feedback.length <= limit) {\n return feedback;\n }\n\n return `${feedback.slice(0, limit)}\n...[truncated, ${feedback.length - limit} 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 getDefaultModelRuntime: () => ModelRuntime;\n private readonly providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\n private readonly getAbortSignal?: () => AbortSignal | undefined;\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 getDefaultModelRuntime: () => ModelRuntime;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n actionReadiness?: ActionReadiness;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n getAbortSignal?: () => AbortSignal | undefined;\n operationResource?: object;\n actionSpace: DeviceAction[];\n },\n ) {\n this.getDefaultModelRuntime = opts.getDefaultModelRuntime;\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.getAbortSignal = opts.getAbortSignal;\n this.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n getDefaultModelRuntime: opts.getDefaultModelRuntime,\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n actionReadiness: opts.actionReadiness,\n operationResource: opts.operationResource,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n abortSignal?: AbortSignal;\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 const session = new ExecutionSession(\n title,\n (signal) =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn(signal)),\n {\n abortSignal: options?.abortSignal ?? this.getAbortSignal?.(),\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 this.hooks?.onExecutionCreated?.(session.getRunner());\n return session;\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(\n ({ planningFeedback, planningFeedbackMaxLength }) =>\n planningFeedback\n ? [\n truncatePlanningFeedback(\n planningFeedback,\n planningFeedbackMaxLength,\n ),\n ]\n : [],\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 locateModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n multimodalPrompt?: TMultimodalPrompt;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, locateModel, 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 sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {\n abortSignal ??= this.getAbortSignal?.();\n const session = this.createExecutionSession('Sleep', { abortSignal });\n const action = defineActionSleep(abortSignal);\n await session.appendAndRun({\n type: 'Action Space',\n subType: action.name,\n param: { timeMs: ms },\n executor: async ({ task }) => {\n assert(\n Number.isFinite(ms) && ms > 0,\n `ms for sleep must be a finite number greater than 0, but got ${ms}`,\n );\n setTimingFieldOnce(task.timing, 'callActionStart');\n try {\n await action.call({ timeMs: ms });\n } finally {\n setTimingFieldOnce(task.timing, 'callActionEnd');\n }\n },\n });\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: { uiContext?: UIContext; abortSignal?: AbortSignal },\n ): Promise<ExecutionResult> {\n const abortSignal = options?.abortSignal ?? this.getAbortSignal?.();\n const session = this.createExecutionSession(title, {\n ...options,\n abortSignal,\n });\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionLocateModel = { ...locateModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionLocateModel,\n { abortSignal },\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 locateModel: 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 abortSignal?.throwIfAborted();\n return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n locateModel,\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 locateModel: 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 abortSignal ??= this.getAbortSignal?.();\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 abortSignal,\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 locateModel = { ...locateModel, executionId: runner.id };\n\n const noIndividualLocateModel =\n planningModel.config.slot === 'default' &&\n locateModel.config.slot === 'default';\n const planningConfig = planningModel.config;\n const locateConfig = locateModel.config;\n const sameSystemOneModel =\n planningModel.adapter.modelType === 'system-one' &&\n locateModel.adapter.modelType === 'system-one' &&\n planningConfig.modelName === locateConfig.modelName &&\n planningConfig.openaiBaseURL === locateConfig.openaiBaseURL;\n const bothJev =\n planningConfig.modelFamily === 'jev' &&\n locateConfig.modelFamily === 'jev';\n const includeLocateInPlanning =\n effort !== 'deepThink' &&\n (noIndividualLocateModel || (sameSystemOneModel && bothJev));\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 delegation = latestPlanResult?.delegation;\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 modelRuntime: ModelRuntime = (() => {\n if (!delegation) {\n return planningModel;\n }\n // For delegated planning, build a default-model runtime for this cycle.\n const base = this.getDefaultModelRuntime();\n assert(\n base.config.modelFamily !== 'jev',\n 'The default planner cannot use the Jev model family',\n );\n return {\n ...base,\n config: { ...base.config, intent: 'planning' },\n executionId: planningModel.executionId,\n onUsage: base.onUsage\n ? (usage) => base.onUsage?.({ ...usage, intent: 'planning' })\n : undefined,\n modelFallback: {\n requestedModel: planningModel.config.modelName,\n requestedSlot: planningModel.config.slot,\n taskType: 'planning',\n reason: delegation.reason,\n },\n };\n })();\n const suggestedAction = delegation?.suggestedAction;\n const planningAdvice = suggestedAction\n ? `The preceding planner suggested that the next step may require action ${JSON.stringify(suggestedAction)}. This suggestion has NOT been executed and is advisory only. Independently determine the next step from the original goal, current screenshot, history and execution feedback. You may choose a different action or finish the task.`\n : undefined;\n const planImpl =\n modelRuntime.adapter.planning.kind === 'custom'\n ? modelRuntime.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,\n planningAdvice,\n getDefaultModelRuntime: this.getDefaultModelRuntime,\n conversationHistory,\n includeLocateInPlanning: !delegation && 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 rawAssistantOutput: planError.rawAssistantOutput,\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 rawAssistantOutput,\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 rawAssistantOutput,\n };\n executorContext.task.usage = withUsageIntent(usage, 'planning');\n executorContext.task.reasoning_content = reasoning_content;\n executorContext.task.output = {\n actions: actions || [],\n delegation: planResult.delegation,\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 if (!planResult?.delegation) {\n // Execute planned actions\n const plans = planResult?.actions || [];\n yamlFlow.push(...(planResult?.yamlFlow || []));\n\n let executables: Awaited<\n ReturnType<typeof this.convertPlanToExecutable>\n >;\n try {\n executables = await this.convertPlanToExecutable(\n plans,\n planningModel,\n locateModel,\n {\n cacheable,\n multimodalPrompt: userPromptToMultimodalPrompt(userPrompt),\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(\n runner.tasks.slice(taskCountBeforeRun),\n ),\n );\n } catch (error: any) {\n // A completed action must not be replayed because readiness failed.\n if (isActionReadinessError(error)) throw error;\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 (\n errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop\n ) {\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\n // Increment replan count for next iteration\n ++replanCount;\n\n if (replanCount > replanningCycleLimit) {\n const errorMsg = `Task stopped: the planning cycle limit (${replanningCycleLimit}) has been reached. This limit prevents the model from getting stuck in an endless planning loop. If your task requires more planning cycles, increase replanningCycleLimit or set the environment variable MIDSCENE_REPLANNING_CYCLE_LIMIT to a higher value. See https://midscenejs.com/zh/reference/#common for details.`;\n return appendFailedPlan(errorMsg, planIndex);\n }\n\n if (\n !planResult?.delegation &&\n !conversationHistory.pendingFeedbackMessage\n ) {\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 rawAssistantOutput: dump.taskInfo?.rawAssistantOutput,\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 type === 'Boolean' || type === 'Assert' || type === 'WaitFor'\n ? 'boolean'\n : 'extract',\n opt,\n extraPageDescription,\n multimodalPrompt,\n uiContext,\n {\n ...executionOptions,\n abortSignal: executionOptions?.abortSignal ?? taskContext.signal,\n },\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 abortSignal =\n executionOptions?.abortSignal ?? this.getAbortSignal?.();\n abortSignal?.throwIfAborted();\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 abortSignal,\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, abortSignal },\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 abortSignal = this.getAbortSignal?.();\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, abortSignal },\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 abortSignal?.throwIfAborted();\n const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\n { abortSignal },\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 { abortSignal },\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":["__webpack_require__","definition","key","Object","obj","prop","Symbol","debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","requestedLimit","limit","Number","Math","TaskExecutor","title","options","session","ExecutionSession","signal","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","planningFeedbackMaxLength","undefined","format","getReadableTimeString","plans","planningModel","locateModel","userInstruction","yamlString","reportOptions","taskTitleStr","userPromptToString","userPromptToMultimodalPrompt","task","executorContext","uiContext","assert","ms","abortSignal","action","defineActionSleep","setTimingFieldOnce","executionPlanningModel","executionLocateModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","noIndividualLocateModel","planningConfig","locateConfig","sameSystemOneModel","bothJev","includeLocateInPlanning","imagesIncludeCount","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","getPreparedUserPrompt","promise","prepareUserPrompt","delegation","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","Array","console","modelRuntime","base","usage","suggestedAction","planningAdvice","JSON","planImpl","standardPlan","planResult","preparedUserPrompt","renderAIContext","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","actions","thought","log","memory","rawResponse","rawAssistantOutput","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","isActionReadinessError","String","type","demand","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":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,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,GAAGA,KAAK,KAAK;QACvB,IAAI,CAAC,cAAc,GAAGA,KAAK,cAAc;QACzC,IAAI,CAAC,mBAAmB,GAAGA,KAAK,WAAW;QAC3C,IAAI,CAAC,WAAW,GAAG,IAAIC,yCAAAA,WAAWA,CAAC;YACjC,wBAAwBD,KAAK,sBAAsB;YACnDF;YACAC;YACA,WAAWC,KAAK,SAAS;YACzB,aAAa,IAAI,CAAC,cAAc;YAChC,iBAAiBA,KAAK,eAAe;YACrC,iBAAiBA,KAAK,eAAe;YACrC,mBAAmBA,KAAK,iBAAiB;QAC3C;IACF;AAolCF;AAkBO,SAASzB,mCACd7G,IAAmB,EACnBE,SAAgC;IAEhC,MAAMsI,SAAStI,WAAW;IAC1B,IAAIsI,UAAUA,OAAO,MAAM,GAAG,GAAG;QAC/B,MAAMC,gBAAyC,EAAE;QACjD,IAAK,IAAInH,IAAI,GAAGA,IAAIkH,OAAO,MAAM,GAAG,GAAGlH,IAAK;YAC1C,MAAMoH,QAAQF,MAAM,CAAClH,EAAE;YACvBmH,cAAc,IAAI,CAAC;gBACjB,MAAM;gBACN,IAAIC,MAAM,UAAU;gBACpB,YAAYA;gBACZ,aAAa,CAAC,eAAe,EAAEpH,IAAI,EAAE,CAAC,EAAEkH,OAAO,MAAM,EAAE;gBACvD,QAAQ;YACV;QACF;QAKAxI,KAAK,QAAQ,GAAGA,KAAK,QAAQ,GACzB;eAAIyI;eAAkBzI,KAAK,QAAQ;SAAC,GACpCyI;IACN;IACA,IAAIvI,WAAW,oBACbA,UAAU,kBAAkB,GAAGd;AAEnC"}
@@ -193,7 +193,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
193
193
  return;
194
194
  }
195
195
  }
196
- const getMidsceneVersion = ()=>"1.16.5";
196
+ const getMidsceneVersion = ()=>"1.17.0";
197
197
  const parsePrompt = (prompt)=>{
198
198
  if ('string' == typeof prompt) return {
199
199
  textPrompt: prompt,
@@ -40,7 +40,7 @@ const index_js_namespaceObject = require("../../service/index.js");
40
40
  var index_js_default = /*#__PURE__*/ __webpack_require__.n(index_js_namespaceObject);
41
41
  const external_models_index_js_namespaceObject = require("../models/index.js");
42
42
  const external_service_caller_index_js_namespaceObject = require("../service-caller/index.js");
43
- const system_one_js_namespaceObject = require("../service-caller/system-one.js");
43
+ const schema_js_namespaceObject = require("../service-caller/system-one/schema.js");
44
44
  const external_fixture_js_namespaceObject = require("./fixture.js");
45
45
  const TEXT_EXPECTED_TOKEN = 'CONNECTIVITY_OK';
46
46
  function isFiniteNumber(value) {
@@ -91,7 +91,17 @@ async function runTextConnectivityCheck(modelRuntime) {
91
91
  const startTime = Date.now();
92
92
  try {
93
93
  const isJev = 'jev' === modelRuntime.config.modelFamily;
94
- const result = await (0, external_service_caller_index_js_namespaceObject.callAI)([
94
+ const result = await (isJev ? (0, external_service_caller_index_js_namespaceObject.callSystemOneAI)({
95
+ state: {
96
+ token: TEXT_EXPECTED_TOKEN
97
+ },
98
+ questions: {
99
+ result: {
100
+ type: 'noul',
101
+ instructions: `Does token equal ${TEXT_EXPECTED_TOKEN}?`
102
+ }
103
+ }
104
+ }, modelRuntime) : (0, external_service_caller_index_js_namespaceObject.callGenerativeAI)([
95
105
  {
96
106
  role: 'system',
97
107
  content: 'Reply with the exact token the user asks for.'
@@ -100,21 +110,9 @@ async function runTextConnectivityCheck(modelRuntime) {
100
110
  role: 'user',
101
111
  content: `Return exactly ${TEXT_EXPECTED_TOKEN}`
102
112
  }
103
- ], modelRuntime, isJev ? {
104
- systemOneRequest: {
105
- state: {
106
- token: TEXT_EXPECTED_TOKEN
107
- },
108
- questions: {
109
- result: {
110
- type: 'noul',
111
- instructions: `Does token equal ${TEXT_EXPECTED_TOKEN}?`
112
- }
113
- }
114
- }
115
- } : void 0);
113
+ ], modelRuntime));
116
114
  const content = result.content.trim();
117
- const answer = isJev ? system_one_js_namespaceObject.systemOneResponseSchema.parse(JSON.parse(content)).answers.result : void 0;
115
+ const answer = isJev ? schema_js_namespaceObject.systemOneResponseSchema.parse(JSON.parse(content)).answers.result : void 0;
118
116
  const passed = isJev ? answer?.type === 'noul' && answer.noul >= 0.5 : content.includes(TEXT_EXPECTED_TOKEN);
119
117
  return buildCheckResult('text', modelRuntime, {
120
118
  passed,
@@ -132,12 +130,19 @@ async function runTextConnectivityCheck(modelRuntime) {
132
130
  async function runVisionConnectivityCheck(modelRuntime) {
133
131
  const startTime = Date.now();
134
132
  try {
135
- if (modelRuntime.adapter.insight.booleanFn) await new (index_js_default())(buildFixtureContext()).extract({
136
- Boolean: 'Does this screenshot show a form?'
137
- }, modelRuntime, {
138
- screenshotIncluded: true
139
- }, void 0, void 0, buildFixtureContext());
140
- else await (0, external_service_caller_index_js_namespaceObject.callAI)([
133
+ if ('jev' === modelRuntime.config.modelFamily) await (0, external_service_caller_index_js_namespaceObject.callSystemOneAI)({
134
+ state: {},
135
+ images: {
136
+ screenshot: external_fixture_js_namespaceObject.CONNECTIVITY_FIXTURE_IMAGE
137
+ },
138
+ questions: {
139
+ result: {
140
+ type: 'noul',
141
+ instructions: 'Does `screenshot` show a form?'
142
+ }
143
+ }
144
+ }, modelRuntime);
145
+ else await (0, external_service_caller_index_js_namespaceObject.callGenerativeAI)([
141
146
  {
142
147
  role: 'user',
143
148
  content: [