@autotest/agent 0.0.3 → 0.0.5

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 (69) hide show
  1. package/README.md +130 -75
  2. package/dist/api/agent_api.d.ts +2 -6
  3. package/dist/api/agent_api.js +6 -11
  4. package/dist/autotest-cli.js +9 -2
  5. package/dist/common/config/config.yaml +134 -0
  6. package/dist/common/model/custom_model.js +63 -5
  7. package/dist/common/path_utils.d.ts +7 -3
  8. package/dist/common/path_utils.js +12 -5
  9. package/dist/common/result_parser.js +1 -1
  10. package/dist/core/agent/layered_agent/decision.js +61 -23
  11. package/dist/core/agent/layered_agent/execute_agent/general_agent.js +1 -1
  12. package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.d.ts +1 -1
  13. package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.js +5 -5
  14. package/dist/core/agent/layered_agent/execute_agent/parser/general_parser.js +1 -1
  15. package/dist/core/agent/layered_agent/execute_agent/parser/glm_parser.js +1 -1
  16. package/dist/core/agent/layered_agent/execute_agent/parser/mai_ui_parser.js +1 -1
  17. package/dist/core/agent/layered_agent/execute_agent/prompts.d.ts +1 -1
  18. package/dist/core/agent/layered_agent/execute_agent/prompts.js +5 -5
  19. package/dist/core/mcp/mcp_tools.d.ts +19 -2
  20. package/dist/core/mcp/mcp_tools.js +40 -12
  21. package/dist/core/memory/_utils.d.ts +18 -0
  22. package/dist/core/memory/_utils.js +140 -0
  23. package/dist/core/memory/replan_manager.d.ts +9 -0
  24. package/dist/core/memory/replan_manager.js +12 -0
  25. package/dist/core/memory/tool_player_popup.d.ts +66 -0
  26. package/dist/core/memory/tool_player_popup.js +276 -0
  27. package/dist/core/memory/tool_player_replan.d.ts +49 -0
  28. package/dist/core/memory/tool_player_replan.js +226 -0
  29. package/dist/core/memory/tool_player_xpath.d.ts +52 -0
  30. package/dist/core/memory/tool_player_xpath.js +139 -0
  31. package/dist/core/prompt/prompt_loader.js +3 -1
  32. package/dist/core/prompt/templates/debug/hypium/hypium_v2.0_optimize_scroll_search.md +310 -0
  33. package/dist/core/prompt/templates/debug/hypium/hypium_v2.0_relative_1000.md +284 -0
  34. package/dist/core/prompt/templates/debug/planner/planner_v3.0.md +140 -0
  35. package/dist/core/prompt/templates/debug/single/single_v2.0_optimize_scroll_search.md +272 -0
  36. package/dist/core/prompt/templates/debug/single/single_v2.0_relative_1000.md +277 -0
  37. package/dist/core/prompt/templates/single/single_v2.0_0_1000.md +315 -0
  38. package/dist/core/skill/skill_manager.js +4 -1
  39. package/dist/core/skill/skills/cancel-all-follows/SKILL.md +23 -0
  40. package/dist/core/skill/skills/create-local-image/SKILL.md +12 -0
  41. package/dist/core/skill/skills/create-local-video/SKILL.md +12 -0
  42. package/dist/core/skill/skills/dismiss-popups/SKILL.md +39 -0
  43. package/dist/core/skill/skills/douyin_test_skills.md +16 -0
  44. package/dist/data_types/case.d.ts +32 -0
  45. package/dist/data_types/case.js +57 -0
  46. package/dist/data_types/index.d.ts +2 -0
  47. package/dist/data_types/index.js +6 -1
  48. package/dist/data_types/screen.d.ts +12 -0
  49. package/dist/data_types/screen.js +23 -0
  50. package/dist/mcp-server/types.js +72 -50
  51. package/dist/reporter/generator.d.ts +0 -14
  52. package/dist/reporter/generator.js +18 -504
  53. package/dist/reporter/html_template/index.d.ts +56 -0
  54. package/dist/reporter/html_template/index.js +524 -0
  55. package/dist/reporter/json_report.d.ts +1 -0
  56. package/dist/reporter/json_report.js +6 -0
  57. package/dist/reporter/types.d.ts +1 -0
  58. package/dist/reporter/types.js +1 -0
  59. package/dist/tools/batch_runner.d.ts +3 -1
  60. package/dist/tools/batch_runner.js +21 -6
  61. package/dist/tools/case_runner/report.d.ts +9 -0
  62. package/dist/tools/case_runner/report.js +264 -0
  63. package/dist/tools/case_runner/runner.d.ts +57 -0
  64. package/dist/tools/case_runner/runner.js +410 -0
  65. package/dist/tools/config/config_tool.d.ts +13 -0
  66. package/dist/tools/config/config_tool.js +339 -0
  67. package/dist/tools/prompt_compare/compare_runner.d.ts +13 -0
  68. package/dist/tools/prompt_compare/compare_runner.js +360 -0
  69. package/package.json +7 -3
