@autotest/agent 0.0.6 → 0.0.8

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