@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,565 +0,0 @@
1
- "use strict";
2
- // ReportAnalyzerAgent -- pure Agent + screenshot-tool architecture (TypeScript port).
3
- //
4
- // Core transformation: eliminate the classifier sub-Agent (which duplicated the main Agent's
5
- // analysis); use a single Agent:
6
- // - Main Agent: system prompt (attribution table + core principles + accuracy table) + tool=[get_step_screenshot]
7
- // - get_step_screenshot returns images + text (images stashed into pendingImages, consumed before the next call)
8
- // - guardrails: validateOutput + validateProcess
9
- // - outer retry: max 3 + error downgrade AnalyzerOutput(status="error")
10
- //
11
- // Entry points:
12
- // - async run(reportDir) -> AnalyzerOutput -- thin wrapper; loads report data then calls runFromData
13
- // - async runFromData(reportData, reportDir?) -> AnalyzerOutput -- core logic entry
14
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- var desc = Object.getOwnPropertyDescriptor(m, k);
17
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
18
- desc = { enumerable: true, get: function() { return m[k]; } };
19
- }
20
- Object.defineProperty(o, k2, desc);
21
- }) : (function(o, m, k, k2) {
22
- if (k2 === undefined) k2 = k;
23
- o[k2] = m[k];
24
- }));
25
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
26
- Object.defineProperty(o, "default", { enumerable: true, value: v });
27
- }) : function(o, v) {
28
- o["default"] = v;
29
- });
30
- var __importStar = (this && this.__importStar) || (function () {
31
- var ownKeys = function(o) {
32
- ownKeys = Object.getOwnPropertyNames || function (o) {
33
- var ar = [];
34
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
35
- return ar;
36
- };
37
- return ownKeys(o);
38
- };
39
- return function (mod) {
40
- if (mod && mod.__esModule) return mod;
41
- var result = {};
42
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
43
- __setModuleDefault(result, mod);
44
- return result;
45
- };
46
- })();
47
- Object.defineProperty(exports, "__esModule", { value: true });
48
- exports.ReportAnalyzerAgent = void 0;
49
- const fs = __importStar(require("fs"));
50
- const path = __importStar(require("path"));
51
- const path_utils_1 = require("../../../common/path_utils");
52
- const logger_1 = require("../../../common/logger");
53
- const model_1 = require("../../../common/model");
54
- const data_loader_1 = require("./data_loader");
55
- const types_1 = require("./types");
56
- const guardrails_1 = require("./guardrails");
57
- const mapping_1 = require("./mapping");
58
- const parse_1 = require("./parse");
59
- const report_writer_1 = require("./report_writer");
60
- const tools_1 = require("./tools");
61
- const hooks_1 = require("./hooks");
62
- const prompt_1 = require("./prompt");
63
- // Retry limit
64
- const MAX_RETRIES = 3;
65
- // Tool-call text marker pattern: [TOOL_CALL] get_step_screenshot step_number=N desc="..."
66
- const TOOL_CALL_PATTERN = /\[TOOL_CALL\]\s*get_step_screenshot\s+step_number=([\d,\s]+)(?:\s+desc="([^"]*)")?/gi;
67
- class ReportAnalyzerAgent {
68
- modelConfig;
69
- appConfig;
70
- dataLoader;
71
- reportWriter;
72
- hooks;
73
- constructor(config, appConfig) {
74
- this.modelConfig = config;
75
- this.appConfig = appConfig ?? null;
76
- this.dataLoader = new data_loader_1.DataLoader();
77
- this.reportWriter = new report_writer_1.ReportWriter();
78
- this.hooks = new hooks_1.AnalyzerHooks();
79
- }
80
- // Analyze a test report; returns root cause analysis result (thin wrapper).
81
- async run(reportDir) {
82
- const reportPath = path.resolve(reportDir);
83
- logger_1.logger.info(`Starting report analysis: ${reportPath}`);
84
- const reportData = this.dataLoader.load(reportPath);
85
- logger_1.logger.info(`Report loaded: task='${reportData.task.slice(0, 50)}...', ` +
86
- `status=${reportData.status}, steps=${reportData.steps.length}`);
87
- return this.runFromData(reportData, reportDir);
88
- }
89
- // Analyze directly from ReportData, bypassing the DataLoader.
90
- // Core logic: only_fail skip -> precheck downgrade -> LLM analysis -> screenshot data -> write report.
91
- async runFromData(reportData, reportDir) {
92
- const startTime = Date.now();
93
- const reportPath = reportDir ? path.resolve(reportDir) : null;
94
- try {
95
- // 1. only_fail quick skip
96
- if ((this.appConfig?.analyze?.onlyFail ?? true) && (reportData.status === 'pass' || reportData.status === 'PASS')) {
97
- logger_1.logger.info('Task status is PASS, onlyFail=true, skipping analysis');
98
- const duration = (Date.now() - startTime) / 1000;
99
- const output = new types_1.AnalyzerOutput({
100
- taskDescription: reportData.task,
101
- taskIntent: 'Task passed, no analysis needed',
102
- taskResultStatus: reportData.status,
103
- summary: 'Task passed (PASS); per config only FAIL cases are analyzed, skipping this analysis.',
104
- analysisTime: new Date().toISOString(),
105
- modelUsed: this.modelConfig.name,
106
- analysisDurationSeconds: duration,
107
- totalLlmCalls: 0,
108
- accuracy: 'Correct',
109
- evidenceCompleteness: {
110
- checkpoints_verified_count: 0,
111
- pass_count: 0,
112
- missing_evidence_count: 0,
113
- summary: types_1.EVIDENCE_NONE,
114
- },
115
- consistencyNotes: [
116
- {
117
- rule_id: 'pass_skip',
118
- severity: types_1.CONSISTENCY_SEVERITY_INFO,
119
- message: 'Task passed (PASS), onlyFail=true, analysis skipped',
120
- },
121
- ],
122
- });
123
- if (reportPath) {
124
- this.reportWriter.write(output, reportPath);
125
- }
126
- return output;
127
- }
128
- // 2. precheck downgrade (R1/R2/R7) -- does not depend on reportPath
129
- const precheckReason = this.precheck(reportData);
130
- if (precheckReason) {
131
- logger_1.logger.info(`Precheck downgrade: ${precheckReason}`);
132
- const duration = (Date.now() - startTime) / 1000;
133
- const output = (0, mapping_1.createPrecheckOutput)(reportData, precheckReason, this.modelConfig.name, duration);
134
- if (reportPath) {
135
- this.reportWriter.write(output, reportPath);
136
- }
137
- return output;
138
- }
139
- // 3. Run the agent (with retry loop)
140
- const analyzerCtx = (0, types_1.createAnalyzerContext)(reportData, this.appConfig);
141
- let output = await this.runAgentWithRetry(reportData, reportPath, startTime, analyzerCtx);
142
- // 4. Supplement screenshot comparison data
143
- output.screenshotData = this.buildScreenshotData(reportData, analyzerCtx);
144
- // 5. Write the report (only when reportPath is present)
145
- if (reportPath) {
146
- this.reportWriter.write(output, reportPath);
147
- }
148
- // 6. Log
149
- const duration = (Date.now() - startTime) / 1000;
150
- let rcDisplay = 'N/A';
151
- if (output.rootCause) {
152
- const subName = (0, types_1.resolveSubCategory)(output.rootCause.subCategory, String(output.rootCause.category));
153
- rcDisplay = `${output.rootCause.category}-${subName}`;
154
- }
155
- logger_1.logger.info(`Analysis complete: root_cause=${rcDisplay}, accuracy=${output.accuracy}, ` +
156
- `duration=${duration.toFixed(1)}s, attempts=${output.totalLlmCalls}`);
157
- return output;
158
- }
159
- catch (e) {
160
- // Single-report fault tolerance: any stage failure does not interrupt the whole batch
161
- const errMsg = e instanceof Error ? e.message : String(e);
162
- logger_1.logger.error(`Analysis failed: ${reportPath ?? 'N/A'}: ${errMsg}`);
163
- const duration = (Date.now() - startTime) / 1000;
164
- const taskDesc = reportPath ? String(reportPath) : reportData.task;
165
- const output = new types_1.AnalyzerOutput({
166
- taskDescription: taskDesc,
167
- taskIntent: 'Analysis process exception',
168
- taskResultStatus: 'error',
169
- summary: `Analysis failed: ${errMsg}`,
170
- analysisTime: new Date().toISOString(),
171
- modelUsed: this.modelConfig.name,
172
- analysisDurationSeconds: duration,
173
- totalLlmCalls: 0,
174
- accuracy: 'Inconclusive',
175
- evidenceCompleteness: {
176
- checkpoints_verified_count: 0,
177
- pass_count: 0,
178
- missing_evidence_count: 0,
179
- summary: types_1.EVIDENCE_NONE,
180
- },
181
- consistencyNotes: [
182
- {
183
- rule_id: 'exception',
184
- severity: types_1.CONSISTENCY_SEVERITY_ERROR,
185
- message: `Analysis exception: ${errMsg.slice(0, 100)}`,
186
- },
187
- ],
188
- });
189
- if (reportPath) {
190
- try {
191
- this.reportWriter.write(output, reportPath);
192
- }
193
- catch {
194
- logger_1.logger.warn('Failed to write error report, abandoning write');
195
- }
196
- }
197
- return output;
198
- }
199
- }
200
- // Pre-check whether the report has enough data to analyze.
201
- // Returns null if passed, or a string downgrade reason.
202
- precheck(reportData) {
203
- // R1: no screenshot data
204
- const hasScreenshots = reportData.steps.some((sd) => sd.screenshots.length > 0);
205
- if (!hasScreenshots) {
206
- return 'Report has no screenshot data; cannot verify Agent observations';
207
- }
208
- // R7: no execution steps
209
- if (reportData.steps.length === 0) {
210
- return 'Report has no execution step data; cannot analyze Agent behavior';
211
- }
212
- // R2: no judgment block (result_text empty)
213
- if (!reportData.resultText) {
214
- return 'Report has no judgment block (result_text is empty); cannot confirm original verdict basis';
215
- }
216
- // Abnormal status
217
- const validStatuses = new Set(['pass', 'PASS', 'fail', 'FAIL', 'failed']);
218
- if (!validStatuses.has(reportData.status)) {
219
- return `Report status abnormal (status=${reportData.status}), not in known status set`;
220
- }
221
- return null;
222
- }
223
- // Run the agent and handle the guardrail-triggered retry loop.
224
- // Retry strategy: guardrail trigger -> rerun with failure-reason hint (max 3 times);
225
- // non-guardrail exceptions also count as retries; on exhaustion return error downgrade.
226
- async runAgentWithRetry(reportData, reportPath, startTime, analyzerCtx) {
227
- const initialInput = this.buildInitialInput(reportData);
228
- const modelConfig = this.modelConfig;
229
- // API record: if apirec is enabled, record analyzer LLM calls to a per-analysis db
230
- // (aligned with python report_analyzer_agent/agent.py api_record plumbing)
231
- let llmCaller;
232
- if (this.appConfig?.agent?.unified?.apirec) {
233
- const { createLLMClient } = await Promise.resolve().then(() => __importStar(require('../../../common/dfx/client_factory')));
234
- const analysisDir = path.join(reportPath ?? process.cwd(), 'analysis');
235
- try {
236
- fs.mkdirSync(analysisDir, { recursive: true });
237
- }
238
- catch { /* ignore */ }
239
- const bundle = createLLMClient(this.appConfig, 'analyze_service', { reportDir: analysisDir });
240
- const { CacheTransport } = await Promise.resolve().then(() => __importStar(require('../../../common/llm_cache/cache_transport')));
241
- const cacheTransport = new CacheTransport(this.appConfig.agent.unified.enableCache);
242
- llmCaller = new model_1.LLMCaller(cacheTransport, bundle.recordingFetch);
243
- logger_1.logger.info(`[AnalyzerAgent] api_record enabled, db at ${analysisDir}/api_records.json`);
244
- }
245
- else {
246
- llmCaller = new model_1.LLMCaller();
247
- }
248
- logger_1.logger.info(`[AnalyzerAgent] model config: model_name=${this.modelConfig.name}, ` +
249
- `base_url=${this.modelConfig.baseUrl}`);
250
- let systemPrompt = prompt_1.MAIN_AGENT_PROMPT;
251
- const promptMdPath = path.join((0, path_utils_1.findDistRoot)(), 'core', 'agent', 'report_analyzer_agent', 'prompts', 'main_agent_v2.0.md');
252
- if (fs.existsSync(promptMdPath)) {
253
- const mdContent = fs.readFileSync(promptMdPath, 'utf-8');
254
- if (mdContent.includes('## Verdict') && mdContent.includes('[TOOL_CALL]')) {
255
- systemPrompt = mdContent;
256
- logger_1.logger.info(`[AnalyzerAgent] loaded prompt from main_agent_v2.0.md`);
257
- }
258
- else {
259
- logger_1.logger.warn(`[AnalyzerAgent] main_agent.md is stale (missing '## Verdict' or '[TOOL_CALL]' protocol), ` +
260
- 'falling back to inline MAIN_AGENT_PROMPT');
261
- }
262
- }
263
- const retryReasons = [];
264
- let retryAttempts = 0;
265
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
266
- logger_1.logger.info(`[AnalyzerAgent] attempt ${attempt + 1}/${MAX_RETRIES}`);
267
- // Reset context for each attempt
268
- analyzerCtx.screenshotCalls.length = 0;
269
- analyzerCtx.pendingImages.length = 0;
270
- // Build the starting user prompt (deep copy of initial input + retry hint)
271
- let conversationParts = [initialInput];
272
- if (retryReasons.length > 0) {
273
- const hint = `Previous analysis was rejected: ${retryReasons.join('; ')}. Please correct and retry.`;
274
- conversationParts.push(hint);
275
- logger_1.logger.info(`[AnalyzerAgent] retry hint: ${hint.slice(0, 100)}`);
276
- }
277
- try {
278
- const result = await this.runAgentLoop(llmCaller, systemPrompt, modelConfig, conversationParts, analyzerCtx);
279
- retryAttempts += 1;
280
- const finalText = result.finalText;
281
- if (!finalText || !finalText.trim()) {
282
- retryReasons.push('LLM output is empty or non-text');
283
- logger_1.logger.warn('[AnalyzerAgent] LLM output empty, retrying');
284
- continue;
285
- }
286
- const parsed = (0, parse_1.parseRootCauseResult)(finalText);
287
- if (parsed === null) {
288
- retryReasons.push(`Parse failed (invalid Markdown format, LLM output first 200 chars: ${finalText.slice(0, 200)})`);
289
- logger_1.logger.warn('[AnalyzerAgent] parse failed (Markdown), retrying');
290
- continue;
291
- }
292
- logger_1.logger.info(`[AnalyzerAgent] parse success: category=${parsed.rootCauseCategory}, ` +
293
- `sub=${parsed.rootCauseSubCategory}, accuracy=${parsed.accuracy}`);
294
- // validateOutput: check RootCauseResult structural integrity
295
- const outputGuard = await (0, guardrails_1.validateOutput)(analyzerCtx, parsed);
296
- if (outputGuard.tripwireTriggered) {
297
- const reason = outputGuard.outputInfo['reason'] ?? 'output guardrail triggered';
298
- retryReasons.push(reason);
299
- logger_1.logger.warn(`[AnalyzerAgent] validateOutput tripwire: ${reason}`);
300
- continue;
301
- }
302
- // validateProcess: check analysis process soundness
303
- const processGuard = await (0, guardrails_1.validateProcess)(analyzerCtx, parsed);
304
- if (processGuard.tripwireTriggered) {
305
- const reason = processGuard.outputInfo['reason'] ?? 'process guardrail triggered';
306
- retryReasons.push(reason);
307
- logger_1.logger.warn(`[AnalyzerAgent] validateProcess tripwire: ${reason}`);
308
- continue;
309
- }
310
- // Validation passed -> map to AnalyzerOutput
311
- const duration = (Date.now() - startTime) / 1000;
312
- const output = (0, mapping_1.mapResultToOutput)(parsed, reportData, this.modelConfig.name, duration, retryAttempts);
313
- // Supplement trace (extracted from the loop turns)
314
- output.trace = result.trace;
315
- // Supplement consistency_notes (derive from guardrail events)
316
- const consistencyNotes = output.consistencyNotes;
317
- if ((this.appConfig?.analyze?.enableMultimodal ?? true) && analyzerCtx.screenshotCalls.length > 0) {
318
- const screenshotStepSet = new Set(analyzerCtx.screenshotCalls);
319
- for (const ev of parsed.evidence) {
320
- if (guardrails_1.SCREENSHOT_CLAIM_PATTERN.test(ev)) {
321
- const matches = ev.matchAll(/step\s*(\d+)/gi);
322
- for (const m of matches) {
323
- const num = parseInt(m[1], 10);
324
- if (!screenshotStepSet.has(num)) {
325
- consistencyNotes.push({
326
- rule_id: 'fabricated_evidence',
327
- severity: types_1.CONSISTENCY_SEVERITY_WARNING,
328
- message: `Evidence claims screenshot analysis for step ${num} but it was not actually viewed`,
329
- });
330
- }
331
- }
332
- }
333
- }
334
- }
335
- logger_1.logger.info(`[AnalyzerAgent] analysis success: attempt=${attempt + 1}`);
336
- return output;
337
- }
338
- catch (e) {
339
- const errorMsg = e instanceof Error ? e.message : String(e);
340
- retryReasons.push(`Exception: ${errorMsg.slice(0, 200)}`);
341
- logger_1.logger.warn(`[AnalyzerAgent] Exception: ${errorMsg.slice(0, 200)}`);
342
- }
343
- }
344
- // Retries exhausted -> error downgrade
345
- const duration = (Date.now() - startTime) / 1000;
346
- const allReasons = retryReasons.join('; ');
347
- logger_1.logger.error(`[AnalyzerAgent] all ${MAX_RETRIES} retries failed: ${allReasons}`);
348
- const taskDesc = reportPath ? String(reportPath) : reportData.task;
349
- return (0, mapping_1.createErrorOutput)(taskDesc, allReasons, this.modelConfig.name, duration);
350
- }
351
- // The agent loop: repeatedly call the LLM, parse tool-call markers, execute the screenshot
352
- // tool, and feed results back until a final Markdown verdict is produced or maxTurns is hit.
353
- async runAgentLoop(llmCaller, systemPrompt, modelConfig, conversationParts, analyzerCtx) {
354
- const trace = [];
355
- const loadedImages = [];
356
- let turn = 0;
357
- for (let i = 0; i < (this.appConfig?.analyze?.maxTurns ?? 8); i++) {
358
- turn += 1;
359
- // Drain any pending images stashed by the tool into the call
360
- const pending = this.hooks.drainPendingImages(analyzerCtx);
361
- for (const group of pending) {
362
- for (const item of group.content) {
363
- const imageUrl = item['image_url'];
364
- if (imageUrl) {
365
- // Strip the data URI prefix to get pure base64
366
- const prefix = 'data:image/jpeg;base64,';
367
- const b64 = imageUrl.startsWith(prefix) ? imageUrl.slice(prefix.length) : imageUrl;
368
- loadedImages.push({ base64Data: b64, mimeType: 'image/jpeg' });
369
- }
370
- }
371
- }
372
- const userPrompt = conversationParts.join('\n\n');
373
- let llmResult;
374
- try {
375
- llmResult = await llmCaller.call({
376
- systemPrompt,
377
- userPrompt,
378
- images: loadedImages.length > 0 ? loadedImages : undefined,
379
- modelConfig,
380
- });
381
- }
382
- catch (e) {
383
- // Re-throw to be handled by the retry loop
384
- throw e;
385
- }
386
- const responseText = llmResult.text ?? '';
387
- const reasoning = llmResult.reasoning ?? '';
388
- const reasoningContent = llmResult.reasoningContent ?? reasoning;
389
- // Parse tool-call markers from the response
390
- const toolCalls = this.parseToolCallMarkers(responseText);
391
- if (toolCalls.length > 0) {
392
- // Record this turn as a tool_calls turn
393
- const traceStep = {
394
- turn,
395
- reasoning,
396
- reasoningContent,
397
- content: responseText,
398
- action: 'tool_calls',
399
- tool_calls: toolCalls.map((tc) => ({
400
- name: 'get_step_screenshot',
401
- args: { step_number: tc.stepNumber, desc: tc.desc },
402
- })),
403
- };
404
- trace.push(traceStep);
405
- // Execute each tool call
406
- const toolResults = [];
407
- for (const tc of toolCalls) {
408
- const toolResult = await (0, tools_1.getStepScreenshot)(analyzerCtx, tc.stepNumber, tc.desc);
409
- if (toolResult.loaded) {
410
- // Images stashed into pendingImages by the tool; collect them for the next call
411
- for (const img of toolResult.images) {
412
- loadedImages.push(img);
413
- }
414
- }
415
- toolResults.push(toolResult.text);
416
- }
417
- // Append the response + tool results to the conversation for the next turn
418
- conversationParts.push(`[Turn ${turn} response]\n${responseText}`);
419
- conversationParts.push(`[Tool results for turn ${turn}]\n${toolResults.join('\n')}`);
420
- conversationParts.push('[Continue]\nYou have received the screenshot evidence above. Continue your analysis. ' +
421
- 'If you need more screenshots, output [TOOL_CALL] markers again. ' +
422
- 'When you have enough evidence, output the final Markdown verdict with the ## Verdict section.');
423
- continue;
424
- }
425
- // No tool calls -> treat as final answer
426
- const traceStep = {
427
- turn,
428
- reasoning,
429
- reasoningContent,
430
- content: responseText,
431
- action: 'final_answer',
432
- };
433
- trace.push(traceStep);
434
- return { finalText: responseText, trace };
435
- }
436
- // maxTurns exhausted; return the last response as final (parser will likely fail -> retry)
437
- logger_1.logger.warn(`[AnalyzerAgent] maxTurns (${(this.appConfig?.analyze?.maxTurns ?? 8)}) reached without a final verdict`);
438
- return { finalText: conversationParts[conversationParts.length - 1] ?? '', trace };
439
- }
440
- // Parse [TOOL_CALL] markers from the LLM text response.
441
- parseToolCallMarkers(text) {
442
- const results = [];
443
- TOOL_CALL_PATTERN.lastIndex = 0;
444
- let match;
445
- while ((match = TOOL_CALL_PATTERN.exec(text)) !== null) {
446
- const rawStep = match[1].trim();
447
- const desc = match[2] ?? '';
448
- // Keep the raw step arg (may be "1,2,3" for a multi-step single call);
449
- // getStepScreenshot parses it internally (aligned with python screenshot_tool).
450
- if (rawStep) {
451
- results.push({ stepNumber: rawStep, desc });
452
- }
453
- }
454
- return results;
455
- }
456
- // Build the initial agent input (5-section structure).
457
- buildInitialInput(reportData) {
458
- const sections = [];
459
- // Section 1: original conclusion
460
- sections.push(`=== Original Conclusion ===\n${reportData.status}`);
461
- // Section 2: test case
462
- sections.push(`=== Test Case ===\n${reportData.task}`);
463
- // Section 3: Agent execution process (reasoning chain)
464
- const plannerOutput = this.formatPlannerOutput(reportData);
465
- sections.push(`=== Agent Execution Process (reasoning chain) ===\n${plannerOutput}`);
466
- // Section 4: Agent judgment block (keep full, no truncation)
467
- let judgmentBlock = (reportData.resultText ?? '').trim();
468
- if (!judgmentBlock) {
469
- judgmentBlock = '(no judgment block content)';
470
- }
471
- sections.push(`=== Agent Judgment Block ===\n${judgmentBlock}`);
472
- // Section 5: step inventory (screenshot numbers and operation descriptions)
473
- const stepInventory = this.formatStepInventory(reportData);
474
- sections.push(`=== Step Inventory (screenshot numbers and operation descriptions) ===\n${stepInventory}`);
475
- // Footer hint
476
- const footer = 'You need to view actual screenshots via the get_step_screenshot tool to obtain UI evidence. ' +
477
- 'Based on the step inventory and the descriptions in the Agent judgment block, locate the ' +
478
- 'screenshot numbers of relevant steps and call the tool to view them. After obtaining enough ' +
479
- 'evidence, return the Markdown with all fields.';
480
- sections.push(footer);
481
- return sections.join('\n\n');
482
- }
483
- // Format the Agent execution process (reasoning chain).
484
- formatPlannerOutput(reportData) {
485
- if (!reportData.steps || reportData.steps.length === 0) {
486
- return '(none)';
487
- }
488
- const lines = [];
489
- for (const sd of reportData.steps) {
490
- if (!sd.thinking)
491
- continue;
492
- lines.push(`--- Step ${sd.stepNumber} ---`);
493
- lines.push(sd.thinking);
494
- lines.push('');
495
- }
496
- return lines.length > 0 ? lines.join('\n') : '(none)';
497
- }
498
- // Format the step inventory.
499
- formatStepInventory(reportData) {
500
- const MAX_STEP_DESC_CHARS = 80;
501
- if (!reportData.steps || reportData.steps.length === 0) {
502
- return '(none)';
503
- }
504
- const lines = [];
505
- for (const sd of reportData.steps) {
506
- const parts = [];
507
- const tc = sd.toolCall ?? {};
508
- const toolName = tc['tool_name'] ?? '';
509
- const arguments_ = tc['arguments'] ?? {};
510
- if (toolName) {
511
- const argumentsJson = JSON.stringify(arguments_);
512
- parts.push(`${toolName}(${argumentsJson})`);
513
- }
514
- const tr = sd.toolResult ?? {};
515
- const resultText = tr['result'] ?? '';
516
- if (resultText) {
517
- parts.push(`Result: ${resultText.slice(0, 60)}`);
518
- }
519
- if (sd.thinking) {
520
- parts.push(`Thinking: ${sd.thinking.slice(0, 80)}`);
521
- }
522
- let desc = parts.length > 0 ? parts.join(' | ') : '(no operation info)';
523
- if (desc.length > MAX_STEP_DESC_CHARS) {
524
- desc = desc.slice(0, MAX_STEP_DESC_CHARS - 1) + '...';
525
- }
526
- lines.push(`Step ${sd.stepNumber}: ${desc}`);
527
- }
528
- return lines.join('\n');
529
- }
530
- // Build screenshot comparison data (only for steps the Agent actually viewed).
531
- buildScreenshotData(reportData, analyzerCtx) {
532
- const screenshotData = [];
533
- const viewedSteps = new Set(analyzerCtx.screenshotCalls);
534
- for (const sd of reportData.steps) {
535
- if (!viewedSteps.has(sd.stepNumber))
536
- continue;
537
- let observedFile = '';
538
- let beforeActionFile = '';
539
- let hasComparison = false;
540
- if (sd.screenshots && sd.screenshots.length >= 1) {
541
- observedFile = path.basename(sd.screenshots[0]);
542
- if (sd.screenshots.length >= 2) {
543
- beforeActionFile = path.basename(sd.screenshots[1]);
544
- hasComparison = observedFile !== beforeActionFile;
545
- }
546
- }
547
- const tc = sd.toolCall ?? {};
548
- const toolName = tc['tool_name'] ?? '';
549
- const arguments_ = tc['arguments'] ?? {};
550
- let actionInfo = '';
551
- if (toolName) {
552
- actionInfo = `${toolName}(${JSON.stringify(arguments_)})`;
553
- }
554
- screenshotData.push({
555
- step_number: sd.stepNumber,
556
- observed_file: observedFile,
557
- before_action_file: beforeActionFile,
558
- action_info: actionInfo,
559
- has_comparison: hasComparison,
560
- });
561
- }
562
- return screenshotData;
563
- }
564
- }
565
- exports.ReportAnalyzerAgent = ReportAnalyzerAgent;
@@ -1,22 +0,0 @@
1
- "use strict";
2
- // Analyzer configuration.
3
- // Reuses the AnalyzerConfig Zod type from common/config and adds a resolver helper.
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.resolveModelConfig = resolveModelConfig;
6
- // Resolve missing model config fields from a unified model config.
7
- // temperature=0.0 is an explicit default and is NOT inherited from unified model.
8
- function resolveModelConfig(config, unifiedModel) {
9
- if (config.modelName && config.baseUrl && config.apiKey) {
10
- return config;
11
- }
12
- return {
13
- ...config,
14
- modelName: config.modelName || unifiedModel.name,
15
- baseUrl: config.baseUrl || unifiedModel.baseUrl,
16
- apiKey: config.apiKey || unifiedModel.apiKey,
17
- // temperature keeps its own value (default 0.0), no fallback to unified model
18
- temperature: config.temperature,
19
- timeout: config.timeout || unifiedModel.timeout,
20
- maxRetries: config.maxRetries || unifiedModel.maxRetries,
21
- };
22
- }