@autotest/agent 0.0.5 → 0.0.7

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 (192) hide show
  1. package/README.md +10 -0
  2. package/dist/api/agent_api.d.ts +2 -2
  3. package/dist/autotest-cli.js +1 -397
  4. package/dist/common/config/config.yaml +5 -0
  5. package/dist/common/config/manager.d.ts +7 -7
  6. package/dist/common/config/types.d.ts +33 -1
  7. package/dist/common/dfx/index.d.ts +1 -1
  8. package/dist/common/image_helper.d.ts +2 -2
  9. package/dist/common/llm_cache/cache_transport.d.ts +1 -1
  10. package/dist/common/llm_cache/prompt_cache.d.ts +2 -2
  11. package/dist/common/utils.d.ts +5 -5
  12. package/dist/core/agent/layered_agent/agent_registry.d.ts +3 -1
  13. package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.d.ts +1 -1
  14. package/dist/core/agent/layered_agent/execute_agent/prompts.d.ts +1 -1
  15. package/dist/core/agent/report_analyzer_agent/prompt.d.ts +1 -1
  16. package/dist/core/agent/report_analyzer_agent/tools.d.ts +1 -1
  17. package/dist/core/agent/rewrite_agent/agent.d.ts +5 -5
  18. package/dist/core/agent/rewrite_agent/guardrails.d.ts +1 -1
  19. package/dist/core/agent/rewrite_agent/mapping.d.ts +1 -1
  20. package/dist/core/agent/rewrite_agent/parse.d.ts +1 -1
  21. package/dist/core/agent/rewrite_agent/types.d.ts +1 -1
  22. package/dist/core/agent/single_agent/agent.d.ts +2 -2
  23. package/dist/core/agent/single_agent/hook_manager.d.ts +1 -2
  24. package/dist/core/agent/single_agent/image_utils.d.ts +1 -2
  25. package/dist/core/agent/single_agent/scroll_search_agent.d.ts +5 -5
  26. package/dist/core/agent/single_agent/subagent_manager.d.ts +1 -2
  27. package/dist/core/agent/single_agent/tool_recorder_hook.d.ts +3 -3
  28. package/dist/core/device/device_protocol.d.ts +1 -1
  29. package/dist/core/device/hdc/device.d.ts +1 -1
  30. package/dist/core/device/index.d.ts +2 -2
  31. package/dist/core/knowledge/knowledge_manager.d.ts +1 -1
  32. package/dist/core/knowledge/vectordb.d.ts +1 -1
  33. package/dist/core/mcp/harmony_hdc_adapter.d.ts +1 -0
  34. package/dist/core/mcp/mcp_tools.d.ts +11 -2
  35. package/dist/core/mcp/verify_tool.d.ts +12 -0
  36. package/dist/core/memory/_utils.d.ts +1 -1
  37. package/dist/core/memory/index.d.ts +1 -1
  38. package/dist/core/memory/memory_manager.d.ts +1 -1
  39. package/dist/core/memory/replan_manager.d.ts +1 -1
  40. package/dist/core/memory/tool_player.d.ts +5 -5
  41. package/dist/core/memory/tool_player_popup.d.ts +1 -1
  42. package/dist/core/memory/tool_player_replan.d.ts +1 -1
  43. package/dist/core/memory/tool_player_xpath.d.ts +3 -3
  44. package/dist/core/prompt/prompt_loader.d.ts +1 -1
  45. package/dist/core/prompt/templates/single/single_v2.0.md +15 -0
  46. package/dist/core/skill/skill_manager.d.ts +2 -2
  47. package/dist/data_types/device.d.ts +1 -1
  48. package/dist/data_types/index.d.ts +1 -1
  49. package/dist/index.d.ts +5 -5
  50. package/dist/index.js +1 -164
  51. package/dist/loop/cli.d.ts +4 -4
  52. package/dist/loop/orchestrator.d.ts +6 -6
  53. package/dist/loop/result_writer.d.ts +1 -1
  54. package/dist/loop/types.d.ts +1 -1
  55. package/dist/tools/batch_runner.js +1 -745
  56. package/dist/tools/case_runner/report.d.ts +1 -1
  57. package/dist/tools/case_runner/runner.d.ts +3 -3
  58. package/dist/tools/case_runner/runner.js +1 -410
  59. package/dist/tools/config/config_tool.d.ts +6 -6
  60. package/dist/tools/config/config_tool.js +1 -339
  61. package/dist/tools/prompt_compare/compare_runner.d.ts +2 -2
  62. package/dist/tools/prompt_compare/compare_runner.js +1 -360
  63. package/package.json +2 -2
  64. package/dist/api/agent_api.js +0 -550
  65. package/dist/api/autotest_agent.js +0 -205
  66. package/dist/api/types.js +0 -11
  67. package/dist/common/case_manager.js +0 -91
  68. package/dist/common/collect_case.js +0 -128
  69. package/dist/common/common_errors.js +0 -66
  70. package/dist/common/config/config_validator.js +0 -28
  71. package/dist/common/config/manager.js +0 -257
  72. package/dist/common/config/output.js +0 -59
  73. package/dist/common/config/types.js +0 -184
  74. package/dist/common/dfx/client_factory.js +0 -62
  75. package/dist/common/dfx/context.js +0 -23
  76. package/dist/common/dfx/index.js +0 -15
  77. package/dist/common/dfx/recorder.js +0 -191
  78. package/dist/common/dfx/recording_fetch.js +0 -228
  79. package/dist/common/dfx/source.js +0 -13
  80. package/dist/common/image_cacher.js +0 -36
  81. package/dist/common/image_helper.js +0 -128
  82. package/dist/common/image_similarity.js +0 -171
  83. package/dist/common/llm_cache/cache_transport.js +0 -102
  84. package/dist/common/llm_cache/prompt_cache.js +0 -113
  85. package/dist/common/logger.js +0 -158
  86. package/dist/common/model/custom_model.js +0 -525
  87. package/dist/common/model/index.js +0 -5
  88. package/dist/common/path_utils.js +0 -88
  89. package/dist/common/result_parser.js +0 -49
  90. package/dist/common/usage/token_usage.js +0 -117
  91. package/dist/common/utils.js +0 -125
  92. package/dist/core/agent/layered_agent/ability_helper.js +0 -125
  93. package/dist/core/agent/layered_agent/agent.js +0 -37
  94. package/dist/core/agent/layered_agent/agent_registry.js +0 -75
  95. package/dist/core/agent/layered_agent/decision.js +0 -516
  96. package/dist/core/agent/layered_agent/execute_agent/action_handler.js +0 -155
  97. package/dist/core/agent/layered_agent/execute_agent/agent_factory.js +0 -41
  98. package/dist/core/agent/layered_agent/execute_agent/base_agent.js +0 -112
  99. package/dist/core/agent/layered_agent/execute_agent/general_agent.js +0 -207
  100. package/dist/core/agent/layered_agent/execute_agent/glm_agent.js +0 -241
  101. package/dist/core/agent/layered_agent/execute_agent/i18n.js +0 -34
  102. package/dist/core/agent/layered_agent/execute_agent/index.js +0 -67
  103. package/dist/core/agent/layered_agent/execute_agent/mai_ui_agent.js +0 -316
  104. package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.js +0 -154
  105. package/dist/core/agent/layered_agent/execute_agent/parser/general_parser.js +0 -243
  106. package/dist/core/agent/layered_agent/execute_agent/parser/glm_parser.js +0 -139
  107. package/dist/core/agent/layered_agent/execute_agent/parser/index.js +0 -9
  108. package/dist/core/agent/layered_agent/execute_agent/parser/mai_ui_parser.js +0 -94
  109. package/dist/core/agent/layered_agent/execute_agent/prompts.js +0 -109
  110. package/dist/core/agent/layered_agent/execute_agent/simple_reporter.js +0 -33
  111. package/dist/core/agent/layered_agent/execute_agent/utils.js +0 -52
  112. package/dist/core/agent/report_analyzer_agent/agent.js +0 -565
  113. package/dist/core/agent/report_analyzer_agent/config.js +0 -22
  114. package/dist/core/agent/report_analyzer_agent/data_loader.js +0 -255
  115. package/dist/core/agent/report_analyzer_agent/guardrails.js +0 -99
  116. package/dist/core/agent/report_analyzer_agent/hooks.js +0 -31
  117. package/dist/core/agent/report_analyzer_agent/index.js +0 -52
  118. package/dist/core/agent/report_analyzer_agent/key_steps_builder.js +0 -42
  119. package/dist/core/agent/report_analyzer_agent/mapping.js +0 -133
  120. package/dist/core/agent/report_analyzer_agent/parse.js +0 -375
  121. package/dist/core/agent/report_analyzer_agent/prompt.js +0 -300
  122. package/dist/core/agent/report_analyzer_agent/report_writer.js +0 -558
  123. package/dist/core/agent/report_analyzer_agent/tools.js +0 -150
  124. package/dist/core/agent/report_analyzer_agent/types.js +0 -274
  125. package/dist/core/agent/rewrite_agent/agent.js +0 -209
  126. package/dist/core/agent/rewrite_agent/guardrails.js +0 -95
  127. package/dist/core/agent/rewrite_agent/mapping.js +0 -56
  128. package/dist/core/agent/rewrite_agent/parse.js +0 -121
  129. package/dist/core/agent/rewrite_agent/types.js +0 -37
  130. package/dist/core/agent/single_agent/agent.js +0 -798
  131. package/dist/core/agent/single_agent/hook_manager.js +0 -60
  132. package/dist/core/agent/single_agent/hooks.js +0 -288
  133. package/dist/core/agent/single_agent/image_utils.js +0 -159
  134. package/dist/core/agent/single_agent/scroll_search_agent.js +0 -376
  135. package/dist/core/agent/single_agent/subagent_manager.js +0 -73
  136. package/dist/core/agent/single_agent/tool_recorder_hook.js +0 -42
  137. package/dist/core/agent/types.js +0 -2
  138. package/dist/core/agent/utils/message_builder.js +0 -138
  139. package/dist/core/device/device_protocol.js +0 -2
  140. package/dist/core/device/hdc/apps.js +0 -437
  141. package/dist/core/device/hdc/device.js +0 -219
  142. package/dist/core/device/hdc/index.js +0 -31
  143. package/dist/core/device/hdc/input.js +0 -74
  144. package/dist/core/device/hdc/screenshot.js +0 -171
  145. package/dist/core/device/index.js +0 -70
  146. package/dist/core/device/types.js +0 -2
  147. package/dist/core/knowledge/knowledge_manager.js +0 -70
  148. package/dist/core/knowledge/vectordb.js +0 -283
  149. package/dist/core/mcp/adapter_factory.js +0 -99
  150. package/dist/core/mcp/android_adapter.js +0 -286
  151. package/dist/core/mcp/base_adapter.js +0 -86
  152. package/dist/core/mcp/harmony_hdc_adapter.js +0 -782
  153. package/dist/core/mcp/ios_adapter.js +0 -286
  154. package/dist/core/mcp/local_tools.js +0 -41
  155. package/dist/core/mcp/mcp_tools.js +0 -410
  156. package/dist/core/mcp/types.js +0 -6
  157. package/dist/core/memory/_utils.js +0 -140
  158. package/dist/core/memory/compressed_session.js +0 -182
  159. package/dist/core/memory/context_compressor.js +0 -176
  160. package/dist/core/memory/index.js +0 -22
  161. package/dist/core/memory/memory_manager.js +0 -28
  162. package/dist/core/memory/reflector.js +0 -95
  163. package/dist/core/memory/replan_manager.js +0 -12
  164. package/dist/core/memory/session_factory.js +0 -29
  165. package/dist/core/memory/tool_player.js +0 -225
  166. package/dist/core/memory/tool_player_popup.js +0 -276
  167. package/dist/core/memory/tool_player_replan.js +0 -226
  168. package/dist/core/memory/tool_player_xpath.js +0 -139
  169. package/dist/core/memory/tool_recorder.js +0 -126
  170. package/dist/core/preprocessor/task_splitter.js +0 -112
  171. package/dist/core/prompt/prompt_loader.js +0 -315
  172. package/dist/core/skill/skill_manager.js +0 -302
  173. package/dist/data_types/action.js +0 -2
  174. package/dist/data_types/agent.js +0 -2
  175. package/dist/data_types/case.js +0 -57
  176. package/dist/data_types/device.js +0 -2
  177. package/dist/data_types/index.js +0 -11
  178. package/dist/data_types/report.js +0 -6
  179. package/dist/data_types/screen.js +0 -23
  180. package/dist/data_types/task.js +0 -2
  181. package/dist/loop/cli.js +0 -127
  182. package/dist/loop/orchestrator.js +0 -314
  183. package/dist/loop/result_writer.js +0 -260
  184. package/dist/loop/types.js +0 -82
  185. package/dist/mcp-server/server.js +0 -341
  186. package/dist/mcp-server/types.js +0 -224
  187. package/dist/reporter/batch_summary.js +0 -197
  188. package/dist/reporter/generator.js +0 -286
  189. package/dist/reporter/html_template/index.js +0 -524
  190. package/dist/reporter/json_report.js +0 -6
  191. package/dist/reporter/types.js +0 -45
  192. package/dist/tools/case_runner/report.js +0 -264
