@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,782 +0,0 @@
1
- "use strict";
2
- /**
3
- * Pure-TypeScript HarmonyOS device adapter.
4
- *
5
- * Drives a connected HarmonyOS device directly through the local `hdc` CLI,
6
- * reimplementing the MCP tool surface that `hypium_mcp` previously provided
7
- * over HTTP. Coordinates arriving from the agent are relative 0.0~1.0 values
8
- * and are scaled to absolute pixels using the real screen resolution captured
9
- * from the device screenshots. Tool result messages report the original
10
- * relative coordinates so they stay aligned with the LLM/agent output.
11
- */
12
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
- if (k2 === undefined) k2 = k;
14
- var desc = Object.getOwnPropertyDescriptor(m, k);
15
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
- desc = { enumerable: true, get: function() { return m[k]; } };
17
- }
18
- Object.defineProperty(o, k2, desc);
19
- }) : (function(o, m, k, k2) {
20
- if (k2 === undefined) k2 = k;
21
- o[k2] = m[k];
22
- }));
23
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
- Object.defineProperty(o, "default", { enumerable: true, value: v });
25
- }) : function(o, v) {
26
- o["default"] = v;
27
- });
28
- var __importStar = (this && this.__importStar) || (function () {
29
- var ownKeys = function(o) {
30
- ownKeys = Object.getOwnPropertyNames || function (o) {
31
- var ar = [];
32
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
- return ar;
34
- };
35
- return ownKeys(o);
36
- };
37
- return function (mod) {
38
- if (mod && mod.__esModule) return mod;
39
- var result = {};
40
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
- __setModuleDefault(result, mod);
42
- return result;
43
- };
44
- })();
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.HarmonyHdcAdapter = void 0;
47
- const child_process_1 = require("child_process");
48
- const fs = __importStar(require("fs"));
49
- const os = __importStar(require("os"));
50
- const path = __importStar(require("path"));
51
- const base_adapter_1 = require("./base_adapter");
52
- const hdc_1 = require("../device/hdc");
53
- const common_errors_1 = require("../../common/common_errors");
54
- const logger_1 = require("../../common/logger");
55
- const DEFAULT_HDC_PATH = 'hdc';
56
- const SCREEN_SIZE_DEFAULT = { width: 1080, height: 2400 };
57
- function sleepSync(seconds) {
58
- if (seconds <= 0)
59
- return Promise.resolve();
60
- return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
61
- }
62
- class HdcDriverImpl {
63
- deviceSn;
64
- ip;
65
- port;
66
- hdcPath;
67
- constructor(deviceSn, ip, port, hdcPath = DEFAULT_HDC_PATH) {
68
- this.deviceSn = deviceSn;
69
- this.ip = ip;
70
- this.port = port;
71
- this.hdcPath = hdcPath;
72
- }
73
- baseArgs() {
74
- return ['-s', `${this.ip}:${this.port}`, '-t', this.deviceSn];
75
- }
76
- runHdcAsync(args, timeout = 30) {
77
- return new Promise((resolve, reject) => {
78
- (0, child_process_1.execFile)(this.hdcPath, args, { encoding: 'utf-8', timeout: timeout * 1000, windowsHide: true, maxBuffer: 50 * 1024 * 1024 }, (err, stdout) => {
79
- if (err) {
80
- const msg = `hdc command failed: ${args.join(' ')} -> ${err.message}`;
81
- logger_1.logger.error(`HdcDriver: ${msg}`);
82
- reject(new Error(msg));
83
- }
84
- else {
85
- resolve(stdout);
86
- }
87
- });
88
- });
89
- }
90
- async shell(command, timeout) {
91
- return this.runHdcAsync([...this.baseArgs(), 'shell', command], timeout ?? 30);
92
- }
93
- async fileRecv(remotePath, localPath) {
94
- try {
95
- const out = await this.runHdcAsync([...this.baseArgs(), 'file', 'recv', remotePath, localPath], 30);
96
- return !/fail|error/i.test(out);
97
- }
98
- catch {
99
- return false;
100
- }
101
- }
102
- async fileSend(localPath, remotePath) {
103
- try {
104
- const out = await this.runHdcAsync([...this.baseArgs(), 'file', 'send', localPath, remotePath], 30);
105
- return !/fail|error/i.test(out);
106
- }
107
- catch {
108
- return false;
109
- }
110
- }
111
- async listTargets() {
112
- return this.runHdcAsync(['-s', `${this.ip}:${this.port}`, 'list', 'targets'], 10);
113
- }
114
- }
115
- class HarmonyHdcAdapter extends base_adapter_1.MCPDeviceAdapterBase {
116
- platform = 'harmony';
117
- hdcPath;
118
- driver;
119
- ip;
120
- port;
121
- screenWidth = 0;
122
- screenHeight = 0;
123
- screenAlwaysOn = false;
124
- deviceResetDevice;
125
- deviceScreenAlwaysOn;
126
- deviceOperationMode;
127
- toastListener = null;
128
- toastBuffer = [];
129
- toastListening = false;
130
- constructor(hdcPath, configManager) {
131
- super(configManager);
132
- this.hdcPath = hdcPath || DEFAULT_HDC_PATH;
133
- const cfg = configManager.getEffectiveConfig();
134
- let deviceSn = cfg.device.deviceSn ?? '';
135
- this.ip = cfg.device.ip;
136
- this.port = cfg.device.port;
137
- this.deviceResetDevice = cfg.device.resetDevice;
138
- this.deviceScreenAlwaysOn = cfg.device.screenAlwaysOn;
139
- this.deviceOperationMode = cfg.device.operationMode;
140
- if (!deviceSn) {
141
- try {
142
- // Try plain hdc list targets first (works for local USB devices without
143
- // needing a remote hdc server). Falls back to -s ip:port for remote setups.
144
- let listResult = (0, child_process_1.execSync)(`${this.hdcPath} list targets`, {
145
- encoding: 'utf-8',
146
- timeout: 5000,
147
- windowsHide: true,
148
- });
149
- if (!listResult.trim()) {
150
- // Fallback: use -s ip:port for remote hdc server
151
- listResult = (0, child_process_1.execSync)(`${this.hdcPath} -s ${this.ip}:${this.port} list targets`, {
152
- encoding: 'utf-8',
153
- timeout: 5000,
154
- windowsHide: true,
155
- });
156
- }
157
- const devices = listResult.trim().split('\n').map((d) => d.trim()).filter(Boolean);
158
- // Filter out remote targets (IP:PORT) — prefer USB device SNs (e.g. MJE...)
159
- const localDevices = devices.filter((d) => !/^\d+\.\d+\.\d+\.\d+:\d+$/.test(d));
160
- const preferred = localDevices.length > 0 ? localDevices : devices;
161
- if (preferred.length > 0) {
162
- deviceSn = preferred[0];
163
- logger_1.logger.info(`Auto-detected device SN: ${deviceSn}`);
164
- }
165
- }
166
- catch (e) {
167
- logger_1.logger.warn(`Auto-detect device SN failed: ${e instanceof Error ? e.message : String(e)}`);
168
- }
169
- }
170
- if (!deviceSn) {
171
- deviceSn = 'default';
172
- }
173
- this.driver = new HdcDriverImpl(deviceSn, this.ip, this.port, this.hdcPath);
174
- }
175
- getDefaultServerUrl() {
176
- return '';
177
- }
178
- getMcpServicePort() {
179
- return 0;
180
- }
181
- useSseTransport() {
182
- return false;
183
- }
184
- async startMcpService() {
185
- if (!(await this.checkDeviceConnected())) {
186
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', `HarmonyOS device not reachable via hdc (${this.driver.deviceSn})`);
187
- }
188
- return '';
189
- }
190
- async checkServiceHealth(_serverUrl) {
191
- const ok = await this.checkDeviceConnected();
192
- return { isHealthy: ok, status: ok ? 'healthy' : 'notRunning' };
193
- }
194
- async killProcessByPort(_port) {
195
- // No background service to manage.
196
- }
197
- async connect() {
198
- logger_1.logger.info(`HarmonyHdcAdapter connecting (${this.platform})...`);
199
- if (!(await this.checkDeviceConnected())) {
200
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', `Fail to connect device [${this.driver.deviceSn}]`);
201
- }
202
- this.connected = true;
203
- try {
204
- await this.callTool('screen_on', undefined, 10, false);
205
- await this.callTool('unlock_screen', undefined, 10, false);
206
- logger_1.logger.info('Device screen unlocked');
207
- }
208
- catch (e) {
209
- logger_1.logger.warn(`Screen unlock failed: ${e instanceof Error ? e.message : String(e)}`);
210
- }
211
- if (this.deviceScreenAlwaysOn) {
212
- try {
213
- await this.setScreenAlwaysOn(true);
214
- }
215
- catch (e) {
216
- logger_1.logger.warn(`Screen always-on failed: ${e instanceof Error ? e.message : String(e)}`);
217
- }
218
- }
219
- logger_1.logger.info('HarmonyHdcAdapter connected');
220
- }
221
- async disconnect() {
222
- this.stopToastListener();
223
- if (this.deviceScreenAlwaysOn) {
224
- try {
225
- await this.setScreenAlwaysOn(false);
226
- }
227
- catch { /* best-effort */ }
228
- }
229
- await super.disconnect();
230
- }
231
- async getScreenshot(saveDir) {
232
- if (!this.connected) {
233
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', 'Adapter not connected');
234
- }
235
- const shot = await (0, hdc_1.getScreenshot)(this.driver, true);
236
- if (shot.width > 0 && shot.height > 0) {
237
- this.screenWidth = shot.width;
238
- this.screenHeight = shot.height;
239
- }
240
- // Fallback saveDir to config.output.rootDir/log (aligned with python hdc_device report_path)
241
- const effectiveSaveDir = saveDir ?? path.join(this.configManager.getEffectiveConfig().output.rootDir, 'log');
242
- let screenshotPath = null;
243
- if (effectiveSaveDir && shot.base64Data) {
244
- try {
245
- fs.mkdirSync(effectiveSaveDir, { recursive: true });
246
- const file = path.join(effectiveSaveDir, `screenshot_${Date.now()}.jpg`);
247
- fs.writeFileSync(file, Buffer.from(shot.base64Data, 'base64'));
248
- screenshotPath = file;
249
- }
250
- catch (e) {
251
- logger_1.logger.error(`Save screenshot failed: ${e instanceof Error ? e.message : String(e)}`);
252
- }
253
- }
254
- return {
255
- base64Data: shot.base64Data,
256
- layoutData: shot.layoutData,
257
- width: shot.width,
258
- height: shot.height,
259
- isSensitive: shot.isSensitive,
260
- screenshotPath,
261
- };
262
- }
263
- async reset() {
264
- if (!this.connected) {
265
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', 'Adapter not connected');
266
- }
267
- if (!this.deviceResetDevice) {
268
- // config.device.resetDevice = false → skip reset entirely
269
- return;
270
- }
271
- try {
272
- await (0, hdc_1.home)(this.driver, 1);
273
- if (Array.isArray(this.deviceResetDevice)) {
274
- // list mode: force-stop specific packages instead of clearing all
275
- for (const pkg of this.deviceResetDevice) {
276
- logger_1.logger.info(`[harmony] force-stop: ${pkg}`);
277
- await this.callTool('stop_app', { app_name: pkg });
278
- }
279
- }
280
- else {
281
- // true mode: clear all recent tasks
282
- await this.callTool('clear_recent_task', undefined, 15, false);
283
- }
284
- }
285
- catch {
286
- // best-effort reset
287
- }
288
- }
289
- async callTool(toolName, args, _timeout, _retryOnFailure) {
290
- if (!this.connected) {
291
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', 'Adapter not connected');
292
- }
293
- const a = args ?? {};
294
- const name = toolName;
295
- switch (name) {
296
- case 'click':
297
- case 'tap': {
298
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
299
- const [x, y] = this.toAbsolute(rel);
300
- await (0, hdc_1.tap)(this.driver, x, y);
301
- return `click (${this.fmt(rel)}) successfully`;
302
- }
303
- case 'double_click':
304
- case 'double_tap': {
305
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
306
- const [x, y] = this.toAbsolute(rel);
307
- await (0, hdc_1.doubleTap)(this.driver, x, y);
308
- return `double_click (${this.fmt(rel)}) successfully`;
309
- }
310
- case 'long_click':
311
- case 'long_press': {
312
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
313
- const [x, y] = this.toAbsolute(rel);
314
- const durationSec = typeof a.duration === 'number' ? a.duration : 2;
315
- await (0, hdc_1.longPress)(this.driver, x, y, Math.round(durationSec * 1000));
316
- return `long_click (${this.fmt(rel)}) successfully`;
317
- }
318
- case 'swipe': {
319
- let startRel = this.extractPoint(a, ['start'], ['start_x', 'start_y']);
320
- let endRel = this.extractPoint(a, ['end'], ['end_x', 'end_y']);
321
- const direction = typeof a.direction === 'string' ? a.direction.toLowerCase() : null;
322
- if (direction) {
323
- const [x1, y1] = startRel;
324
- const [x2, y2] = endRel;
325
- if ((direction === 'left' && x1 < x2) || (direction === 'right' && x1 > x2)
326
- || (direction === 'up' && y1 < y2) || (direction === 'down' && y1 > y2)) {
327
- [startRel, endRel] = [endRel, startRel];
328
- }
329
- }
330
- const [sx, sy] = this.toAbsolute(startRel);
331
- const [ex, ey] = this.toAbsolute(endRel);
332
- await (0, hdc_1.swipe)(this.driver, sx, sy, ex, ey);
333
- return `swipe (${this.fmt(startRel)})->(${this.fmt(endRel)}) successfully`;
334
- }
335
- case 'drag': {
336
- const startRel = this.extractPoint(a, ['start'], ['start_x', 'start_y']);
337
- const endRel = this.extractPoint(a, ['end'], ['end_x', 'end_y']);
338
- const [sx, sy] = this.toAbsolute(startRel);
339
- const [ex, ey] = this.toAbsolute(endRel);
340
- await this.driver.shell(`uitest uiInput drag ${sx} ${sy} ${ex} ${ey}`);
341
- return `drag (${this.fmt(startRel)})->(${this.fmt(endRel)}) successfully`;
342
- }
343
- case 'input_text':
344
- case 'type_text': {
345
- const text = typeof a.text === 'string' ? a.text : '';
346
- await (0, hdc_1.typeText)(this.driver, text);
347
- return `input_text successfully`;
348
- }
349
- case 'clear_text': {
350
- await (0, hdc_1.clearText)(this.driver);
351
- return `clear_text successfully`;
352
- }
353
- case 'go_back':
354
- case 'back': {
355
- const times = typeof a.times === 'number' ? Math.max(1, a.times) : 1;
356
- for (let i = 0; i < times; i++) {
357
- await (0, hdc_1.back)(this.driver, 0.5);
358
- }
359
- return `go_back successfully`;
360
- }
361
- case 'go_home':
362
- case 'home': {
363
- const times = typeof a.times === 'number' ? Math.max(1, a.times) : 1;
364
- for (let i = 0; i < times; i++) {
365
- await (0, hdc_1.home)(this.driver, 0.5);
366
- }
367
- return `go_home successfully`;
368
- }
369
- case 'start_app': {
370
- const appName = typeof a.app_name === 'string' ? a.app_name : '';
371
- if (a.cold_start) {
372
- await this.callTool('stop_app', { app_name: appName });
373
- await sleepSync(1);
374
- }
375
- const ok = await (0, hdc_1.launchApp)(this.driver, appName, 1);
376
- return ok ? `start_app ${appName} successfully` : `start_app ${appName} failed`;
377
- }
378
- case 'stop_app': {
379
- const appName = typeof a.app_name === 'string' ? a.app_name : '';
380
- const bundle = (0, hdc_1.getPackageName)(appName) ?? appName;
381
- await this.driver.shell(`aa force-stop ${bundle}`);
382
- return `stop_app ${bundle} successfully`;
383
- }
384
- case 'clear_app_data': {
385
- const appName = typeof a.app_name === 'string' ? a.app_name : (typeof a.bundle_name === 'string' ? a.bundle_name : '');
386
- const bundle = (0, hdc_1.getPackageName)(appName) ?? appName;
387
- let echo = await this.driver.shell(`bm clean -n ${bundle} -d`);
388
- if (/error|fail|unknow/i.test(echo)) {
389
- echo = await this.driver.shell(`bm clean -n ${bundle} -c`);
390
- }
391
- return `clear_app_data ${bundle} successfully`;
392
- }
393
- case 'wait': {
394
- const duration = typeof a.duration === 'number' ? Math.min(a.duration, 200) : 3;
395
- await sleepSync(duration);
396
- return `Already wait ${duration} s`;
397
- }
398
- case 'press_key': {
399
- const keyName = typeof a.key_name === 'string' ? a.key_name : '';
400
- const code = this.keyNameToCode(keyName);
401
- if (code == null) {
402
- return `press_key failed: unsupported key ${keyName}`;
403
- }
404
- if (keyName === 'home') {
405
- await (0, hdc_1.home)(this.driver, 0.5);
406
- }
407
- else {
408
- await this.driver.shell(`uitest uiInput keyEvent ${code}`);
409
- }
410
- return `press_key ${keyName} successfully`;
411
- }
412
- case 'screen_on': {
413
- await this.driver.shell('power-shell wakeup');
414
- await sleepSync(1);
415
- return `screen_on successfully`;
416
- }
417
- case 'screen_off': {
418
- await this.driver.shell('power-shell suspend');
419
- await sleepSync(1);
420
- return `screen_off successfully`;
421
- }
422
- case 'unlock_screen': {
423
- await this.callTool('screen_on', undefined, 10, false);
424
- await sleepSync(1);
425
- if (await this.isDisplayLocked()) {
426
- const [, h] = await this.getScreenSize();
427
- const w = this.screenWidth || SCREEN_SIZE_DEFAULT.width;
428
- const sx = Math.floor(0.5 * w);
429
- const sy = Math.floor(0.99 * h);
430
- const ey = Math.floor(0.7 * h);
431
- await (0, hdc_1.swipe)(this.driver, sx, sy, sx, ey);
432
- }
433
- return `unlock_screen successfully`;
434
- }
435
- case 'clear_recent_task': {
436
- await this.clearRecentTasks();
437
- return `后台应用已清理`;
438
- }
439
- case 'enter_recent_task': {
440
- await this.driver.shell('uitest uiInput combinationKeyEvent 2076 2049');
441
- await sleepSync(1);
442
- return `enter_recent_task successfully`;
443
- }
444
- case 'get_current_app': {
445
- return await (0, hdc_1.getCurrentApp)(this.driver, false);
446
- }
447
- case 'screenshot': {
448
- const savePath = typeof a.save_path === 'string' ? a.save_path : '';
449
- const shot = await (0, hdc_1.getScreenshot)(this.driver, false);
450
- if (shot.width > 0 && shot.height > 0) {
451
- this.screenWidth = shot.width;
452
- this.screenHeight = shot.height;
453
- }
454
- if (savePath && shot.base64Data) {
455
- try {
456
- fs.mkdirSync(path.dirname(savePath), { recursive: true });
457
- fs.writeFileSync(savePath, Buffer.from(shot.base64Data, 'base64'));
458
- return savePath;
459
- }
460
- catch (e) {
461
- logger_1.logger.error(`screenshot save failed: ${e instanceof Error ? e.message : String(e)}`);
462
- }
463
- }
464
- return shot.base64Data ? 'screenshot captured' : 'screenshot failed';
465
- }
466
- case 'layout': {
467
- const shot = await (0, hdc_1.getScreenshot)(this.driver, true);
468
- return shot.layoutData || '';
469
- }
470
- case 'open_control_center': {
471
- const times = a.full_screen ? 2 : 1;
472
- for (let i = 0; i < times; i++) {
473
- const [sx, sy] = this.toAbsolute([0.8, 0]);
474
- const [ex, ey] = this.toAbsolute([0.8, 0.4]);
475
- await (0, hdc_1.swipe)(this.driver, sx, sy, ex, ey);
476
- }
477
- return `open_control_center successfully`;
478
- }
479
- case 'open_notification_center': {
480
- const times = a.full_screen ? 2 : 1;
481
- for (let i = 0; i < times; i++) {
482
- const [sx, sy] = this.toAbsolute([0.3, 0]);
483
- const [ex, ey] = this.toAbsolute([0.3, 0.4]);
484
- await (0, hdc_1.swipe)(this.driver, sx, sy, ex, ey);
485
- }
486
- return `open_notification_center successfully`;
487
- }
488
- case 'pinch_in': {
489
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
490
- const [cx, cy] = this.toAbsolute(rel);
491
- const radius = typeof a.radius === 'number' ? a.radius : 300;
492
- const scale = typeof a.scale === 'number' ? a.scale : 0.2;
493
- await this.pinchGesture(cx, cy, radius, scale);
494
- return `pinch_in (${this.fmt(rel)}) successfully`;
495
- }
496
- case 'pinch_out': {
497
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
498
- const [cx, cy] = this.toAbsolute(rel);
499
- const radius = typeof a.radius === 'number' ? a.radius : 300;
500
- const scale = typeof a.scale === 'number' ? a.scale : 1.6;
501
- await this.pinchGesture(cx, cy, radius, scale);
502
- return `pinch_out (${this.fmt(rel)}) successfully`;
503
- }
504
- case 'rotate_gesture': {
505
- const rel = this.extractPoint(a, ['pos', 'center'], ['center_x', 'center_y']);
506
- const [cx, cy] = this.toAbsolute(rel);
507
- const angle = typeof a.angle === 'number' ? a.angle : 90;
508
- const clockwise = a.clockwise !== false;
509
- const radius = typeof a.radius === 'number' ? a.radius : 300;
510
- await this.rotateGesture(cx, cy, angle, clockwise, radius);
511
- return `rotate_gesture (${this.fmt(rel)}, angle=${angle}, clockwise=${clockwise}) successfully`;
512
- }
513
- case 'rotate_screen': {
514
- const direction = typeof a.direction === 'string' ? a.direction.toLowerCase() : 'portrait';
515
- const angle = direction === 'landscape' ? 270 : 0;
516
- let out = await this.driver.shell(`uitest uiInput setDisplayRotation ${angle}`);
517
- if (/error|fail|not found|not support/i.test(out)) {
518
- const orient = direction === 'landscape' ? 3 : 0;
519
- out = await this.driver.shell(`hidumper -s DisplayManagerService -a "-s 0 -o ${orient}"`);
520
- }
521
- return `rotate_screen ${direction} (angle=${angle}) result: ${out.trim() || 'ok'}`;
522
- }
523
- case 'stop_all_app': {
524
- await this.clearRecentTasks();
525
- return `stop_all_app successfully`;
526
- }
527
- case 'start_listen_toast': {
528
- this.startToastListener();
529
- return `start_listen_toast successfully`;
530
- }
531
- case 'get_toast': {
532
- const timeout = typeof a.timeout === 'number' ? a.timeout : 3;
533
- return await this.getLatestToast(timeout);
534
- }
535
- case 'start_data_collect': {
536
- return `start_data_collect acknowledged (no-op: collection not enabled in nodejs adapter)`;
537
- }
538
- case 'stop_data_collect': {
539
- return `stop_data_collect acknowledged (no-op: collection not enabled in nodejs adapter)`;
540
- }
541
- case 'generate_report': {
542
- return `generate_report acknowledged (nodejs uses reporter module)`;
543
- }
544
- case 'mcp_clean_up':
545
- case 'finish': {
546
- return `${name} acknowledged`;
547
- }
548
- default:
549
- return `Tool ${toolName} not available`;
550
- }
551
- }
552
- async checkDeviceConnected() {
553
- try {
554
- const out = await this.driver.listTargets();
555
- const connected = new Set();
556
- for (const line of out.split('\n')) {
557
- const parts = line.trim().split(/\s+/).filter(Boolean);
558
- if (parts.length === 0)
559
- continue;
560
- if (/no\s+target|empty|nil/i.test(line))
561
- continue;
562
- const state = parts.slice(1).join(' ');
563
- if (/offline|unavailable|disconnect/i.test(state))
564
- continue;
565
- connected.add(parts[0]);
566
- }
567
- const sn = this.driver.deviceSn;
568
- if (sn && sn !== 'default') {
569
- return connected.has(sn);
570
- }
571
- return connected.size > 0;
572
- }
573
- catch {
574
- return false;
575
- }
576
- }
577
- async setScreenAlwaysOn(enable) {
578
- const action = enable ? '-t' : '-f';
579
- await this.driver.shell(`hidumper -s PowerManagerService -a ${action}`);
580
- this.screenAlwaysOn = enable;
581
- }
582
- async isDisplayLocked() {
583
- try {
584
- const echo = await this.driver.shell('hidumper -s ScreenlockService -a -all');
585
- return /screenlocked.*true/i.test(echo);
586
- }
587
- catch {
588
- return false;
589
- }
590
- }
591
- async getScreenSize() {
592
- if (this.screenWidth > 0 && this.screenHeight > 0) {
593
- return [this.screenWidth, this.screenHeight];
594
- }
595
- const shot = await (0, hdc_1.getScreenshot)(this.driver, false);
596
- if (shot.width > 0 && shot.height > 0) {
597
- this.screenWidth = shot.width;
598
- this.screenHeight = shot.height;
599
- }
600
- else {
601
- this.screenWidth = SCREEN_SIZE_DEFAULT.width;
602
- this.screenHeight = SCREEN_SIZE_DEFAULT.height;
603
- }
604
- return [this.screenWidth, this.screenHeight];
605
- }
606
- toAbsolute(rel) {
607
- const w = this.screenWidth || SCREEN_SIZE_DEFAULT.width;
608
- const h = this.screenHeight || SCREEN_SIZE_DEFAULT.height;
609
- const x = Math.floor(Math.max(0, Math.min(rel[0], 1)) * w);
610
- const y = Math.floor(Math.max(0, Math.min(rel[1], 1)) * h);
611
- return [x, y];
612
- }
613
- fmt(rel) {
614
- const round = (v) => String(Math.round(v * 1e4) / 1e4);
615
- return `${round(rel[0])},${round(rel[1])}`;
616
- }
617
- extractPoint(args, tupleKeys, splitKeys) {
618
- for (const key of tupleKeys) {
619
- const v = args[key];
620
- if (Array.isArray(v) && v.length === 2 && typeof v[0] === 'number' && typeof v[1] === 'number') {
621
- return [v[0], v[1]];
622
- }
623
- }
624
- const x = args[splitKeys[0]];
625
- const y = args[splitKeys[1]];
626
- if (typeof x === 'number' && typeof y === 'number') {
627
- return [x, y];
628
- }
629
- if (typeof x === 'number') {
630
- return [x, 0];
631
- }
632
- if (typeof y === 'number') {
633
- return [0, y];
634
- }
635
- return [0, 0];
636
- }
637
- keyNameToCode(keyName) {
638
- switch (keyName) {
639
- case 'home': return 1;
640
- case 'power': return 18;
641
- case 'volume_up': return 16;
642
- case 'volume_down': return 17;
643
- default: return null;
644
- }
645
- }
646
- async clearRecentTasks() {
647
- await (0, hdc_1.home)(this.driver, 1);
648
- await sleepSync(1);
649
- const output = await this.driver.shell('aa dump -l');
650
- const bundles = new Set();
651
- for (const line of output.split('\n')) {
652
- const m = line.match(/bundle name \[([^\]]+)\]/);
653
- if (m && m[1]) {
654
- bundles.add(m[1]);
655
- }
656
- }
657
- for (const bundle of bundles) {
658
- try {
659
- await this.driver.shell(`aa force-stop ${bundle}`);
660
- }
661
- catch {
662
- // best-effort stop
663
- }
664
- }
665
- }
666
- async pinchGesture(cx, cy, radius, scale) {
667
- const segments = 8;
668
- const startRadius = scale < 1 ? radius : Math.round(radius / scale);
669
- const endRadius = Math.round(startRadius * scale);
670
- const duration = 0.5;
671
- const intervalMs = Math.max(20, Math.round((duration / segments) * 1000));
672
- const pts0 = [];
673
- const pts1 = [];
674
- for (let i = 0; i <= segments; i++) {
675
- const t = i / segments;
676
- const r = startRadius + (endRadius - startRadius) * t;
677
- pts0.push([Math.round(cx - r), Math.round(cy)]);
678
- pts1.push([Math.round(cx + r), Math.round(cy)]);
679
- }
680
- await this.driver.shell(`uinput -T -d ${pts0[0][0]} ${pts0[0][1]} -i 0`);
681
- await this.driver.shell(`uinput -T -d ${pts1[0][0]} ${pts1[0][1]} -i 1`);
682
- for (let i = 1; i <= segments; i++) {
683
- await this.driver.shell(`uinput -T -m ${pts0[i - 1][0]} ${pts0[i - 1][1]} ${pts0[i][0]} ${pts0[i][1]} ${intervalMs} -i 0`);
684
- await this.driver.shell(`uinput -T -m ${pts1[i - 1][0]} ${pts1[i - 1][1]} ${pts1[i][0]} ${pts1[i][1]} ${intervalMs} -i 1`);
685
- }
686
- await this.driver.shell(`uinput -T -u ${pts0[segments][0]} ${pts0[segments][1]} -i 0`);
687
- await this.driver.shell(`uinput -T -u ${pts1[segments][0]} ${pts1[segments][1]} -i 1`);
688
- }
689
- async rotateGesture(cx, cy, angle, clockwise, radius) {
690
- const segments = 8;
691
- const angleRad = (angle * Math.PI) / 180;
692
- const speed = 600;
693
- const arcLength = Math.abs(angleRad) * radius;
694
- const duration = arcLength / speed;
695
- const intervalMs = Math.max(20, Math.round((duration / segments) * 1000));
696
- const startAngle0 = clockwise ? 0 : Math.PI;
697
- const startAngle1 = clockwise ? Math.PI : 0;
698
- const pts0 = [];
699
- const pts1 = [];
700
- for (let i = 0; i <= segments; i++) {
701
- const t = i / segments;
702
- const a0 = startAngle0 + angleRad * t;
703
- const a1 = startAngle1 + angleRad * t;
704
- pts0.push([Math.round(cx + radius * Math.cos(a0)), Math.round(cy + radius * Math.sin(a0))]);
705
- pts1.push([Math.round(cx + radius * Math.cos(a1)), Math.round(cy + radius * Math.sin(a1))]);
706
- }
707
- await this.driver.shell(`uinput -T -d ${pts0[0][0]} ${pts0[0][1]} -i 0`);
708
- await this.driver.shell(`uinput -T -d ${pts1[0][0]} ${pts1[0][1]} -i 1`);
709
- for (let i = 1; i <= segments; i++) {
710
- await this.driver.shell(`uinput -T -m ${pts0[i - 1][0]} ${pts0[i - 1][1]} ${pts0[i][0]} ${pts0[i][1]} ${intervalMs} -i 0`);
711
- await this.driver.shell(`uinput -T -m ${pts1[i - 1][0]} ${pts1[i - 1][1]} ${pts1[i][0]} ${pts1[i][1]} ${intervalMs} -i 1`);
712
- }
713
- await this.driver.shell(`uinput -T -u ${pts0[segments][0]} ${pts0[segments][1]} -i 0`);
714
- await this.driver.shell(`uinput -T -u ${pts1[segments][0]} ${pts1[segments][1]} -i 1`);
715
- }
716
- startToastListener() {
717
- this.stopToastListener();
718
- this.toastBuffer = [];
719
- this.toastListening = true;
720
- try {
721
- this.toastListener = (0, child_process_1.spawn)(this.hdcPath, [
722
- '-s', `${this.ip}:${this.port}`, '-t', this.driver.deviceSn,
723
- 'shell', 'hilog',
724
- ], {
725
- stdio: ['ignore', 'pipe', 'pipe'],
726
- windowsHide: true,
727
- });
728
- this.toastListener.stdout?.on('data', (chunk) => {
729
- const lines = chunk.toString('utf-8').split('\n');
730
- for (const line of lines) {
731
- if (/toast/i.test(line)) {
732
- this.toastBuffer.push(line.trim());
733
- if (this.toastBuffer.length > 50)
734
- this.toastBuffer.shift();
735
- }
736
- }
737
- });
738
- this.toastListener.on('error', (err) => {
739
- logger_1.logger.warn(`toast listener error: ${err.message}`);
740
- });
741
- }
742
- catch (e) {
743
- logger_1.logger.warn(`start_listen_toast failed: ${e instanceof Error ? e.message : String(e)}`);
744
- }
745
- }
746
- stopToastListener() {
747
- if (this.toastListener) {
748
- const pid = this.toastListener.pid;
749
- try {
750
- if (os.platform() === 'win32' && pid) {
751
- // Windows: kill the entire process tree (hdc may spawn child processes)
752
- (0, child_process_1.execSync)(`taskkill /F /T /PID ${pid}`, { timeout: 5000, windowsHide: true });
753
- }
754
- else {
755
- this.toastListener.kill('SIGTERM');
756
- }
757
- }
758
- catch { /* best-effort */ }
759
- this.toastListener = null;
760
- }
761
- this.toastListening = false;
762
- }
763
- async getLatestToast(timeout) {
764
- const deadline = Date.now() + timeout * 1000;
765
- while (Date.now() < deadline) {
766
- if (this.toastBuffer.length > 0) {
767
- const latest = this.toastBuffer[this.toastBuffer.length - 1];
768
- this.toastBuffer = [];
769
- this.toastListening = false;
770
- return this.extractToastText(latest);
771
- }
772
- await sleepSync(0.3);
773
- }
774
- this.toastListening = false;
775
- return '';
776
- }
777
- extractToastText(line) {
778
- const match = line.match(/["']([^"']+)["']/);
779
- return match?.[1] ?? line;
780
- }
781
- }
782
- exports.HarmonyHdcAdapter = HarmonyHdcAdapter;