@@ -41,7 +41,9 @@ var __importStar = (this && this.__importStar) || (function () {
41
41
  })();
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
43
  exports.loadSkill = exports.login = exports.goHome = exports.wait = exports.goBackTwice = exports.goBack = exports.clearApp = exports.stopApp = exports.startApp = exports.chat = exports.TOOL_REGISTRY = void 0;
44
+ exports.addToBlacklist = addToBlacklist;
44
45
  exports.collectFunctionTool = collectFunctionTool;
46
+ exports.getToolEntries = getToolEntries;
45
47
  exports.getRegisteredTools = getRegisteredTools;
46
48
  exports.getPackageNameMap = getPackageNameMap;
47
49
  exports.getMainAbilityForBundle = getMainAbilityForBundle;
@@ -55,13 +57,39 @@ const types_1 = require("../../reporter/types");
55
57
  const custom_model_1 = require("../../common/model/custom_model");
56
58
  /** Registry of all collected tool functions, keyed by name. */
57
59
  exports.TOOL_REGISTRY = {};
60
+ /** Ordered list of tool entries with metadata (aligned with python _GLOBAL_TOOL_REGISTRY). */
61
+ const _TOOL_ENTRIES = [];
62
+ /** Tool blacklist — names excluded from getToolEntries() (aligned with python _TOOL_BLACKLIST). */
63
+ const _TOOL_BLACKLIST = new Set(['login']);
64
+ /** Add tool names to the blacklist. */
65
+ function addToBlacklist(...names) {
66
+ for (const n of names)
67
+ _TOOL_BLACKLIST.add(n);
68
+ logger_1.logger.debug(`[ToolRegistry] Blacklisted: ${names.join(', ')}`);
69
+ }
58
70
  /**
59
- * Register a tool function into {@link TOOL_REGISTRY} and return it.
71
+ * Register a tool function with metadata into the registry.
72
+ * Aligned with python collect_function_tool — stores both the function and
73
+ * its description/parameters so collectAllTools can build the Available Tools
74
+ * list dynamically instead of a hardcoded array.
60
75
  */
61
- function collectFunctionTool(name, fn) {
76
+ function collectFunctionTool(name, fn, meta) {
62
77
  exports.TOOL_REGISTRY[name] = fn;
78
+ _TOOL_ENTRIES.push({
79
+ name,
80
+ description: meta?.description ?? `${name} tool`,
81
+ parameters: meta?.parameters ?? {},
82
+ fn,
83
+ });
84
+ logger_1.logger.debug(`[ToolRegistry] Registered: ${name}`);
63
85
  return fn;
64
86
  }
87
+ /** Get all registered tool entries, excluding blacklisted ones. */
88
+ function getToolEntries() {
89
+ if (_TOOL_BLACKLIST.size === 0)
90
+ return [..._TOOL_ENTRIES];
91
+ return _TOOL_ENTRIES.filter((e) => !_TOOL_BLACKLIST.has(e.name));
92
+ }
65
93
  /** Get all registered tool functions. */
66
94
  function getRegisteredTools() {
67
95
  return Object.values(exports.TOOL_REGISTRY);
@@ -108,7 +136,7 @@ exports.chat = collectFunctionTool('chat', async (message) => {
108
136
  _chatLock = null;
109
137
  resolveLock('');
110
138
  }
111
- });
139
+ }, { description: 'Send a sub-task instruction to the executor (describe what to do in natural language, e.g. click a button, swipe, input text). The executor will look at the screen and perform the actual operation', parameters: { message: 'string' } });
112
140
  async function _doChat(message) {
113
141
  logger_1.logger.info(`\n[Executor] Running: ${message}`);
114
142
  const executorAgent = getExecutorAgent();
@@ -207,7 +235,7 @@ async function doStartApp(appName) {
207
235
  /** Start an app by display name or bundle name. */
208
236
  exports.startApp = collectFunctionTool('start_app', async (appName) => {
209
237
  return doStartApp(appName);
210
- });
238
+ }, { description: 'Start an application by display name or bundle name', parameters: { app_name: 'string' } });
211
239
  /** Stop an app by display name or bundle name. */
212
240
  exports.stopApp = collectFunctionTool('stop_app', async (appName) => {
213
241
  const device = getExecutorDevice();
@@ -219,7 +247,7 @@ exports.stopApp = collectFunctionTool('stop_app', async (appName) => {
219
247
  await device.home();
220
248
  }
221
249
  return `stop ${appName} successfully. Task finished. Please output the final result now.`;
222
- });
250
+ }, { description: 'Stop an application by display name or bundle name', parameters: { app_name: 'string' } });
223
251
  /** Clear an app's data to simulate a first-install state. */