@@ -1,516 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DecisionPlanner = exports.MCPExecutorDevice = void 0;
4
- exports.getDeviceConfig = getDeviceConfig;
5
- exports.createClientConfig = createClientConfig;
6
- exports.collectAllTools = collectAllTools;
7
- exports.extractResult = extractResult;
8
- exports.decisionChat = decisionChat;
9
- const types_1 = require("../../../reporter/types");
10
- const logger_1 = require("../../../common/logger");
11
- const model_1 = require("../../../common/model");
12
- const cache_transport_1 = require("../../../common/llm_cache/cache_transport");
13
- const prompt_loader_1 = require("../../prompt/prompt_loader");
14
- const skill_manager_1 = require("../../skill/skill_manager");
15
- const utils_1 = require("../../../common/utils");
16
- const agent_registry_1 = require("./agent_registry");
17
- const agent_factory_1 = require("./execute_agent/agent_factory");
18
- function mkEvent(eventType, content, opts) {
19
- return {
20
- eventType,
21
- timestamp: new Date().toISOString(),
22
- content,
23
- data: opts?.data ?? {},
24
- screenshotPath: opts?.screenshotPath ?? null,
25
- stepNumber: opts?.stepNumber ?? null,
26
- };
27
- }
28
- function getDeviceConfig(args, config) {
29
- const deviceSn = args.device ?? config.device.deviceSn;
30
- const ip = args.ip ?? config.device.ip;
31
- const port = args.port ?? config.device.port;
32
- return { deviceSn, ip, port };
33
- }
34
- function createClientConfig(config) {
35
- return config.model.decision;
36
- }
37
- const DEFAULT_MCP_TOOLS = [
38
- { name: 'tap', description: 'Tap at the given coordinates. Coordinates are normalized decimals 0.0~1.0: (0.0,0.0)=top-left, (1.0,1.0)=bottom-right. Do NOT output integers like 499; use 0.499 instead', parameters: { x: 'number', y: 'number' } },
39
- { name: 'double_tap', description: 'Double tap at the given coordinates. Coordinates are normalized decimals 0.0~1.0', parameters: { x: 'number', y: 'number' } },
40
- { name: 'long_press', description: 'Long press at the given coordinates. Coordinates are normalized decimals 0.0~1.0', parameters: { x: 'number', y: 'number' } },
41
- { name: 'swipe', description: 'Swipe from start to end coordinates. Coordinates are normalized decimals 0.0~1.0: (0.0,0.0)=top-left, (1.0,1.0)=bottom-right. Do NOT output integers', parameters: { start_x: 'number', start_y: 'number', end_x: 'number', end_y: 'number' } },
42
- { name: 'back', description: 'Press back key', parameters: {} },
43
- { name: 'go_home', description: 'Go to home screen', parameters: {} },
44
- { name: 'start_app', description: 'Start an application by name', parameters: { app_name: 'string' } },
45
- { name: 'type_text', description: 'Type text into the focused input', parameters: { text: 'string' } },
46
- { name: 'chat', 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' } },
47
- { name: 'finish', description: 'Finish the task with a result message', parameters: { message: 'string' } },
48
- ];
49
- function collectAllTools(adapter) {
50
- // Try to introspect the adapter's real tool set first
51
- try {
52
- const tools = adapter.listTools?.();
53
- if (tools && tools.length > 0) {
54
- return tools;
55
- }
56
- }
57
- catch {
58
- // Adapter doesn't support listTools or not connected — fall back to defaults
59
- }
60
- // Fall back to a default set of well-known MCP tools
61
- return DEFAULT_MCP_TOOLS.map((t) => ({
62
- name: t.name,
63
- description: t.description,
64
- inputSchema: t.parameters,
65
- outputSchema: {},
66
- }));
67
- }
68
- function buildSkillsMetadata() {
69
- try {
70
- const skillManager = new skill_manager_1.SkillManager();
71
- const skills = skillManager.listSkills();
72
- if (skills.length === 0) {
73
- return '';
74
- }
75
- return skills.map((name) => `- ${name}`).join('\n');
76
- }
77
- catch {
78
- return '';
79
- }
80
- }
81
- function formatToolsForPrompt(tools) {
82
- return tools
83
- .map((t) => `- ${t.name}: ${t.description} (params: ${JSON.stringify(t.inputSchema)})`)
84
- .join('\n');
85
- }
86
- function extractFirstJsonObject(text) {
87
- const start = text.indexOf('{');
88
- if (start < 0) {
89
- return null;
90
- }
91
- let depth = 0;
92
- let inString = false;
93
- let escape = false;
94
- for (let i = start; i < text.length; i++) {
95
- const ch = text[i];
96
- if (inString) {
97
- if (escape) {
98
- escape = false;
99
- }
100
- else if (ch === '\\') {
101
- escape = true;
102
- }
103
- else if (ch === '"') {
104
- inString = false;
105
- }
106
- continue;
107
- }
108
- if (ch === '"') {
109
- inString = true;
110
- }
111
- else if (ch === '{') {
112
- depth += 1;
113
- }
114
- else if (ch === '}') {
115
- depth -= 1;
116
- if (depth === 0) {
117
- return text.slice(start, i + 1);
118
- }
119
- }
120
- }
121
- return null;
122
- }
123
- function tryParseToolCall(jsonText, fallback) {
124
- try {
125
- const parsed = JSON.parse(jsonText);
126
- const name = parsed.name ?? parsed.action ?? '';
127
- const argumentsObj = parsed.arguments ?? {};
128
- const reasoning = parsed.reasoning ?? undefined;
129
- if (name === 'finish' || name === 'answer' || name === 'terminate' || !name) {
130
- return { isFinish: true, message: argumentsObj.message ?? fallback, reasoning };
131
- }
132
- return { toolCall: { name, arguments: argumentsObj }, isFinish: false, reasoning };
133
- }
134
- catch {
135
- return null;
136
- }
137
- }
138
- function repairCoordinateJson(text) {
139
- let out = text;
140
- out = out.replace(/"x"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\}/g, '"x": $1, "y": $2}');
141
- out = out.replace(/"start_x"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*,\s*"end_x"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\}/g, '"start_x": $1, "start_y": $2, "end_x": $3, "end_y": $4}');
142
- return out;
143
- }
144
- function parsePlannerOutput(text) {
145
- const fenceMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
146
- const jsonText = fenceMatch?.[1]?.trim() ?? extractFirstJsonObject(text);
147
- if (jsonText) {
148
- const direct = tryParseToolCall(jsonText, text);
149
- if (direct)
150
- return direct;
151
- const repaired = repairCoordinateJson(jsonText);
152
- if (repaired !== jsonText) {
153
- const fixed = tryParseToolCall(repaired, text);
154
- if (fixed)
155
- return fixed;
156
- }
157
- return { isFinish: false, parseError: `Malformed planner JSON: ${jsonText}` };
158
- }
159
- return { isFinish: true, message: text };
160
- }
161
- function extractResult(output) {
162
- const passMatch = output.match(/PASS(?:\s*[::]\s*(.*))?/i);
163
- if (passMatch) {
164
- return { status: 'PASS', tip: passMatch[1]?.trim() ?? output };
165
- }
166
- const failMatch = output.match(/FAIL(?:\s*[::]\s*(.*))?/i);
167
- if (failMatch) {
168
- return { status: 'FAIL', tip: failMatch[1]?.trim() ?? output };
169
- }
170
- if (output.includes('任务结果') || output.includes('判定结果')) {
171
- if (output.includes('不通过')) {
172
- const idx = output.indexOf('任务结果') >= 0 ? output.indexOf('任务结果') : output.indexOf('判定结果');
173
- return { status: 'FAIL', tip: output.slice(idx).trim() };
174
- }
175
- if (output.includes('通过')) {
176
- const idx = output.indexOf('任务结果') >= 0 ? output.indexOf('任务结果') : output.indexOf('判定结果');
177
- return { status: 'PASS', tip: output.slice(idx).trim() };
178
- }
179
- }
180
- return { status: 'UNKNOWN', tip: output };
181
- }
182
- class MCPExecutorDevice {
183
- adapter;
184
- reportGenerator;
185
- deviceId;
186
- constructor(adapter, reportGenerator) {
187
- this.adapter = adapter;
188
- this.reportGenerator = reportGenerator;
189
- this.deviceId = 'default';
190
- }
191
- async getScreenshot(_timeout, saveToReport) {
192
- const screenshot = await this.adapter.getScreenshot();
193
- if (saveToReport && this.reportGenerator && screenshot.base64Data) {
194
- const savedPath = this.reportGenerator.saveScreenshot(screenshot.base64Data, screenshot.layoutData, 'planner');
195
- return { ...screenshot, screenshotPath: savedPath };
196
- }
197
- return screenshot;
198
- }
199
- async tap(x, y) {
200
- await this.adapter.callTool('tap', { x, y });
201
- }
202
- async doubleTap(x, y) {
203
- await this.adapter.callTool('double_tap', { x, y });
204
- }
205
- async longPress(x, y) {
206
- await this.adapter.callTool('long_press', { x, y });
207
- }
208
- async swipe(startX, startY, endX, endY) {
209
- await this.adapter.callTool('swipe', { start_x: startX, start_y: startY, end_x: endX, end_y: endY });
210
- }
211
- async typeText(text) {
212
- await this.adapter.callTool('type_text', { text });
213
- }
214
- async clearText() {
215
- await this.adapter.callTool('clear_text', {});
216
- }
217
- async back() {
218
- await this.adapter.callTool('back', {});
219
- }
220
- async home() {
221
- await this.adapter.callTool('go_home', {});
222
- }
223
- async launchApp(appName) {
224
- try {
225
- await this.adapter.callTool('start_app', { app_name: appName });
226
- return true;
227
- }
228
- catch (e) {
229
- logger_1.logger.warn(`launchApp failed: ${e instanceof Error ? e.message : String(e)}`);
230
- return false;
231
- }
232
- }
233
- async getCurrentApp() {
234
- return '';
235
- }
236
- async listTools() {
237
- return collectAllTools(this.adapter);
238
- }
239
- async callTool(toolName, toolArgs) {
240
- try {
241
- const result = await this.adapter.callTool(toolName, toolArgs);
242
- const output = typeof result === 'string' ? result : JSON.stringify(result);
243
- return { output, success: true, errorMsg: '' };
244
- }
245
- catch (e) {
246
- const errMsg = e instanceof Error ? e.message : String(e);
247
- return { output: '', success: false, errorMsg: errMsg };
248
- }
249
- }
250
- async cleanUp() {
251
- try {
252
- await this.adapter.reset();
253
- }
254
- catch {
255
- // cleanup failure is not blocking
256
- }
257
- }
258
- }
259
- exports.MCPExecutorDevice = MCPExecutorDevice;
260
- class DecisionPlanner {
261
- adapter;
262
- config;
263
- reportGenerator;
264
- hooks;
265
- llmCaller;
266
- executorAgent;
267
- stepNumber = 0;
268
- maxSteps;
269
- history = [];
270
- constructor(opts) {
271
- this.adapter = opts.adapter;
272
- this.config = opts.config;
273
- this.reportGenerator = opts.reportGenerator;
274
- this.hooks = opts.hooks;
275
- this.llmCaller = opts.llmCaller ?? new model_1.LLMCaller(new cache_transport_1.CacheTransport(this.config.agent.unified.enableCache));
276
- this.executorAgent = opts.executorAgent;
277
- this.maxSteps = this.config.agent.unified.maxSteps;
278
- }
279
- async run(task) {
280
- let finalOutput = '';
281
- let finalStatus = 'UNKNOWN';
282
- const decisionModelConfig = createClientConfig(this.config);
283
- const tools = collectAllTools(this.adapter);
284
- const toolsText = formatToolsForPrompt(tools);
285
- const skillsMetadata = buildSkillsMetadata();
286
- let systemPrompt = (0, prompt_loader_1.load)(prompt_loader_1.PromptCategory.PLANNER);
287
- if (skillsMetadata) {
288
- systemPrompt += `\n\n## Available Skills\n${skillsMetadata}`;
289
- }
290
- systemPrompt += `\n\n## Available Tools\n${toolsText}\n\n## Output Format\nReturn a single JSON object inside a json code fence: \`{"reasoning": "<先简述当前屏幕观察,再声明完成条件/异常条件检查结论>", "name": "tool_name", "arguments": {...}}\`. The "reasoning" field is mandatory — every step must state your observation and judgment before the action. To finish, use \`{"reasoning": "<判定依据>", "name": "finish", "arguments": {"message": "PASS 或 FAIL - 原因"}}\`.\n\n## Coordinate System\nAll tap/swipe coordinates MUST be normalized decimals in 0.0~1.0: (0.0,0.0)=screen top-left, (1.0,1.0)=bottom-right. Never output integers (e.g. write 0.499, not 499) — integer coordinates will be mapped off-screen and the tap will miss.`;
291
- if (this.hooks) {
292
- await this.hooks.onAgentStart('layered');
293
- }
294
- while (this.stepNumber < this.maxSteps) {
295
- this.stepNumber += 1;
296
- if (this.adapter.isAborted()) {
297
- finalOutput = 'Task stopped by user';
298
- finalStatus = 'STOP_BY_USER';
299
- break;
300
- }
301
- if (this.hooks) {
302
- await this.hooks.onLLMStart('layered', this.stepNumber);
303
- }
304
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.STEP_START, `Step ${this.stepNumber} started (layered)`, { stepNumber: this.stepNumber }));
305
- let screenshot = null;
306
- try {
307
- screenshot = await this.captureScreenshot();
308
- }
309
- catch (e) {
310
- logger_1.logger.warn(`Failed to capture screenshot: ${e instanceof Error ? e.message : String(e)}`);
311
- }
312
- const decision = await this.planStep(task, systemPrompt, decisionModelConfig, screenshot);
313
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_OUTPUT, `Planner decision: ${decision.toolCall?.name ?? (decision.parseError ? 'parse_error' : 'finish')}`, {
314
- data: {
315
- action: decision.toolCall?.name ?? (decision.parseError ? 'parse_error' : 'finish'),
316
- shouldFinish: decision.isFinish,
317
- reasoning: decision.parseError ?? decision.reasoning ?? decision.message ?? '',
318
- },
319
- stepNumber: this.stepNumber,
320
- }));
321
- if (decision.parseError) {
322
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_PARSE_ERROR, `Planner output parse error at step ${this.stepNumber}`, {
323
- data: { parseError: decision.parseError },
324
- stepNumber: this.stepNumber,
325
- }));
326
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.STEP_END, `Step ${this.stepNumber} skipped (planner output parse error, will retry next step)`, {
327
- data: { status: 'ERROR', parseError: decision.parseError },
328
- stepNumber: this.stepNumber,
329
- }));
330
- this.history.push(`Step ${this.stepNumber}: [parse error] ${decision.parseError}`);
331
- if (this.hooks) {
332
- await this.hooks.onLLMEnd('layered', this.stepNumber, { decision, executorResult: null });
333
- }
334
- continue;
335
- }
336
- if (decision.isFinish) {
337
- finalOutput = decision.message ?? '';
338
- const extracted = extractResult(finalOutput);
339
- finalStatus = extracted.status;
340
- finalOutput = extracted.tip;
341
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.STEP_END, `Step ${this.stepNumber} finished (planner decided to finish)`, {
342
- data: { status: finalStatus },
343
- stepNumber: this.stepNumber,
344
- }));
345
- break;
346
- }
347
- const executorResult = await this.executeStep(decision.toolCall, screenshot);
348
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.MCP_TOOL_END, `Executor result: ${executorResult.observation}`, {
349
- data: { success: executorResult.success, screenshotChanged: executorResult.screenshotChanged },
350
- stepNumber: this.stepNumber,
351
- }));
352
- this.history.push(`Step ${this.stepNumber}: ${decision.toolCall.name}(${JSON.stringify(decision.toolCall.arguments)}) -> ${executorResult.observation.slice(0, 200)}`);
353
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.STEP_END, `Step ${this.stepNumber} completed (layered)`, { stepNumber: this.stepNumber }));
354
- if (this.hooks) {
355
- await this.hooks.onLLMEnd('layered', this.stepNumber, { decision, executorResult });
356
- }
357
- }
358
- if (this.stepNumber >= this.maxSteps && finalStatus === 'UNKNOWN') {
359
- finalStatus = 'FAIL';
360
- finalOutput = `Max steps reached (${this.maxSteps})`;
361
- }
362
- if (this.hooks) {
363
- await this.hooks.onAgentEnd('layered', { finalOutput, status: finalStatus });
364
- }
365
- this.reportGenerator.endTask(finalOutput, finalStatus);
366
- const savedFiles = await this.reportGenerator.saveAll();
367
- return { finalOutput, status: finalStatus, savedFiles };
368
- }
369
- async captureScreenshot() {
370
- const screenshot = await this.adapter.getScreenshot();
371
- let savedPath = null;
372
- if (screenshot.base64Data) {
373
- savedPath = this.reportGenerator.saveScreenshot(screenshot.base64Data, screenshot.layoutData, `step_${this.stepNumber}`);
374
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_OBSERVATION, `Current Screen Observation for step ${this.stepNumber}`, {
375
- screenshotPath: savedPath,
376
- stepNumber: this.stepNumber,
377
- }));
378
- }
379
- return { ...screenshot, screenshotPath: savedPath };
380
- }
381
- async planStep(task, systemPrompt, modelConfig, screenshot) {
382
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_START, `Planner observing screenshot for step ${this.stepNumber}`, { stepNumber: this.stepNumber }));
383
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.LLM_CALL, `Planner LLM call for step ${this.stepNumber}`, { data: { role: 'planner' }, stepNumber: this.stepNumber }));
384
- const historyText = this.history.length > 0 ? this.history.join('\n') : 'none';
385
- const userPrompt = `Task: ${task}\n\nAction History:\n${historyText}\n\nObserve the current screenshot, state your observation and judgment (completion/exception check) in the "reasoning" field, then decide the next action. Return a single JSON object in a json code fence.`;
386
- const images = [];
387
- if (screenshot?.base64Data) {
388
- images.push({ base64Data: screenshot.base64Data, mimeType: 'image/jpeg' });
389
- }
390
- let llmResult;
391
- try {
392
- llmResult = await this.llmCaller.call({
393
- systemPrompt,
394
- userPrompt,
395
- images,
396
- modelConfig,
397
- });
398
- }
399
- catch (e) {
400
- const errMsg = e instanceof Error ? e.message : String(e);
401
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.LLM_RESPONSE, `Planner LLM error: ${errMsg}`, { data: { simulated: true, role: 'planner' }, stepNumber: this.stepNumber }));
402
- return { isFinish: true, message: `Planner error: ${errMsg}` };
403
- }
404
- const decision = parsePlannerOutput(llmResult.text);
405
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, decision.reasoning ?? llmResult.reasoning ?? llmResult.text, { stepNumber: this.stepNumber }));
406
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.LLM_RESPONSE, `Planner LLM response for step ${this.stepNumber}`, {
407
- data: { text: llmResult.text.slice(0, 200), finishReason: llmResult.finishReason, role: 'planner' },
408
- stepNumber: this.stepNumber,
409
- }));
410
- if (llmResult.tokenUsage) {
411
- this.reportGenerator.addTokenUsage(llmResult.tokenUsage, 'DecisionAgent', this.stepNumber);
412
- }
413
- return decision;
414
- }
415
- async executeStep(toolCall, screenshot) {
416
- const toolName = toolCall.name;
417
- const toolArgs = toolCall.arguments;
418
- (0, utils_1.normalizeToolCoordinates)(toolName, toolArgs);
419
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_TOOL_CALL, `Planner delegated to executor: ${toolName}`, {
420
- data: { tool_name: toolName, arguments: toolArgs, delegated: this.executorAgent != null },
421
- stepNumber: this.stepNumber,
422
- }));
423
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.MCP_TOOL_START, `Executor executing: ${toolName}`, {
424
- data: { toolName, args: toolArgs, role: 'executor' },
425
- stepNumber: this.stepNumber,
426
- }));
427
- if (this.hooks) {
428
- await this.hooks.onToolStart('layered', toolName, toolArgs);
429
- }
430
- try {
431
- let result;
432
- if (this.executorAgent) {
433
- result = await this.executorAgent.executeToolCall(toolCall, screenshot);
434
- }
435
- else {
436
- const raw = await this.adapter.callTool(toolName, toolArgs);
437
- const obs = typeof raw === 'string' ? raw : JSON.stringify(raw);
438
- result = { success: true, observation: obs, screenshotChanged: true };
439
- }
440
- if (this.hooks) {
441
- await this.hooks.onToolEnd('layered', toolName, result.observation, this.stepNumber);
442
- }
443
- return result;
444
- }
445
- catch (err) {
446
- const errMsg = err instanceof Error ? err.message : String(err);
447
- return { success: false, observation: errMsg, screenshotChanged: false };
448
- }
449
- }
450
- }
451
- exports.DecisionPlanner = DecisionPlanner;
452
- async function decisionChat(chatArgs) {
453
- const { config, adapter, reportGenerator, args, hooks, llmCaller } = chatArgs;
454
- reportGenerator.setTask(args.task);
455
- const testCase = args.caseNum ?? args.taskName ?? args.task;
456
- reportGenerator.setTestCase(testCase);
457
- reportGenerator.startTask();
458
- // Set up an executor agent and register it so hooks can access the device.
459
- const executorDevice = new MCPExecutorDevice(adapter, reportGenerator);
460
- const executorAgentConfig = { ...config.agent.unified, mode: 'layered' };
461
- const executorModelConfig = config.model.execute;
462
- const executorOpts = {
463
- modelConfig: executorModelConfig,
464
- agentConfig: executorAgentConfig,
465
- device: executorDevice,
466
- reportGenerator: reportGenerator,
467
- llmCaller: llmCaller,
468
- };
469
- let executorAgent = chatArgs.executorAgent;
470
- if (!executorAgent) {
471
- try {
472
- executorAgent = agent_factory_1.AgentFactory.create(executorModelConfig.provider, executorOpts);
473
- agent_registry_1.agentRegistry.setExecutorAgent(executorAgent);
474
- }
475
- catch (e) {
476
- logger_1.logger.warn(`Failed to create executor agent: ${e instanceof Error ? e.message : String(e)}`);
477
- }
478
- }
479
- else {
480
- agent_registry_1.agentRegistry.setExecutorAgent(executorAgent);
481
- }
482
- logger_1.logger.info(`Initializing Planner (${config.model.decision.name})...`);
483
- const planner = new DecisionPlanner({
484
- adapter,
485
- config,
486
- reportGenerator,
487
- hooks,
488
- llmCaller,
489
- executorAgent: executorAgent ?? undefined,
490
- });
491
- let result;
492
- try {
493
- if (executorAgent) {
494
- executorAgent.init();
495
- }
496
- result = await planner.run(args.task);
497
- logger_1.logger.info(`Final Result: ${result.finalOutput}`);
498
- }
499
- catch (e) {
500
- const errMsg = e instanceof Error ? e.message : String(e);
501
- logger_1.logger.error(`Error: ${errMsg}`);
502
- reportGenerator.endTask(`Error: ${errMsg}`);
503
- result = { finalOutput: `Error: ${errMsg}`, status: 'ERROR', savedFiles: {} };
504
- }
505
- finally {
506
- try {
507
- if (executorAgent) {
508
- await executorAgent.cleanUp();
509
- }
510
- }
511
- catch (e) {
512
- logger_1.logger.error(`Executor cleanup error: ${e instanceof Error ? e.message : String(e)}`);
513
- }
514
- }
515
- return result;
516
- }
@@ -1,155 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ActionHandler = void 0;
4
- const utils_1 = require("./utils");
5
- class ActionHandler {
6
- device;
7
- confirmationCallback;
8
- takeoverCallback;
9
- constructor(device, confirmationCallback, takeoverCallback) {
10
- this.device = device;
11
- this.confirmationCallback = confirmationCallback ?? this.defaultConfirmation;
12
- this.takeoverCallback = takeoverCallback ?? this.defaultTakeover;
13
- }
14
- async execute(action) {
15
- const actionType = action._metadata ?? '';
16
- if (actionType === 'finish') {
17
- return { success: true, shouldFinish: true, message: action.message };
18
- }
19
- if (actionType !== 'do') {
20
- return { success: false, shouldFinish: true, message: `Unknown action type: ${actionType}` };
21
- }
22
- const actionName = action.action;
23
- if (!actionName || typeof actionName !== 'string') {
24
- return { success: false, shouldFinish: false, message: `Unknown action: ${actionName}` };
25
- }
26
- const handler = this.getHandler(actionName);
27
- if (!handler) {
28
- return { success: false, shouldFinish: false, message: `Unknown action: ${actionName}` };
29
- }
30
- try {
31
- return await handler(action);
32
- }
33
- catch (e) {
34
- const msg = e instanceof Error ? e.message : String(e);
35
- return { success: false, shouldFinish: false, message: `Action failed: ${msg}` };
36
- }
37
- }
38
- getHandler(actionName) {
39
- const handlers = {
40
- Launch: this.handleLaunch.bind(this),
41
- Tap: this.handleTap.bind(this),
42
- Type: this.handleType.bind(this),
43
- Type_Name: this.handleType.bind(this),
44
- Swipe: this.handleSwipe.bind(this),
45
- Back: this.handleBack.bind(this),
46
- Home: this.handleHome.bind(this),
47
- 'Double Tap': this.handleDoubleTap.bind(this),
48
- 'Long Press': this.handleLongPress.bind(this),
49
- Wait: this.handleWait.bind(this),
50
- Take_over: this.handleTakeover.bind(this),
51
- Note: this.handleNote.bind(this),
52
- };
53
- return handlers[actionName] ?? null;
54
- }
55
- async handleLaunch(action) {
56
- const appName = action.app;
57
- if (!appName) {
58
- return { success: false, shouldFinish: false, message: 'No app name specified' };
59
- }
60
- const success = await this.device.launchApp(appName);
61
- if (success) {
62
- return { success: true, shouldFinish: false };
63
- }
64
- return { success: false, shouldFinish: false, message: `App not found: ${appName}` };
65
- }
66
- async handleTap(action) {
67
- const element = action.element;
68
- if (!element) {
69
- return { success: false, shouldFinish: false, message: 'No element coordinates' };
70
- }
71
- const [x, y] = element;
72
- if (action.message) {
73
- if (!this.confirmationCallback(action.message)) {
74
- return { success: false, shouldFinish: true, message: 'User cancelled sensitive operation' };
75
- }
76
- }
77
- await this.device.tap(x, y);
78
- return { success: true, shouldFinish: false };
79
- }
80
- async handleType(action) {
81
- const text = action.text ?? '';
82
- await this.device.clearText();
83
- await (0, utils_1.sleep)(0.3);
84
- await this.device.typeText(text);
85
- await (0, utils_1.sleep)(0.5);
86
- return { success: true, shouldFinish: false };
87
- }
88
- async handleSwipe(action) {
89
- const start = action.start;
90
- const end = action.end;
91
- if (!start || !end) {
92
- return { success: false, shouldFinish: false, message: 'Missing swipe coordinates' };
93
- }
94
- const [startX, startY] = start;
95
- const [endX, endY] = end;
96
- await this.device.swipe(startX, startY, endX, endY);
97
- return { success: true, shouldFinish: false };
98
- }
99
- async handleBack(_action) {
100
- await this.device.back();
101
- return { success: true, shouldFinish: false };
102
- }
103
- async handleHome(_action) {
104
- await this.device.home();
105
- return { success: true, shouldFinish: false };
106
- }
107
- async handleDoubleTap(action) {
108
- const element = action.element;
109
- if (!element) {
110
- return { success: false, shouldFinish: false, message: 'No element coordinates' };
111
- }
112
- const [x, y] = element;
113
- await this.device.doubleTap(x, y);
114
- return { success: true, shouldFinish: false };
115
- }
116
- async handleLongPress(action) {
117
- const element = action.element;
118
- if (!element) {
119
- return { success: false, shouldFinish: false, message: 'No element coordinates' };
120
- }
121
- const [x, y] = element;
122
- await this.device.longPress(x, y);
123
- return { success: true, shouldFinish: false };
124
- }
125
- async handleWait(action) {
126
- const durationStr = action.duration ?? '1 seconds';
127
- let duration = 1.0;
128
- try {
129
- duration = parseFloat(durationStr.replace('seconds', '').trim());
130
- if (Number.isNaN(duration)) {
131
- duration = 1.0;
132
- }
133
- }
134
- catch {
135
- duration = 1.0;
136
- }
137
- await (0, utils_1.sleep)(duration);
138
- return { success: true, shouldFinish: false };
139
- }
140
- async handleTakeover(action) {
141
- const message = action.message ?? 'User intervention required';
142
- this.takeoverCallback(message);
143
- return { success: true, shouldFinish: false };
144
- }
145
- async handleNote(_action) {
146
- return { success: true, shouldFinish: false };
147
- }
148
- defaultConfirmation(message) {
149
- return true;
150
- }
151
- defaultTakeover(message) {
152
- // no-op
153
- }
154
- }
155
- exports.ActionHandler = ActionHandler;