@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,59 +0,0 @@
1
- "use strict";
2
- /**
3
- * Global hook registry for cross-cutting agent hooks.
4
- *
5
- * Unlike the per-agent `AgentHooks` interface (wired directly into an agent),
6
- * HookManager is a process-wide singleton where cross-cutting hooks (e.g.
7
- * ToolRecorderHook) register themselves and get fired on every agent's
8
- * lifecycle events. Errors in one hook are isolated (logged, never crash the
9
- * agent).
10
- */
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.hookManager = void 0;
13
- const logger_1 = require("../../../common/logger");
14
- class HookManagerImpl {
15
- hooks = new Map();
16
- register(name, hook) {
17
- this.hooks.set(name, hook);
18
- logger_1.logger.debug(`HookManager: registered hook '${name}'`);
19
- }
20
- unregister(name) {
21
- this.hooks.delete(name);
22
- }
23
- clear() {
24
- this.hooks.clear();
25
- }
26
- listHooks() {
27
- return Array.from(this.hooks.keys());
28
- }
29
- /** Fire an event to all registered hooks. Errors are isolated (logged, never thrown). */
30
- async fireEvent(event, ctx = {}) {
31
- const methodName = this._eventToMethod(event);
32
- for (const [name, hook] of this.hooks) {
33
- const fn = hook[methodName];
34
- if (!fn)
35
- continue;
36
- try {
37
- await fn(ctx);
38
- }
39
- catch (e) {
40
- logger_1.logger.error(`HookManager: hook '${name}' threw on ${event}: ${e instanceof Error ? e.message : String(e)}`);
41
- }
42
- }
43
- }
44
- _eventToMethod(event) {
45
- // on_agent_start -> onAgentStart
46
- const map = {
47
- 'on_agent_start': 'onAgentStart',
48
- 'on_agent_end': 'onAgentEnd',
49
- 'on_step_start': 'onStepStart',
50
- 'on_step_end': 'onStepEnd',
51
- 'on_llm_start': 'onLLMStart',
52
- 'on_llm_end': 'onLLMEnd',
53
- 'on_tool_start': 'onToolStart',
54
- 'on_tool_end': 'onToolEnd',
55
- };
56
- return map[event];
57
- }
58
- }
59
- exports.hookManager = new HookManagerImpl();
@@ -1,288 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SingleAgentHooks = void 0;
4
- const common_errors_1 = require("../../../common/common_errors");
5
- const token_usage_1 = require("../../../common/usage/token_usage");
6
- const types_1 = require("../../../reporter/types");
7
- const logger_1 = require("../../../common/logger");
8
- function mkEvent(eventType, content, opts) {
9
- return {
10
- eventType,
11
- timestamp: new Date().toISOString(),
12
- content,
13
- data: opts?.data ?? {},
14
- screenshotPath: opts?.screenshotPath ?? null,
15
- stepNumber: opts?.stepNumber ?? null,
16
- };
17
- }
18
- const COMMON_ERRORS_PROMPT_LOCAL = common_errors_1.COMMON_ERRORS_PROMPT;
19
- function _parseThinkingContent(text) {
20
- const thinkingMatch = text.match(/<thinking>(.*?)<\/thinking>/s);
21
- if (thinkingMatch) {
22
- return thinkingMatch[1].trim();
23
- }
24
- return '';
25
- }
26
- function _parseJudgmentContent(text) {
27
- const judgmentMatch = text.match(/<judgment>(.*?)<\/judgment>/s);
28
- if (judgmentMatch) {
29
- return judgmentMatch[1].trim();
30
- }
31
- const JUDGMENT_SECTION_RE = /##\s*(?:Judgment Process|判定过程)\s*\n(.*?)(?=\n##\s|\Z)/s;
32
- const mdMatch = text.match(JUDGMENT_SECTION_RE);
33
- if (mdMatch) {
34
- return mdMatch[1].trim();
35
- }
36
- return '';
37
- }
38
- class SingleAgentHooks {
39
- adapter;
40
- reportGenerator;
41
- tokenType;
42
- toolCount;
43
- historyActions;
44
- stepStartTime;
45
- agentConfig;
46
- constructor(adapter, reportGenerator, tokenType, agentConfig) {
47
- this.adapter = adapter;
48
- this.reportGenerator = reportGenerator ?? null;
49
- this.tokenType = tokenType ?? token_usage_1.TokenUsage;
50
- this.toolCount = 0;
51
- this.historyActions = [];
52
- this.stepStartTime = 0;
53
- this.agentConfig = agentConfig ?? null;
54
- }
55
- static _stripVerdict(text) {
56
- const lines = text.split('\n');
57
- const filtered = lines.filter((l) => !(/^\s*(verdict|任务结果)\s*[::]/i.test(l)));
58
- return filtered.join('\n').trim();
59
- }
60
- async onAgentStart(agentName) {
61
- logger_1.logger.info(`[${agentName}] Agent started`);
62
- if (this.reportGenerator) {
63
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_START, `Agent ${agentName} started`));
64
- }
65
- }
66
- async onAgentEnd(agentName, output) {
67
- logger_1.logger.info(`[${agentName}] Agent finished: ${output}`);
68
- if (this.reportGenerator) {
69
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_END, 'Agent finished', { data: { output: String(output) } }));
70
- }
71
- }
72
- async onLLMStart(agentName, stepNumber) {
73
- this.stepStartTime = Date.now();
74
- logger_1.logger.info(`[${agentName}] Preparing LLM input with screenshot...`);
75
- try {
76
- const screenshot = await this.adapter.getScreenshot();
77
- if (screenshot && screenshot.base64Data) {
78
- if (this.reportGenerator) {
79
- const screenshotPath = this.reportGenerator.saveScreenshot(screenshot.base64Data, screenshot.layoutData, `step_${this.toolCount + 1}`);
80
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_OBSERVATION, 'Current Screen Observation', { screenshotPath, stepNumber: this.toolCount + 1 }));
81
- }
82
- if (this.toolCount > 0) {
83
- const historyText = this.historyActions.length > 0
84
- ? this.historyActions.slice(-10).join('\n')
85
- : 'none';
86
- const progressHint = `Observe UI content and changes from previous step, make next decision based on task breakdown and execution history.
87
- [Progress: ${this.toolCount + 1}]
88
- [Action history: ${historyText}]
89
- ${COMMON_ERRORS_PROMPT_LOCAL}`;
90
- if (this.reportGenerator) {
91
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, progressHint, { stepNumber: this.toolCount + 1 }));
92
- }
93
- }
94
- }
95
- }
96
- catch (e) {
97
- logger_1.logger.warn(`Failed to inject screenshot: ${e}`);
98
- }
99
- }
100
- async onLLMEnd(agentName, stepNumber, response) {
101
- logger_1.logger.info(`[${agentName}] --- LLM Response ---`);
102
- const resp = response;
103
- const output = resp?.output;
104
- const step = this.toolCount + 1;
105
- if (typeof output === 'string') {
106
- const judgmentText = _parseJudgmentContent(output);
107
- if (judgmentText) {
108
- logger_1.logger.info(`[${agentName}] Judgment: ${judgmentText}`);
109
- if (this.reportGenerator) {
110
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_END, judgmentText, { stepNumber: step }));
111
- }
112
- }
113
- else {
114
- const thinkingText = _parseThinkingContent(output);
115
- if (thinkingText) {
116
- logger_1.logger.info(`[${agentName}] Thinking: ${thinkingText}`);
117
- if (this.reportGenerator) {
118
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, SingleAgentHooks._stripVerdict(thinkingText), { stepNumber: step }));
119
- }
120
- }
121
- else {
122
- logger_1.logger.info(`[${agentName}] Text: ${output}`);
123
- if (this.reportGenerator) {
124
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, SingleAgentHooks._stripVerdict(output), { stepNumber: step }));
125
- }
126
- }
127
- }
128
- }
129
- else if (output && Array.isArray(output)) {
130
- for (const item of output) {
131
- const itemType = item?.type;
132
- if (itemType === 'reasoning') {
133
- const summary = item?.summary;
134
- if (summary) {
135
- for (const s of summary) {
136
- const text = s?.text ?? '';
137
- const judgmentText = _parseJudgmentContent(text);
138
- if (judgmentText) {
139
- logger_1.logger.info(`[${agentName}] Judgment: ${judgmentText}`);
140
- if (this.reportGenerator) {
141
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_END, judgmentText, { stepNumber: step }));
142
- }
143
- }
144
- else {
145
- const thinkingText = _parseThinkingContent(text);
146
- if (thinkingText) {
147
- logger_1.logger.info(`[${agentName}] Thinking: ${thinkingText}`);
148
- if (this.reportGenerator) {
149
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, SingleAgentHooks._stripVerdict(thinkingText), { stepNumber: step }));
150
- }
151
- }
152
- else {
153
- logger_1.logger.info(`[${agentName}] Reasoning: ${text}`);
154
- if (this.reportGenerator) {
155
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, SingleAgentHooks._stripVerdict(text), { stepNumber: step }));
156
- }
157
- }
158
- }
159
- }
160
- }
161
- const content = item?.content;
162
- if (content && Array.isArray(content)) {
163
- for (const c of content) {
164
- const text = c?.text ?? '';
165
- logger_1.logger.info(`[${agentName}] content: ${text}`);
166
- if (this.reportGenerator) {
167
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, SingleAgentHooks._stripVerdict(text), { stepNumber: step }));
168
- }
169
- }
170
- }
171
- }
172
- if (itemType === 'message') {
173
- const messageContent = item?.content;
174
- if (messageContent && Array.isArray(messageContent)) {
175
- for (const contentItem of messageContent) {
176
- if (contentItem?.type === 'output_text') {
177
- const text = contentItem?.text ?? '';
178
- logger_1.logger.info(`[${agentName}] Text: ${text}`);
179
- if (this.reportGenerator) {
180
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_OUTPUT, SingleAgentHooks._stripVerdict(text), { stepNumber: step }));
181
- }
182
- }
183
- }
184
- }
185
- }
186
- if (itemType === 'function_call') {
187
- try {
188
- const callArgs = JSON.parse(item?.arguments ?? '{}');
189
- const callToolName = item?.name ?? '';
190
- logger_1.logger.info(`[${agentName}] Tool: ${callToolName} args: ${JSON.stringify(callArgs)}`);
191
- if (this.reportGenerator) {
192
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_TOOL_CALL, `Called: ${callToolName}`, { data: { tool_name: callToolName, arguments: callArgs }, stepNumber: step }));
193
- }
194
- }
195
- catch {
196
- logger_1.logger.warn(`Failed to parse tool args: ${item?.arguments}`);
197
- }
198
- }
199
- }
200
- }
201
- const usage = resp?.usage;
202
- if (usage) {
203
- const tokenUsage = this.tokenType.fromUsageObj(usage);
204
- if (!tokenUsage)
205
- return;
206
- logger_1.logger.info(`[${agentName}] ${tokenUsage.toString()}`);
207
- if (this.reportGenerator) {
208
- this.reportGenerator.addTokenUsage(tokenUsage, 'SingleAgent', this.toolCount + 1);
209
- }
210
- }
211
- }
212
- async onToolStart(agentName, toolName, args) {
213
- logger_1.logger.info(`[${agentName}] Calling tool: ${toolName}`);
214
- if (this.reportGenerator) {
215
- try {
216
- const screenshot = await this.adapter.getScreenshot();
217
- const screenshotPath = this.reportGenerator.saveScreenshot(screenshot.base64Data, screenshot.layoutData, `step_${this.toolCount + 1}`);
218
- const eventData = { tool_name: toolName };
219
- if (args) {
220
- eventData.arguments = args;
221
- if ('log' in args) {
222
- this.historyActions.push(`${this.historyActions.length + 1}. ${args.log}`);
223
- }
224
- if (['click', 'double_click', 'long_press', 'long_click'].includes(toolName)) {
225
- eventData.action = toolName;
226
- if ('x' in args && 'y' in args) {
227
- eventData.point = [args.x, args.y];
228
- }
229
- else if ('pos' in args && Array.isArray(args.pos) && args.pos.length === 2) {
230
- eventData.point = [args.pos[0], args.pos[1]];
231
- }
232
- }
233
- else if (toolName === 'swipe') {
234
- if ('start' in args && 'end' in args) {
235
- const start = args.start;
236
- const end = args.end;
237
- if (Array.isArray(start) && start.length === 2 && Array.isArray(end) && end.length === 2) {
238
- eventData.action = 'swipe';
239
- eventData.start = [start[0], start[1]];
240
- eventData.end = [end[0], end[1]];
241
- }
242
- }
243
- else if ('start_x' in args && 'start_y' in args && 'end_x' in args && 'end_y' in args) {
244
- eventData.action = 'swipe';
245
- eventData.start = [args.start_x, args.start_y];
246
- eventData.end = [args.end_x, args.end_y];
247
- }
248
- }
249
- }
250
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.MCP_TOOL_START, `Starting: ${toolName}`, { data: eventData, screenshotPath, stepNumber: this.toolCount + 1 }));
251
- }
252
- catch (e) {
253
- logger_1.logger.warn(`Failed to capture screenshot: ${e}`);
254
- }
255
- }
256
- }
257
- async onToolEnd(agentName, toolName, result, stepNumber) {
258
- const resultStr = String(result).slice(0, 200);
259
- const elapsed = this.stepStartTime ? (Date.now() - this.stepStartTime) / 1000 : 0;
260
- const elapsedStr = elapsed < 60 ? `${elapsed.toFixed(1)}s` : `${(elapsed / 60).toFixed(1)}m`;
261
- const stepMeta = `[Step ${this.toolCount + 1} | ${elapsedStr}]`;
262
- logger_1.logger.info(`[${agentName}] ${stepMeta} Tool ${toolName} result: ${resultStr}`);
263
- this.toolCount += 1;
264
- if (this.reportGenerator) {
265
- try {
266
- const screenshot = await this.adapter.getScreenshot();
267
- const screenshotPath = this.reportGenerator.saveScreenshot(screenshot.base64Data, screenshot.layoutData, `step_${this.toolCount}`);
268
- const eventData = { tool_name: toolName, result: resultStr };
269
- try {
270
- const parsed = JSON.parse(String(result));
271
- if (typeof parsed === 'object' && parsed !== null) {
272
- Object.assign(eventData, parsed);
273
- }
274
- }
275
- catch {
276
- }
277
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.MCP_TOOL_END, `Completed: ${toolName}`, { data: eventData, screenshotPath, stepNumber: this.toolCount }));
278
- }
279
- catch (e) {
280
- logger_1.logger.warn(`Failed to capture screenshot: ${e}`);
281
- }
282
- }
283
- if (toolName === 'start_app' && result.includes('failed!')) {
284
- throw new Error(`Task terminated: ${result}`);
285
- }
286
- }
287
- }
288
- exports.SingleAgentHooks = SingleAgentHooks;
@@ -1,158 +0,0 @@
1
- "use strict";
2
- /**
3
- * Screenshot injection + action markers.
4
- *
5
- * Provides:
6
- * - compressScreenshot: resize via sharp for LLM context window
7
- * - drawActionMarker: overlay click dot / swipe arrow via SVG→sharp composite
8
- * - injectScreenshotsAndHistory: build user message with prev+current+history
9
- * - manageImageHistory: strip old images from session items
10
- */
11
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- var desc = Object.getOwnPropertyDescriptor(m, k);
14
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
- desc = { enumerable: true, get: function() { return m[k]; } };
16
- }
17
- Object.defineProperty(o, k2, desc);
18
- }) : (function(o, m, k, k2) {
19
- if (k2 === undefined) k2 = k;
20
- o[k2] = m[k];
21
- }));
22
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
- Object.defineProperty(o, "default", { enumerable: true, value: v });
24
- }) : function(o, v) {
25
- o["default"] = v;
26
- });
27
- var __importStar = (this && this.__importStar) || (function () {
28
- var ownKeys = function(o) {
29
- ownKeys = Object.getOwnPropertyNames || function (o) {
30
- var ar = [];
31
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
- return ar;
33
- };
34
- return ownKeys(o);
35
- };
36
- return function (mod) {
37
- if (mod && mod.__esModule) return mod;
38
- var result = {};
39
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
- __setModuleDefault(result, mod);
41
- return result;
42
- };
43
- })();
44
- Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.compressScreenshot = compressScreenshot;
46
- exports.drawActionMarker = drawActionMarker;
47
- exports.injectScreenshotsAndHistory = injectScreenshotsAndHistory;
48
- exports.manageImageHistory = manageImageHistory;
49
- const image_helper_1 = require("../../../common/image_helper");
50
- const logger_1 = require("../../../common/logger");
51
- const MAX_SCREENSHOT_PIXELS = 1500;
52
- /** Compress a base64 screenshot to a target pixel count. */
53
- async function compressScreenshot(base64Data, maxPixels = MAX_SCREENSHOT_PIXELS) {
54
- return (0, image_helper_1.compressBase64Image)(base64Data, maxPixels, 70);
55
- }
56
- /**
57
- * Draw an action marker (click dot + crosshair, or swipe arrow) on a screenshot.
58
- * Uses SVG → sharp composite for overlay drawing.
59
- */
60
- async function drawActionMarker(base64Data, action) {
61
- try {
62
- const sharp = await Promise.resolve().then(() => __importStar(require('sharp')));
63
- const img = Buffer.from(base64Data, 'base64');
64
- const metadata = await sharp.default(img).metadata();
65
- const w = metadata.width ?? 1080;
66
- const h = metadata.height ?? 2400;
67
- // Build SVG overlay for the marker
68
- let svg = `<svg width="${w}" height="${h}" xmlns="http://www.w3.org/2000/svg">`;
69
- if (action.type === 'click' && action.point) {
70
- const [x, y] = action.point;
71
- const px = Math.round(x * w);
72
- const py = Math.round(y * h);
73
- // Red dot with white border + crosshair
74
- svg += `<circle cx="${px}" cy="${py}" r="14" fill="none" stroke="#fff" stroke-width="3"/>`;
75
- svg += `<circle cx="${px}" cy="${py}" r="12" fill="rgba(220,38,38,0.7)" stroke="#fff" stroke-width="2"/>`;
76
- svg += `<line x1="${px - 20}" y1="${py}" x2="${px + 20}" y2="${py}" stroke="#fff" stroke-width="2"/>`;
77
- svg += `<line x1="${px}" y1="${py - 20}" x2="${px}" y2="${py + 20}" stroke="#fff" stroke-width="2"/>`;
78
- }
79
- else if (action.type === 'swipe' && action.start && action.end) {
80
- const [sx, sy] = action.start;
81
- const [ex, ey] = action.end;
82
- const px1 = Math.round(sx * w), py1 = Math.round(sy * h);
83
- const px2 = Math.round(ex * w), py2 = Math.round(ey * h);
84
- // Red arrow line
85
- svg += `<line x1="${px1}" y1="${py1}" x2="${px2}" y2="${py2}" stroke="rgba(220,38,38,0.8)" stroke-width="5" stroke-linecap="round"/>`;
86
- svg += `<circle cx="${px1}" cy="${py1}" r="6" fill="rgba(220,38,38,0.8)"/>`;
87
- // Arrowhead
88
- const angle = Math.atan2(py2 - py1, px2 - px1);
89
- const ah = 18;
90
- svg += `<polygon points="${px2},${py2} ${px2 - ah * Math.cos(angle - 0.4)},${py2 - ah * Math.sin(angle - 0.4)} ${px2 - ah * Math.cos(angle + 0.4)},${py2 - ah * Math.sin(angle + 0.4)}" fill="rgba(220,38,38,0.9)"/>`;
91
- }
92
- svg += `</svg>`;
93
- const overlay = Buffer.from(svg);
94
- const result = await sharp.default(img)
95
- .composite([{ input: overlay, top: 0, left: 0 }])
96
- .jpeg({ quality: 70 })
97
- .toBuffer();
98
- return result.toString('base64');
99
- }
100
- catch (e) {
101
- logger_1.logger.warn(`[image_utils] drawActionMarker failed: ${e instanceof Error ? e.message : String(e)}`);
102
- return base64Data;
103
- }
104
- }
105
- /**
106
- * Build a user message with previous screenshot (with action marker) + current screenshot + progress history.
107
- * Returns content blocks for the AI SDK user message.
108
- */
109
- function injectScreenshotsAndHistory(prevScreenshot, currentScreenshot, historyActions, lastActionInfo) {
110
- const blocks = [];
111
- // 1. Previous screenshot (with action marker if available)
112
- if (prevScreenshot) {
113
- blocks.push({ type: 'text', text: '## Previous screen (with action marker)' });
114
- blocks.push({
115
- type: 'file',
116
- data: `data:image/jpeg;base64,${prevScreenshot}`,
117
- mediaType: 'image/jpeg',
118
- });
119
- }
120
- // 2. Current screenshot
121
- blocks.push({ type: 'text', text: '## Current screen' });
122
- blocks.push({
123
- type: 'file',
124
- data: `data:image/jpeg;base64,${currentScreenshot}`,
125
- mediaType: 'image/jpeg',
126
- });
127
- // 3. Progress history
128
- if (historyActions.length > 0) {
129
- blocks.push({ type: 'text', text: `## History\n${historyActions.join('\n')}` });
130
- }
131
- return blocks;
132
- }
133
- /**
134
- * Strip old image parts from session items, keeping only the most recent N images.
135
- * Converts older image parts to text placeholders.
136
- */
137
- function manageImageHistory(items, maxImages = 3) {
138
- let imageCount = 0;
139
- // Walk backwards, count images, convert old ones to text
140
- for (let i = items.length - 1; i >= 0; i--) {
141
- const item = items[i];
142
- const content = item['content'];
143
- if (Array.isArray(content)) {
144
- for (const part of content) {
145
- if (part['type'] === 'file' || part['type'] === 'image' || part['type'] === 'input_image') {
146
- imageCount++;
147
- if (imageCount > maxImages) {
148
- part['type'] = 'text';
149
- part['text'] = '[previous screenshot omitted]';
150
- delete part['data'];
151
- delete part['image_url'];
152
- }
153
- }
154
- }
155
- }
156
- }
157
- return items;
158
- }