224
252
  exports.clearApp = collectFunctionTool('clear_app', async (appName) => {
225
253
  const device = getExecutorDevice();
@@ -230,12 +258,12 @@ exports.clearApp = collectFunctionTool('clear_app', async (appName) => {
230
258
  // ignore
231
259
  }
232
260
  return `clear ${appName} successfully`;
233
- });
261
+ }, { description: 'Clear an application data to simulate first-install state', parameters: { app_name: 'string' } });
234
262
  /** Press the back button once. */
235
263
  exports.goBack = collectFunctionTool('go_back', async () => {
236
264
  await getExecutorDevice().back();
237
265
  return 'go back successfully';
238
- });
266
+ }, { description: 'Press the back button once', parameters: {} });
239
267
  /** Press the back button twice. */
240
268
  exports.goBackTwice = collectFunctionTool('go_back_twice', async () => {
241
269
  const device = getExecutorDevice();
@@ -243,7 +271,7 @@ exports.goBackTwice = collectFunctionTool('go_back_twice', async () => {
243
271
  await sleep(1);
244
272
  await device.back();
245
273
  return 'go back twice successfully';
246
- });
274
+ }, { description: 'Press the back button twice', parameters: {} });
247
275
  /** Wait for a number of seconds. */
248
276
  exports.wait = collectFunctionTool('wait', async (times) => {
249
277
  await sleep(times);
@@ -252,16 +280,16 @@ exports.wait = collectFunctionTool('wait', async (times) => {
252
280
  seconds: times,
253
281
  message: `wait ${times} seconds successfully`,
254
282
  });
255
- });
283
+ }, { description: 'Wait for a specified number of seconds', parameters: { times: 'number' } });
256
284
  /** Press the home button to return to the desktop. */
257
285
  exports.goHome = collectFunctionTool('go_home', async () => {
258
286
  await getExecutorDevice().home();
259
287
  return 'go home successfully';
260
- });
288
+ }, { description: 'Press the home button to return to the desktop', parameters: {} });
261
289
  /** Login placeholder tool. */
262
290
  exports.login = collectFunctionTool('login', async () => {
263
291
  return JSON.stringify({ action: 'login', message: 'login successfully' });
264
- });
292
+ }, { description: 'Login placeholder tool', parameters: {} });
265
293
  /** Resolve the main ability name for a bundle name. */
