@autotest/agent 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) 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 +24 -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/mcp_prompts.d.ts +1 -1
  12. package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.js +5 -5
  13. package/dist/core/agent/layered_agent/execute_agent/parser/general_parser.js +1 -1
  14. package/dist/core/agent/layered_agent/execute_agent/parser/glm_parser.js +1 -1
  15. package/dist/core/agent/layered_agent/execute_agent/parser/mai_ui_parser.js +1 -1
  16. package/dist/core/agent/layered_agent/execute_agent/prompts.d.ts +1 -1
  17. package/dist/core/agent/layered_agent/execute_agent/prompts.js +5 -5
  18. package/dist/core/mcp/mcp_tools.d.ts +19 -2
  19. package/dist/core/mcp/mcp_tools.js +40 -12
  20. package/dist/core/memory/_utils.d.ts +18 -0
  21. package/dist/core/memory/_utils.js +140 -0
  22. package/dist/core/memory/replan_manager.d.ts +9 -0
  23. package/dist/core/memory/replan_manager.js +12 -0
  24. package/dist/core/memory/tool_player_popup.d.ts +66 -0
  25. package/dist/core/memory/tool_player_popup.js +276 -0
  26. package/dist/core/memory/tool_player_replan.d.ts +49 -0
  27. package/dist/core/memory/tool_player_replan.js +226 -0
  28. package/dist/core/memory/tool_player_xpath.d.ts +52 -0
  29. package/dist/core/memory/tool_player_xpath.js +139 -0
  30. package/dist/core/prompt/prompt_loader.js +3 -1
  31. package/dist/core/prompt/templates/debug/hypium/hypium_v2.0_optimize_scroll_search.md +310 -0
  32. package/dist/core/prompt/templates/debug/hypium/hypium_v2.0_relative_1000.md +284 -0
  33. package/dist/core/prompt/templates/debug/planner/planner_v3.0.md +140 -0
  34. package/dist/core/prompt/templates/debug/single/single_v2.0_optimize_scroll_search.md +272 -0
  35. package/dist/core/prompt/templates/debug/single/single_v2.0_relative_1000.md +277 -0
  36. package/dist/core/prompt/templates/single/single_v2.0_0_1000.md +315 -0
  37. package/dist/core/skill/skill_manager.js +4 -1
  38. package/dist/core/skill/skills/cancel-all-follows/SKILL.md +23 -0
  39. package/dist/core/skill/skills/create-local-image/SKILL.md +12 -0
  40. package/dist/core/skill/skills/create-local-video/SKILL.md +12 -0
  41. package/dist/core/skill/skills/dismiss-popups/SKILL.md +39 -0
  42. package/dist/core/skill/skills/douyin_test_skills.md +16 -0
  43. package/dist/data_types/case.d.ts +32 -0
  44. package/dist/data_types/case.js +57 -0
  45. package/dist/data_types/index.d.ts +2 -0
  46. package/dist/data_types/index.js +6 -1
  47. package/dist/data_types/screen.d.ts +12 -0
  48. package/dist/data_types/screen.js +23 -0
  49. package/dist/mcp-server/types.js +72 -50
  50. package/dist/reporter/generator.d.ts +0 -14
  51. package/dist/reporter/generator.js +18 -504
  52. package/dist/reporter/html_template/index.d.ts +56 -0
  53. package/dist/reporter/html_template/index.js +524 -0
  54. package/dist/reporter/json_report.d.ts +1 -0
  55. package/dist/reporter/json_report.js +6 -0
  56. package/dist/reporter/types.d.ts +1 -0
  57. package/dist/reporter/types.js +1 -0
  58. package/dist/tools/batch_runner.d.ts +3 -1
  59. package/dist/tools/batch_runner.js +13 -6
  60. package/dist/tools/case_runner/report.d.ts +9 -0
  61. package/dist/tools/case_runner/report.js +264 -0
  62. package/dist/tools/case_runner/runner.d.ts +57 -0
  63. package/dist/tools/case_runner/runner.js +410 -0
  64. package/dist/tools/config/config_tool.d.ts +13 -0
  65. package/dist/tools/config/config_tool.js +339 -0
  66. package/dist/tools/prompt_compare/compare_runner.d.ts +13 -0
  67. package/dist/tools/prompt_compare/compare_runner.js +360 -0
  68. package/package.json +7 -3
@@ -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;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Replan mixin for ToolPlayer.
3
+ *
4
+ * Ported from python core/memory/tool_player_replan.py.
5
+ * Contains the replan prompt builder and the triggerReplan method.
6
+ * Delegates to a replanCallback callable so the host application owns the
7
+ * replanning lifecycle.
8
+ */
9
+ interface RecordingRecord {
10
+ toolName?: string;
11
+ tool_name?: string;
12
+ arguments?: Record<string, unknown>;
13
+ result?: unknown;
14
+ }
15
+ interface FailureInfo {
16
+ failureReason?: string;
17
+ failure_reason?: string;
18
+ failedStep?: string;
19
+ failed_step?: string;
20
+ suggestion?: string;
21
+ failedStepIndex?: number;
22
+ failed_step_index?: number;
23
+ originalTask?: string;
24
+ original_task?: string;
25
+ }
26
+ interface ReplanHost {
27
+ replanTriggered: boolean;
28
+ replanCallback?: (prompt: string) => Promise<string>;
29
+ currentSession: {
30
+ task: string;
31
+ recordings: RecordingRecord[];
32
+ } | null;
33
+ currentRecordings: RecordingRecord[];
34
+ lastPlaybackResults: Array<Record<string, unknown>> | null;
35
+ config?: {
36
+ taskTimeout?: number;
37
+ task_timeout?: number;
38
+ };
39
+ }
40
+ export declare class ReplanMixin {
41
+ protected host: ReplanHost;
42
+ constructor(host: ReplanHost);
43
+ buildReplanPrompt(originalTask: string, fullHistory: RecordingRecord[], failureInfo: FailureInfo): string;
44
+ static formatHistoryForReplan(fullHistory: RecordingRecord[]): string;
45
+ static extractActionDescription(messageText: string): string;
46
+ static parseResultSummary(result: unknown): [string, boolean];
47
+ triggerReplan(failureInfo: FailureInfo, remainingTimeout?: number): Promise<void>;
48
+ }
49
+ export {};