266
294
  function getMainAbilityForBundle(bundleName) {
267
295
  return getMainAbility(bundleName);
@@ -278,7 +306,7 @@ exports.loadSkill = collectFunctionTool('load_skill', async (skillName) => {
278
306
  return `Skill '${skillName}' loaded successfully. Content:\n\n${content}`;
279
307
  }
280
308
  return `Skill '${skillName}' not found. Please check the skill name.`;
281
- });
309
+ }, { description: 'Load the detailed steps for a named skill', parameters: { skill_name: 'string' } });
282
310
  /**
283
311
  * Verify the task result based on recent execution history (screenshots + logs).
284
312
  * @param verificationDescription What to verify.
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Internal utility functions shared across memory module.
3
+ *
4
+ * Ported from python core/memory/_utils.py.
5
+ * Provides helpers for response text extraction, message filtering, retry
6
+ * decoration, and a lightweight TimeCalculate class used by ToolPlayer.
7
+ */
8
+ export declare function fallbackToGlobal<T>(config: unknown, extractor: (cfg: unknown) => T, validator?: ((value: T) => boolean) | null, label?: string, globalConfig?: unknown): T | null;
9
+ export declare function isValidModelConfig(modelConfig: unknown): boolean;
10
+ export declare function extractTextFromResponse(response: unknown): string;
11
+ export declare function filterImagesFromMessage(message: unknown): unknown;
12
+ export declare function retryOnException<T>(fn: () => Promise<T>, maxRetries?: number, delay?: number, backoff?: number): Promise<T>;
13
+ export declare class TimeCalculate {
14
+ startTime: Date;
15
+ endTime: Date;
16
+ constructor(startTime?: Date, endTime?: Date);
17
+ get duration(): number;
18
+ }
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ /**
3
+ * Internal utility functions shared across memory module.
4
+ *
5
+ * Ported from python core/memory/_utils.py.
6
+ * Provides helpers for response text extraction, message filtering, retry
7
+ * decoration, and a lightweight TimeCalculate class used by ToolPlayer.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.TimeCalculate = void 0;
11
+ exports.fallbackToGlobal = fallbackToGlobal;
12
+ exports.isValidModelConfig = isValidModelConfig;
13
+ exports.extractTextFromResponse = extractTextFromResponse;
14
+ exports.filterImagesFromMessage = filterImagesFromMessage;
15
+ exports.retryOnException = retryOnException;
16
+ const logger_1 = require("../../common/logger");
17
+ function fallbackToGlobal(config, extractor, validator = null, label = '', globalConfig) {
18
+ const isValid = (value) => {
19
+ if (validator)
20
+ return validator(value);
21
+ return value !== null && value !== undefined;
22
+ };
23
+ let result = null;
24
+ if (config !== null && config !== undefined) {
25
+ try {
26
+ result = extractor(config);
27
+ }
28
+ catch (e) {
29
+ logger_1.logger.debug(`Failed to extract ${label} from passed config: ${e instanceof Error ? e.message : String(e)}`);
30
+ }
31
+ }
32
+ if (isValid(result))
33
+ return result;
34
+ if (globalConfig !== null && globalConfig !== undefined && globalConfig !== config) {
35
+ try {
36
+ result = extractor(globalConfig);
37
+ }
38
+ catch (e) {
39
+ logger_1.logger.debug(`Failed to extract ${label} from global config: ${e instanceof Error ? e.message : String(e)}`);
40
+ return null;
41
+ }
42
+ if (isValid(result)) {
43
+ logger_1.logger.info(`${label} not found in passed config, using global config`);
44
+ return result;
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+ function isValidModelConfig(modelConfig) {
50
+ if (!modelConfig || typeof modelConfig !== 'object')
51
+ return false;
52
+ const cfg = modelConfig;
53
+ return Boolean(cfg['name']) && Boolean(cfg['baseUrl'] || cfg['base_url']);
54
+ }
55
+ function extractTextFromResponse(response) {
56
+ if (!response || typeof response !== 'object')
57
+ return '';
58
+ const output = response['output'];
59
+ if (!Array.isArray(output))
60
+ return '';
61
+ const textParts = [];
62
+ for (const item of output) {
63
+ if (!item || typeof item !== 'object')
64
+ continue;
65
+ const itemType = item['type'];
66
+ if (itemType === 'reasoning') {
67
+ const summary = item['summary'];
68
+ if (Array.isArray(summary)) {
69
+ const thinkingParts = [];
70
+ for (const s of summary) {
71
+ if (s && typeof s === 'object' && s['type'] === 'summary_text') {
72
+ thinkingParts.push(String(s['text'] ?? ''));
73
+ }
74
+ }
75
+ if (thinkingParts.length) {
76
+ logger_1.logger.debug(`\n[Model Thinking]\n${thinkingParts.join('')}`);
77
+ }
78
+ }
79
+ }
80
+ if (itemType === 'message' && item['role'] === 'assistant') {
81
+ const content = item['content'];
82
+ if (Array.isArray(content)) {
83
+ for (const c of content) {
84
+ if (c && typeof c === 'object' && c['type'] === 'output_text') {
85
+ textParts.push(String(c['text'] ?? ''));
86
+ }
87
+ }
88
+ }
89
+ }
90
+ }
91
+ return textParts.join('');
92
+ }
93
+ function filterImagesFromMessage(message) {
94
+ if (!message || typeof message !== 'object')
95
+ return message;
96
+ if (Array.isArray(message))
97
+ return [...message];
98
+ const filtered = { ...message };
99
+ const content = filtered['content'];
100
+ if (Array.isArray(content)) {
101
+ filtered['content'] = content.filter((item) => {
102
+ if (item && typeof item === 'object') {
103
+ const type = item['type'];
104
+ return type !== 'input_image' && type !== 'image_url';
105
+ }
106
+ return true;
107
+ });
108
+ }
109
+ return filtered;
110
+ }
111
+ function retryOnException(fn, maxRetries = 3, delay = 1000, backoff = 2) {
112
+ return (async () => {
113
+ let currentDelay = delay;
114
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
115
+ try {
116
+ return await fn();
117
+ }
118
+ catch (e) {
119
+ if (attempt === maxRetries - 1)
120
+ throw e;
121
+ logger_1.logger.warning(`retry failed (attempt ${attempt + 1}/${maxRetries}): ${e instanceof Error ? e.message : String(e)}`);
122
+ await new Promise((resolve) => setTimeout(resolve, currentDelay));
123
+ currentDelay *= backoff;
124
+ }
125
+ }
126
+ throw new Error('unreachable');
127
+ })();
128
+ }
129
+ class TimeCalculate {
130
+ startTime;
131
+ endTime;
132
+ constructor(startTime, endTime) {
133
+ this.startTime = startTime ?? new Date();
134
+ this.endTime = endTime ?? new Date();
135
+ }
136
+ get duration() {
137
+ return (this.endTime.getTime() - this.startTime.getTime()) / 1000;
138
+ }
139
+ }
140
+ exports.TimeCalculate = TimeCalculate;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Replan manager facade.
3
+ *
4
+ * Ported from python core/memory/replan_manager.py.
5
+ * Re-exports the replan functionality from tool_player_replan so callers
6
+ * can import it from core/memory/replan_manager.
7
+ */
8
+ export { ReplanMixin } from './tool_player_replan';
9
+ export type { FailureInfo, RecordingRecord, ReplanHost } from './tool_player_replan';
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ /**
3
+ * Replan manager facade.
4
+ *
5
+ * Ported from python core/memory/replan_manager.py.
6
+ * Re-exports the replan functionality from tool_player_replan so callers
7
+ * can import it from core/memory/replan_manager.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.ReplanMixin = void 0;
11
+ var tool_player_replan_1 = require("./tool_player_replan");
12
+ Object.defineProperty(exports, "ReplanMixin", { enumerable: true, get: function () { return tool_player_replan_1.ReplanMixin; } });
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Popup handling and LLM screenshot analysis mixin for ToolPlayer.
3
+ *
4
+ * Ported from python core/memory/tool_player_popup.py.
5
+ * Detects unexpected popups during playback via LLM screenshot analysis,
6
+ * closes them, and retries the failed step. Also handles skipping popup
7
+ * steps that are no longer relevant.
8
+ *
9
+ * Uses the Node.js LLMCaller instead of direct OpenAI client.
10
+ */
11
+ import type { ModelConfig } from '../../common/config/types';
12
+ interface PopupConfig {
13
+ enabled: boolean;
14
+ maxRetryAttempts: number;
15
+ skipPopupSteps: boolean;
16
+ }
17
+ interface PopupHost {
18
+ device: {
19
+ callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
20
+ getScreenshot?: () => Promise<{
21
+ base64Data?: string;
22
+ width?: number;
23
+ height?: number;
24
+ }>;
25
+ };
26
+ modelConfig?: ModelConfig;
27
+ popupConfig: PopupConfig;
28
+ popupStats: {
29
+ detected: number;
30
+ closed: number;
31
+ skipped: number;
32
+ retrySuccess: number;
33
+ retryFailed: number;
34
+ };
35
+ currentSession: {
36
+ recordings: Array<Record<string, unknown>>;
37
+ } | null;
38
+ currentRecordings: Array<Record<string, unknown>>;
39
+ currentIndex: number;
40
+ executeToolAsync?: (toolName: string, args: Record<string, unknown>, clickCache?: unknown) => Promise<string>;
41
+ }
42
+ interface PopupInfo {
43
+ popupType: string;
44
+ action: string;
45
+ deviceX: number;
46
+ deviceY: number;
47
+ }
48
+ interface StepAnalysis {
49
+ isPopupOperation: boolean;
50
+ hasPopup: boolean;
51
+ deviceX: number;
52
+ deviceY: number;
53
+ popupType: string;
54
+ }
55
+ export declare class PopupMixin {
56
+ protected host: PopupHost;
57
+ constructor(host: PopupHost);
58
+ analyzeScreenshotWithLlm(prompt: string): Promise<string>;
59
+ retryFailedStep(failedStepIndex: number): Promise<boolean>;
60
+ isPopupStillExists(): Promise<PopupInfo | null>;
61
+ handleUnexpectedPopup(failedStepIndex: number): Promise<boolean>;
62
+ tryResolveStepFailure(failedStepIndex: number, recording: Record<string, unknown>, arguments_: Record<string, unknown>): Promise<'skip' | 'retry_success' | 'failed'>;
63
+ analyzeStepAndScreen(arguments_: Record<string, unknown>): Promise<StepAnalysis>;
64
+ skipPopupStep(recording: Record<string, unknown>, stepIndex: number): Promise<boolean>;
65
+ }
66
+ export {};
@@ -0,0 +1,276 @@
1
+ "use strict";
2
+ /**
3
+ * Popup handling and LLM screenshot analysis mixin for ToolPlayer.
4
+ *
5
+ * Ported from python core/memory/tool_player_popup.py.
6
+ * Detects unexpected popups during playback via LLM screenshot analysis,
7
+ * closes them, and retries the failed step. Also handles skipping popup
8
+ * steps that are no longer relevant.
9
+ *
10
+ * Uses the Node.js LLMCaller instead of direct OpenAI client.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.PopupMixin = void 0;
14
+ const logger_1 = require("../../common/logger");
15
+ const custom_model_1 = require("../../common/model/custom_model");
16
+ class PopupMixin {
17
+ host;
18
+ constructor(host) {
19
+ this.host = host;
20
+ }
21
+ async analyzeScreenshotWithLlm(prompt) {
22
+ try {
23
+ const screenshot = this.host.device.getScreenshot ? await this.host.device.getScreenshot() : null;
24
+ if (!screenshot?.base64Data) {
25
+ logger_1.logger.warning('[ToolPlayer] No screenshot available for LLM analysis');
26
+ return '';
27
+ }
28
+ if (!this.host.modelConfig) {
29
+ logger_1.logger.warning('[ToolPlayer] No model config for LLM analysis');
30
+ return '';
31
+ }
32
+ const llmCaller = new custom_model_1.LLMCaller();
33
+ const result = await llmCaller.call({
34
+ systemPrompt: 'You are a screen analysis assistant. Respond only with JSON.',
35
+ userPrompt: prompt,
36
+ modelConfig: this.host.modelConfig,
37
+ images: [{ base64Data: screenshot.base64Data, mimeType: 'image/jpeg' }],
38
+ });
39
+ logger_1.logger.info(`[ToolPlayer] LLM analysis result: ${result.text.slice(0, 200)}`);
40
+ return result.text;
41
+ }
42
+ catch (e) {
43
+ logger_1.logger.error(`[ToolPlayer] LLM screenshot analysis failed: ${e instanceof Error ? e.message : String(e)}`);
44
+ return '';
45
+ }
46
+ }
47
+ async retryFailedStep(failedStepIndex) {
48
+ try {
49
+ if (!this.host.currentSession || failedStepIndex >= this.host.currentSession.recordings.length) {
50
+ logger_1.logger.error(`[ToolPlayer] Invalid failed_step_index: ${failedStepIndex}`);
51
+ return false;
52
+ }
53
+ const originalRecording = this.host.currentSession.recordings[failedStepIndex];
54
+ const toolName = String(originalRecording['tool_name'] ?? originalRecording['toolName'] ?? '');
55
+ const arguments_ = (originalRecording['arguments'] ?? {});
56
+ const clickCache = originalRecording['click_cache'];
57
+ logger_1.logger.info(`[ToolPlayer] Retrying step ${failedStepIndex}: ${toolName}(${JSON.stringify(arguments_)})`);
58
+ if (!this.host.executeToolAsync) {
59
+ logger_1.logger.error('[ToolPlayer] executeToolAsync not available');
60
+ return false;
61
+ }
62
+ const retryResult = await this.host.executeToolAsync(toolName, arguments_, clickCache);
63
+ let isSuccess = true;
64
+ if (toolName === 'execute') {
65
+ try {
66
+ const resultData = retryResult.startsWith('{') ? JSON.parse(retryResult) : {};
67
+ if (resultData['replan_required'])
68
+ isSuccess = false;
69
+ }
70
+ catch {
71
+ if (['无法', '未找到', '不存在', '失败'].some((kw) => retryResult.includes(kw))) {
72
+ isSuccess = false;
73
+ }
74
+ }
75
+ }
76
+ const playbackRecord = {
77
+ order: originalRecording['order'] ?? failedStepIndex,
78
+ tool_name: toolName,
79
+ arguments: arguments_,
80
+ result: retryResult,
81
+ timestamp: originalRecording['timestamp'] ?? '',
82
+ click_cache: clickCache,
83
+ is_played: true,
84
+ is_retry: true,
85
+ };
86
+ if (failedStepIndex < this.host.currentRecordings.length) {
87
+ this.host.currentRecordings[failedStepIndex] = playbackRecord;
88
+ }
89
+ else {
90
+ this.host.currentRecordings.push(playbackRecord);
91
+ }
92
+ logger_1.logger.info(`[ToolPlayer] Retry step ${failedStepIndex}: ${isSuccess ? 'SUCCESS' : 'FAILED'}`);
93
+ return isSuccess;
94
+ }
95
+ catch (e) {
96
+ logger_1.logger.error(`[ToolPlayer] Retry failed step ${failedStepIndex} error: ${e instanceof Error ? e.message : String(e)}`);
97
+ return false;
98
+ }
99
+ }
100
+ async isPopupStillExists() {
101
+ try {
102
+ const screenshot = this.host.device.getScreenshot ? await this.host.device.getScreenshot() : null;
103
+ const imgWidth = screenshot?.width ?? 1080;
104
+ const imgHeight = screenshot?.height ?? 1920;
105
+ const prompt = `请仔细分析当前屏幕截图,判断是否存在弹窗(popup/dialog/alert/对话框/弹窗/系统弹窗/广告弹窗)。
106
+
107
+ 请按以下JSON格式回答(只返回JSON,不要包含其他文字):
108
+ 如果存在弹窗,请找出处理该弹窗需要点击的按钮的中心坐标(用0-1的归一化坐标表示,0=最左边/最上边,1=最右边/最下边):
109
+ {
110
+ "has_popup": true,
111
+ "popup_type": "弹窗类型(如:隐私协议确认、系统权限弹窗、广告弹窗、更新提示、确认对话框等)",
112
+ "action": "需要点击的按钮文本(如:同意、关闭、确定、取消、允许等)",
113
+ "close_x": 按钮中心的X坐标(0-1范围),
114
+ "close_y": 按钮中心的Y坐标(0-1范围)
115
+ }
116
+ 如果不存在弹窗:
117
+ {
118
+ "has_popup": false
119
+ }`;
120
+ const responseText = await this.analyzeScreenshotWithLlm(prompt);
121
+ if (!responseText)
122
+ return null;
123
+ const jsonStart = responseText.indexOf('{');
124
+ const jsonEnd = responseText.lastIndexOf('}') + 1;
125
+ if (jsonStart < 0 || jsonEnd <= jsonStart) {
126
+ logger_1.logger.warning('[ToolPlayer] Failed to parse popup detection response');
127
+ return null;
128
+ }
129
+ const result = JSON.parse(responseText.slice(jsonStart, jsonEnd));
130
+ if (result['has_popup']) {
131
+ const closeX = Number(result['close_x'] ?? 0);
132
+ const closeY = Number(result['close_y'] ?? 0);
133
+ const deviceX = Math.max(0, Math.min(Math.round(closeX * imgWidth), imgWidth - 1));
134
+ const deviceY = Math.max(0, Math.min(Math.round(closeY * imgHeight), imgHeight - 1));
135
+ const action = String(result['action'] ?? '关闭');
136
+ logger_1.logger.warning(`[ToolPlayer] Popup detected: type=${result['popup_type']}, action=${action}, ` +
137
+ `normalized (${closeX}, ${closeY}) -> device (${deviceX}, ${deviceY}), device=${imgWidth}x${imgHeight}`);
138
+ this.host.popupStats.detected++;
139
+ return {
140
+ popupType: String(result['popup_type'] ?? 'unknown'),
141
+ action,
142
+ deviceX,
143
+ deviceY,
144
+ };
145
+ }
146
+ logger_1.logger.info('[ToolPlayer] No popup detected on screen');
147
+ return null;
148
+ }
149
+ catch (e) {
150
+ logger_1.logger.warning(`[ToolPlayer] isPopupStillExists failed: ${e instanceof Error ? e.message : String(e)}`);
151
+ return null;
152
+ }
153
+ }
154
+ async handleUnexpectedPopup(failedStepIndex) {
155
+ if (!this.host.popupConfig.enabled) {
156
+ logger_1.logger.info('[ToolPlayer] Popup handling disabled, skipping');
157
+ return false;
158
+ }
159
+ const maxAttempts = this.host.popupConfig.maxRetryAttempts;
160
+ logger_1.logger.warning(`[ToolPlayer] Checking for unexpected popup (step ${failedStepIndex}, max_attempts=${maxAttempts})`);
161
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
162
+ const popupInfo = await this.isPopupStillExists();
163
+ if (!popupInfo) {
164
+ logger_1.logger.info('[ToolPlayer] No popup detected, cannot handle');
165
+ return false;
166
+ }
167
+ logger_1.logger.warning(`[ToolPlayer] Attempt ${attempt + 1}/${maxAttempts}: Handling popup - ` +
168
+ `type=${popupInfo.popupType}, action=${popupInfo.action}, device at (${popupInfo.deviceX}, ${popupInfo.deviceY})`);
169
+ try {
170
+ if (popupInfo.deviceX > 0 || popupInfo.deviceY > 0) {
171
+ await this.host.device.callTool('click', { x: popupInfo.deviceX, y: popupInfo.deviceY });
172
+ }
173
+ else {
174
+ logger_1.logger.warning('[ToolPlayer] No close coordinates from LLM, falling back to go_back');
175
+ await this.host.device.callTool('go_back', {});
176
+ }
177
+ await new Promise((resolve) => setTimeout(resolve, 1000));
178
+ const verifyResult = await this.isPopupStillExists();
179
+ if (!verifyResult) {
180
+ logger_1.logger.warning(`[ToolPlayer] Popup closed successfully on attempt ${attempt + 1}`);
181
+ this.host.popupStats.closed++;
182
+ const retrySuccess = await this.retryFailedStep(failedStepIndex);
183
+ if (retrySuccess) {
184
+ this.host.popupStats.retrySuccess++;
185
+ logger_1.logger.warning('[ToolPlayer] Retry succeeded after popup handling');
186
+ return true;
187
+ }
188
+ this.host.popupStats.retryFailed++;
189
+ logger_1.logger.warning('[ToolPlayer] Retry failed after popup handling');
190
+ return false;
191
+ }
192
+ logger_1.logger.warning(`[ToolPlayer] Popup still exists after attempt ${attempt + 1}, retrying...`);
193
+ }
194
+ catch (e) {
195
+ logger_1.logger.error(`[ToolPlayer] Failed to close popup on attempt ${attempt + 1}: ${e instanceof Error ? e.message : String(e)}`);
196
+ }
197
+ }
198
+ logger_1.logger.warning(`[ToolPlayer] Failed to handle popup after ${maxAttempts} attempts`);
199
+ return false;
200
+ }
201
+ async tryResolveStepFailure(failedStepIndex, recording, arguments_) {
202
+ if (!this.host.popupConfig.enabled)
203
+ return 'failed';
204
+ if (this.host.popupConfig.skipPopupSteps) {
205
+ const analysis = await this.analyzeStepAndScreen(arguments_);
206
+ if (analysis.isPopupOperation && (!analysis.hasPopup || (analysis.deviceX === 0 && analysis.deviceY === 0))) {
207
+ await this.skipPopupStep(recording, failedStepIndex);
208
+ return 'skip';
209
+ }
210
+ }
211
+ const handled = await this.handleUnexpectedPopup(failedStepIndex);
212
+ if (handled)
213
+ return 'retry_success';
214
+ return 'failed';
215
+ }
216
+ async analyzeStepAndScreen(arguments_) {
217
+ const empty = { isPopupOperation: false, hasPopup: false, deviceX: 0, deviceY: 0, popupType: '' };
218
+ try {
219
+ const messageText = arguments_['message'] ?? String(arguments_);
220
+ const screenshot = this.host.device.getScreenshot ? await this.host.device.getScreenshot() : null;
221
+ const imgWidth = screenshot?.width ?? 1080;
222
+ const imgHeight = screenshot?.height ?? 1920;
223
+ const prompt = `请分析以下操作步骤描述和当前屏幕截图,回答两个问题。
224
+
225
+ 问题1:该操作步骤是否与"关闭弹窗/对话框/弹窗广告/系统弹窗/权限申请弹窗"相关?
226
+ 操作描述:${messageText}
227
+
228
+ 问题2:当前屏幕截图是否存在弹窗(对话框、弹窗广告、系统权限请求、提示框等)?
229
+
230
+ 请按以下JSON格式回答(只返回JSON,不要包含其他文字):
231
+ {
232
+ "is_popup_operation": true或false,
233
+ "has_popup": true或false,
234
+ "popup_type": "如果存在弹窗,填写弹窗类型;否则填空字符串",
235
+ "close_x": 如果存在弹窗,填写处理该弹窗需要点击的按钮的X坐标(0-1归一化);否则填0,
236
+ "close_y": 如果存在弹窗,填写处理该弹窗需要点击的按钮的Y坐标(0-1归一化);否则填0
237
+ }`;
238
+ const responseText = await this.analyzeScreenshotWithLlm(prompt);
239
+ if (!responseText)
240
+ return empty;
241
+ const jsonStart = responseText.indexOf('{');
242
+ const jsonEnd = responseText.lastIndexOf('}') + 1;
243
+ if (jsonStart < 0 || jsonEnd <= jsonStart)
244
+ return empty;
245
+ const result = JSON.parse(responseText.slice(jsonStart, jsonEnd));
246
+ const closeX = Number(result['close_x'] ?? 0);
247
+ const closeY = Number(result['close_y'] ?? 0);
248
+ const deviceX = closeX ? Math.max(0, Math.min(Math.round(closeX * imgWidth), imgWidth - 1)) : 0;
249
+ const deviceY = closeY ? Math.max(0, Math.min(Math.round(closeY * imgHeight), imgHeight - 1)) : 0;
250
+ logger_1.logger.info(`[ToolPlayer] Step analysis: is_popup=${result['is_popup_operation']}, ` +
251
+ `has_popup=${result['has_popup']}, popup_type=${result['popup_type']}, device=(${deviceX}, ${deviceY})`);
252
+ return {
253
+ isPopupOperation: Boolean(result['is_popup_operation']),
254
+ hasPopup: Boolean(result['has_popup']),
255
+ deviceX,
256
+ deviceY,
257
+ popupType: String(result['popup_type'] ?? ''),
258
+ };
259
+ }
260
+ catch (e) {
261
+ logger_1.logger.warning(`[ToolPlayer] analyzeStepAndScreen failed: ${e instanceof Error ? e.message : String(e)}`);
262
+ return empty;
263
+ }
264
+ }
265
+ async skipPopupStep(recording, stepIndex) {
266
+ const args = (recording['arguments'] ?? {});
267
+ const messageText = args['message'] ?? String(recording['arguments'] ?? '');
268
+ logger_1.logger.info(`[ToolPlayer] Skipping popup step ${stepIndex}: LLM confirmed popup no longer exists (message: ${messageText.slice(0, 80)})`);
269
+ this.host.popupStats.skipped++;
270
+ recording['is_played'] = true;
271
+ recording['is_skipped'] = true;
272
+ recording['result'] = '[SKIPPED] Popup no longer exists, step skipped';
273
+ return true;
274
+ }
275
+ }
276
+ exports.PopupMixin = PopupMixin;