@autotest/agent 0.0.6 → 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 (153) hide show
  1. package/README.md +7 -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 +4 -0
  5. package/dist/common/config/manager.d.ts +4 -4
  6. package/dist/common/config/types.d.ts +5 -0
  7. package/dist/common/dfx/index.d.ts +1 -1
  8. package/dist/core/agent/single_agent/agent.d.ts +1 -0
  9. package/dist/core/device/device_protocol.d.ts +1 -1
  10. package/dist/core/knowledge/knowledge_manager.d.ts +3 -3
  11. package/dist/core/knowledge/vectordb.d.ts +5 -5
  12. package/dist/core/mcp/harmony_hdc_adapter.d.ts +1 -0
  13. package/dist/core/mcp/mcp_tools.d.ts +1 -0
  14. package/dist/core/mcp/verify_tool.d.ts +12 -0
  15. package/dist/core/prompt/templates/single/single_v2.0.md +15 -0
  16. package/dist/data_types/device.d.ts +1 -1
  17. package/dist/data_types/index.d.ts +1 -1
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +1 -163
  20. package/dist/tools/batch_runner.js +1 -745
  21. package/dist/tools/case_runner/runner.js +1 -410
  22. package/dist/tools/config/config_tool.js +1 -339
  23. package/dist/tools/prompt_compare/compare_runner.js +1 -360
  24. package/package.json +2 -2
  25. package/dist/api/agent_api.js +0 -550
  26. package/dist/api/autotest_agent.js +0 -205
  27. package/dist/api/types.js +0 -11
  28. package/dist/common/case_manager.js +0 -91
  29. package/dist/common/collect_case.js +0 -128
  30. package/dist/common/common_errors.js +0 -66
  31. package/dist/common/config/config_validator.js +0 -28
  32. package/dist/common/config/manager.js +0 -257
  33. package/dist/common/config/output.js +0 -59
  34. package/dist/common/config/types.js +0 -185
  35. package/dist/common/dfx/client_factory.js +0 -62
  36. package/dist/common/dfx/context.js +0 -23
  37. package/dist/common/dfx/index.js +0 -15
  38. package/dist/common/dfx/recorder.js +0 -191
  39. package/dist/common/dfx/recording_fetch.js +0 -228
  40. package/dist/common/dfx/source.js +0 -13
  41. package/dist/common/image_cacher.js +0 -36
  42. package/dist/common/image_helper.js +0 -128
  43. package/dist/common/image_similarity.js +0 -171
  44. package/dist/common/llm_cache/cache_transport.js +0 -102
  45. package/dist/common/llm_cache/prompt_cache.js +0 -113
  46. package/dist/common/logger.js +0 -158
  47. package/dist/common/model/custom_model.js +0 -487
  48. package/dist/common/model/index.js +0 -5
  49. package/dist/common/path_utils.js +0 -88
  50. package/dist/common/result_parser.js +0 -49
  51. package/dist/common/usage/token_usage.js +0 -117
  52. package/dist/common/utils.js +0 -125
  53. package/dist/core/agent/layered_agent/ability_helper.js +0 -125
  54. package/dist/core/agent/layered_agent/agent.js +0 -37
  55. package/dist/core/agent/layered_agent/agent_registry.js +0 -82
  56. package/dist/core/agent/layered_agent/decision.js +0 -518
  57. package/dist/core/agent/layered_agent/execute_agent/action_handler.js +0 -155
  58. package/dist/core/agent/layered_agent/execute_agent/agent_factory.js +0 -41
  59. package/dist/core/agent/layered_agent/execute_agent/base_agent.js +0 -112
  60. package/dist/core/agent/layered_agent/execute_agent/general_agent.js +0 -207
  61. package/dist/core/agent/layered_agent/execute_agent/glm_agent.js +0 -241
  62. package/dist/core/agent/layered_agent/execute_agent/i18n.js +0 -34
  63. package/dist/core/agent/layered_agent/execute_agent/index.js +0 -67
  64. package/dist/core/agent/layered_agent/execute_agent/mai_ui_agent.js +0 -316
  65. package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.js +0 -154
  66. package/dist/core/agent/layered_agent/execute_agent/parser/general_parser.js +0 -243
  67. package/dist/core/agent/layered_agent/execute_agent/parser/glm_parser.js +0 -139
  68. package/dist/core/agent/layered_agent/execute_agent/parser/index.js +0 -9
  69. package/dist/core/agent/layered_agent/execute_agent/parser/mai_ui_parser.js +0 -94
  70. package/dist/core/agent/layered_agent/execute_agent/prompts.js +0 -109
  71. package/dist/core/agent/layered_agent/execute_agent/simple_reporter.js +0 -33
  72. package/dist/core/agent/layered_agent/execute_agent/utils.js +0 -52
  73. package/dist/core/agent/report_analyzer_agent/agent.js +0 -565
  74. package/dist/core/agent/report_analyzer_agent/config.js +0 -22
  75. package/dist/core/agent/report_analyzer_agent/data_loader.js +0 -255
  76. package/dist/core/agent/report_analyzer_agent/guardrails.js +0 -99
  77. package/dist/core/agent/report_analyzer_agent/hooks.js +0 -31
  78. package/dist/core/agent/report_analyzer_agent/index.js +0 -52
  79. package/dist/core/agent/report_analyzer_agent/key_steps_builder.js +0 -42
  80. package/dist/core/agent/report_analyzer_agent/mapping.js +0 -133
  81. package/dist/core/agent/report_analyzer_agent/parse.js +0 -375
  82. package/dist/core/agent/report_analyzer_agent/prompt.js +0 -300
  83. package/dist/core/agent/report_analyzer_agent/report_writer.js +0 -558
  84. package/dist/core/agent/report_analyzer_agent/tools.js +0 -150
  85. package/dist/core/agent/report_analyzer_agent/types.js +0 -274
  86. package/dist/core/agent/rewrite_agent/agent.js +0 -209
  87. package/dist/core/agent/rewrite_agent/guardrails.js +0 -95
  88. package/dist/core/agent/rewrite_agent/mapping.js +0 -56
  89. package/dist/core/agent/rewrite_agent/parse.js +0 -121
  90. package/dist/core/agent/rewrite_agent/types.js +0 -37
  91. package/dist/core/agent/single_agent/agent.js +0 -801
  92. package/dist/core/agent/single_agent/hook_manager.js +0 -59
  93. package/dist/core/agent/single_agent/hooks.js +0 -288
  94. package/dist/core/agent/single_agent/image_utils.js +0 -158
  95. package/dist/core/agent/single_agent/scroll_search_agent.js +0 -405
  96. package/dist/core/agent/single_agent/subagent_manager.js +0 -72
  97. package/dist/core/agent/single_agent/tool_recorder_hook.js +0 -42
  98. package/dist/core/agent/types.js +0 -2
  99. package/dist/core/agent/utils/message_builder.js +0 -138
  100. package/dist/core/device/device_protocol.js +0 -2
  101. package/dist/core/device/hdc/apps.js +0 -437
  102. package/dist/core/device/hdc/device.js +0 -219
  103. package/dist/core/device/hdc/index.js +0 -31
  104. package/dist/core/device/hdc/input.js +0 -74
  105. package/dist/core/device/hdc/screenshot.js +0 -171
  106. package/dist/core/device/index.js +0 -70
  107. package/dist/core/device/types.js +0 -2
  108. package/dist/core/knowledge/knowledge_manager.js +0 -70
  109. package/dist/core/knowledge/vectordb.js +0 -283
  110. package/dist/core/mcp/adapter_factory.js +0 -99
  111. package/dist/core/mcp/android_adapter.js +0 -286
  112. package/dist/core/mcp/base_adapter.js +0 -86
  113. package/dist/core/mcp/harmony_hdc_adapter.js +0 -798
  114. package/dist/core/mcp/ios_adapter.js +0 -286
  115. package/dist/core/mcp/local_tools.js +0 -41
  116. package/dist/core/mcp/mcp_tools.js +0 -473
  117. package/dist/core/mcp/types.js +0 -6
  118. package/dist/core/memory/_utils.js +0 -140
  119. package/dist/core/memory/compressed_session.js +0 -182
  120. package/dist/core/memory/context_compressor.js +0 -176
  121. package/dist/core/memory/index.js +0 -22
  122. package/dist/core/memory/memory_manager.js +0 -28
  123. package/dist/core/memory/reflector.js +0 -95
  124. package/dist/core/memory/replan_manager.js +0 -12
  125. package/dist/core/memory/session_factory.js +0 -29
  126. package/dist/core/memory/tool_player.js +0 -225
  127. package/dist/core/memory/tool_player_popup.js +0 -276
  128. package/dist/core/memory/tool_player_replan.js +0 -226
  129. package/dist/core/memory/tool_player_xpath.js +0 -139
  130. package/dist/core/memory/tool_recorder.js +0 -126
  131. package/dist/core/preprocessor/task_splitter.js +0 -112
  132. package/dist/core/prompt/prompt_loader.js +0 -315
  133. package/dist/core/skill/skill_manager.js +0 -302
  134. package/dist/data_types/action.js +0 -2
  135. package/dist/data_types/agent.js +0 -2
  136. package/dist/data_types/case.js +0 -57
  137. package/dist/data_types/device.js +0 -2
  138. package/dist/data_types/index.js +0 -11
  139. package/dist/data_types/report.js +0 -6
  140. package/dist/data_types/screen.js +0 -23
  141. package/dist/data_types/task.js +0 -2
  142. package/dist/loop/cli.js +0 -127
  143. package/dist/loop/orchestrator.js +0 -314
  144. package/dist/loop/result_writer.js +0 -260
  145. package/dist/loop/types.js +0 -82
  146. package/dist/mcp-server/server.js +0 -341
  147. package/dist/mcp-server/types.js +0 -224
  148. package/dist/reporter/batch_summary.js +0 -197
  149. package/dist/reporter/generator.js +0 -286
  150. package/dist/reporter/html_template/index.js +0 -529
  151. package/dist/reporter/json_report.js +0 -6
  152. package/dist/reporter/types.js +0 -45
  153. package/dist/tools/case_runner/report.js +0 -264
@@ -1,798 +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
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
- logger_1.logger.info('[HarmonyHdcAdapter] reset skipped (resetDevice=false)');
269
- return;
270
- }
271
- try {
272
- logger_1.logger.info('[HarmonyHdcAdapter] reset: go home + clear recent tasks');
273
- await (0, hdc_1.home)(this.driver, 1);
274
- if (Array.isArray(this.deviceResetDevice)) {
275
- // list mode: force-stop specific packages instead of clearing all
276
- for (const pkg of this.deviceResetDevice) {
277
- logger_1.logger.info(`[HarmonyHdcAdapter] force-stop: ${pkg}`);
278
- await this.callTool('stop_app', { app_name: pkg });
279
- }
280
- }
281
- else {
282
- // true mode: clear all recent tasks
283
- await this.callTool('clear_recent_task', undefined, 15, false);
284
- }
285
- logger_1.logger.info('[HarmonyHdcAdapter] reset completed');
286
- }
287
- catch (e) {
288
- logger_1.logger.warn(`[HarmonyHdcAdapter] reset failed (best-effort): ${e instanceof Error ? e.message : String(e)}`);
289
- }
290
- }
291
- async callTool(toolName, args, _timeout, _retryOnFailure) {
292
- if (!this.connected) {
293
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', 'Adapter not connected');
294
- }
295
- const a = args ?? {};
296
- const name = toolName;
297
- switch (name) {
298
- case 'click':
299
- case 'tap': {
300
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
301
- const [x, y] = this.toAbsolute(rel);
302
- await (0, hdc_1.tap)(this.driver, x, y);
303
- return `click (${this.fmt(rel)}) successfully`;
304
- }
305
- case 'double_click':
306
- case 'double_tap': {
307
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
308
- const [x, y] = this.toAbsolute(rel);
309
- await (0, hdc_1.doubleTap)(this.driver, x, y);
310
- return `double_click (${this.fmt(rel)}) successfully`;
311
- }
312
- case 'long_click':
313
- case 'long_press': {
314
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
315
- const [x, y] = this.toAbsolute(rel);
316
- const durationSec = typeof a.duration === 'number' ? a.duration : 2;
317
- await (0, hdc_1.longPress)(this.driver, x, y, Math.round(durationSec * 1000));
318
- return `long_click (${this.fmt(rel)}) successfully`;
319
- }
320
- case 'swipe': {
321
- let startRel = this.extractPoint(a, ['start'], ['start_x', 'start_y']);
322
- let endRel = this.extractPoint(a, ['end'], ['end_x', 'end_y']);
323
- const direction = typeof a.direction === 'string' ? a.direction.toLowerCase() : null;
324
- if (direction) {
325
- const [x1, y1] = startRel;
326
- const [x2, y2] = endRel;
327
- if ((direction === 'left' && x1 < x2) || (direction === 'right' && x1 > x2)
328
- || (direction === 'up' && y1 < y2) || (direction === 'down' && y1 > y2)) {
329
- [startRel, endRel] = [endRel, startRel];
330
- }
331
- }
332
- const [sx, sy] = this.toAbsolute(startRel);
333
- const [ex, ey] = this.toAbsolute(endRel);
334
- await (0, hdc_1.swipe)(this.driver, sx, sy, ex, ey);
335
- return `swipe (${this.fmt(startRel)})->(${this.fmt(endRel)}) successfully`;
336
- }
337
- case 'drag': {
338
- const startRel = this.extractPoint(a, ['start'], ['start_x', 'start_y']);
339
- const endRel = this.extractPoint(a, ['end'], ['end_x', 'end_y']);
340
- const [sx, sy] = this.toAbsolute(startRel);
341
- const [ex, ey] = this.toAbsolute(endRel);
342
- await this.driver.shell(`uitest uiInput drag ${sx} ${sy} ${ex} ${ey}`);
343
- return `drag (${this.fmt(startRel)})->(${this.fmt(endRel)}) successfully`;
344
- }
345
- case 'input_text':
346
- case 'type_text': {
347
- const text = typeof a.text === 'string' ? a.text : '';
348
- await (0, hdc_1.typeText)(this.driver, text);
349
- return `input_text successfully`;
350
- }
351
- case 'clear_text': {
352
- await (0, hdc_1.clearText)(this.driver);
353
- return `clear_text successfully`;
354
- }
355
- case 'go_back':
356
- case 'back': {
357
- const times = typeof a.times === 'number' ? Math.max(1, a.times) : 1;
358
- for (let i = 0; i < times; i++) {
359
- await (0, hdc_1.back)(this.driver, 0.5);
360
- }
361
- return `go_back successfully`;
362
- }
363
- case 'go_home':
364
- case 'home': {
365
- const times = typeof a.times === 'number' ? Math.max(1, a.times) : 1;
366
- for (let i = 0; i < times; i++) {
367
- await (0, hdc_1.home)(this.driver, 0.5);
368
- }
369
- return `go_home successfully`;
370
- }
371
- case 'start_app': {
372
- const appName = typeof a.app_name === 'string' ? a.app_name : '';
373
- if (a.cold_start) {
374
- await this.callTool('stop_app', { app_name: appName });
375
- await sleepSync(1);
376
- }
377
- const ok = await (0, hdc_1.launchApp)(this.driver, appName, 1);
378
- return ok ? `start_app ${appName} successfully` : `start_app ${appName} failed`;
379
- }
380
- case 'start_app_by_deep_link': {
381
- const uri = typeof a.uri === 'string' ? a.uri : '';
382
- if (!uri)
383
- return 'start_app_by_deep_link failed: uri is required';
384
- const parts = ['aa', 'start', '-U', uri];
385
- if (a.bundle_name)
386
- parts.push('-b', String(a.bundle_name));
387
- if (a.ability_name)
388
- parts.push('-a', String(a.ability_name));
389
- const cmd = parts.join(' ');
390
- const out = await this.driver.shell(cmd);
391
- const success = !out.toLowerCase().includes('error') && !out.toLowerCase().includes('fail');
392
- return success ? `start_app_by_deep_link ${uri} successfully` : `start_app_by_deep_link ${uri} failed: ${out}`;
393
- }
394
- case 'stop_app': {
395
- const appName = typeof a.app_name === 'string' ? a.app_name : '';
396
- const bundle = (0, hdc_1.getPackageName)(appName) ?? appName;
397
- await this.driver.shell(`aa force-stop ${bundle}`);
398
- return `stop_app ${bundle} successfully`;
399
- }
400
- case 'clear_app_data': {
401
- const appName = typeof a.app_name === 'string' ? a.app_name : (typeof a.bundle_name === 'string' ? a.bundle_name : '');
402
- const bundle = (0, hdc_1.getPackageName)(appName) ?? appName;
403
- let echo = await this.driver.shell(`bm clean -n ${bundle} -d`);
404
- if (/error|fail|unknow/i.test(echo)) {
405
- echo = await this.driver.shell(`bm clean -n ${bundle} -c`);
406
- }
407
- return `clear_app_data ${bundle} successfully`;
408
- }
409
- case 'wait': {
410
- const duration = typeof a.duration === 'number' ? Math.min(a.duration, 200) : 3;
411
- await sleepSync(duration);
412
- return `Already wait ${duration} s`;
413
- }
414
- case 'press_key': {
415
- const keyName = typeof a.key_name === 'string' ? a.key_name : '';
416
- const code = this.keyNameToCode(keyName);
417
- if (code == null) {
418
- return `press_key failed: unsupported key ${keyName}`;
419
- }
420
- if (keyName === 'home') {
421
- await (0, hdc_1.home)(this.driver, 0.5);
422
- }
423
- else {
424
- await this.driver.shell(`uitest uiInput keyEvent ${code}`);
425
- }
426
- return `press_key ${keyName} successfully`;
427
- }
428
- case 'screen_on': {
429
- await this.driver.shell('power-shell wakeup');
430
- await sleepSync(1);
431
- return `screen_on successfully`;
432
- }
433
- case 'screen_off': {
434
- await this.driver.shell('power-shell suspend');
435
- await sleepSync(1);
436
- return `screen_off successfully`;
437
- }
438
- case 'unlock_screen': {
439
- await this.callTool('screen_on', undefined, 10, false);
440
- await sleepSync(1);
441
- if (await this.isDisplayLocked()) {
442
- const [, h] = await this.getScreenSize();
443
- const w = this.screenWidth || SCREEN_SIZE_DEFAULT.width;
444
- const sx = Math.floor(0.5 * w);
445
- const sy = Math.floor(0.99 * h);
446
- const ey = Math.floor(0.7 * h);
447
- await (0, hdc_1.swipe)(this.driver, sx, sy, sx, ey);
448
- }
449
- return `unlock_screen successfully`;
450
- }
451
- case 'clear_recent_task': {
452
- await this.clearRecentTasks();
453
- return `后台应用已清理`;
454
- }
455
- case 'enter_recent_task': {
456
- await this.driver.shell('uitest uiInput combinationKeyEvent 2076 2049');
457
- await sleepSync(1);
458
- return `enter_recent_task successfully`;
459
- }
460
- case 'get_current_app': {
461
- return await (0, hdc_1.getCurrentApp)(this.driver, false);
462
- }
463
- case 'screenshot': {
464
- const savePath = typeof a.save_path === 'string' ? a.save_path : '';
465
- const shot = await (0, hdc_1.getScreenshot)(this.driver, false);
466
- if (shot.width > 0 && shot.height > 0) {
467
- this.screenWidth = shot.width;
468
- this.screenHeight = shot.height;
469
- }
470
- if (savePath && shot.base64Data) {
471
- try {
472
- fs.mkdirSync(path.dirname(savePath), { recursive: true });
473
- fs.writeFileSync(savePath, Buffer.from(shot.base64Data, 'base64'));
474
- return savePath;
475
- }
476
- catch (e) {
477
- logger_1.logger.error(`screenshot save failed: ${e instanceof Error ? e.message : String(e)}`);
478
- }
479
- }
480
- return shot.base64Data ? 'screenshot captured' : 'screenshot failed';
481
- }
482
- case 'layout': {
483
- const shot = await (0, hdc_1.getScreenshot)(this.driver, true);
484
- return shot.layoutData || '';
485
- }
486
- case 'open_control_center': {
487
- const times = a.full_screen ? 2 : 1;
488
- for (let i = 0; i < times; i++) {
489
- const [sx, sy] = this.toAbsolute([0.8, 0]);
490
- const [ex, ey] = this.toAbsolute([0.8, 0.4]);
491
- await (0, hdc_1.swipe)(this.driver, sx, sy, ex, ey);
492
- }
493
- return `open_control_center successfully`;
494
- }
495
- case 'open_notification_center': {
496
- const times = a.full_screen ? 2 : 1;
497
- for (let i = 0; i < times; i++) {
498
- const [sx, sy] = this.toAbsolute([0.3, 0]);
499
- const [ex, ey] = this.toAbsolute([0.3, 0.4]);
500
- await (0, hdc_1.swipe)(this.driver, sx, sy, ex, ey);
501
- }
502
- return `open_notification_center successfully`;
503
- }
504
- case 'pinch_in': {
505
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
506
- const [cx, cy] = this.toAbsolute(rel);
507
- const radius = typeof a.radius === 'number' ? a.radius : 300;
508
- const scale = typeof a.scale === 'number' ? a.scale : 0.2;
509
- await this.pinchGesture(cx, cy, radius, scale);
510
- return `pinch_in (${this.fmt(rel)}) successfully`;
511
- }
512
- case 'pinch_out': {
513
- const rel = this.extractPoint(a, ['pos'], ['x', 'y']);
514
- const [cx, cy] = this.toAbsolute(rel);
515
- const radius = typeof a.radius === 'number' ? a.radius : 300;
516
- const scale = typeof a.scale === 'number' ? a.scale : 1.6;
517
- await this.pinchGesture(cx, cy, radius, scale);
518
- return `pinch_out (${this.fmt(rel)}) successfully`;
519
- }
520
- case 'rotate_gesture': {
521
- const rel = this.extractPoint(a, ['pos', 'center'], ['center_x', 'center_y']);
522
- const [cx, cy] = this.toAbsolute(rel);
523
- const angle = typeof a.angle === 'number' ? a.angle : 90;
524
- const clockwise = a.clockwise !== false;
525
- const radius = typeof a.radius === 'number' ? a.radius : 300;
526
- await this.rotateGesture(cx, cy, angle, clockwise, radius);
527
- return `rotate_gesture (${this.fmt(rel)}, angle=${angle}, clockwise=${clockwise}) successfully`;
528
- }
529
- case 'rotate_screen': {
530
- const direction = typeof a.direction === 'string' ? a.direction.toLowerCase() : 'portrait';
531
- const angle = direction === 'landscape' ? 270 : 0;
532
- let out = await this.driver.shell(`uitest uiInput setDisplayRotation ${angle}`);
533
- if (/error|fail|not found|not support/i.test(out)) {
534
- const orient = direction === 'landscape' ? 3 : 0;
535
- out = await this.driver.shell(`hidumper -s DisplayManagerService -a "-s 0 -o ${orient}"`);
536
- }
537
- return `rotate_screen ${direction} (angle=${angle}) result: ${out.trim() || 'ok'}`;
538
- }
539
- case 'stop_all_app': {
540
- await this.clearRecentTasks();
541
- return `stop_all_app successfully`;
542
- }
543
- case 'start_listen_toast': {
544
- this.startToastListener();
545
- return `start_listen_toast successfully`;
546
- }
547
- case 'get_toast': {
548
- const timeout = typeof a.timeout === 'number' ? a.timeout : 3;
549
- return await this.getLatestToast(timeout);
550
- }
551
- case 'start_data_collect': {
552
- return `start_data_collect acknowledged (no-op: collection not enabled in nodejs adapter)`;
553
- }
554
- case 'stop_data_collect': {
555
- return `stop_data_collect acknowledged (no-op: collection not enabled in nodejs adapter)`;
556
- }
557
- case 'generate_report': {
558
- return `generate_report acknowledged (nodejs uses reporter module)`;
559
- }
560
- case 'mcp_clean_up':
561
- case 'finish': {
562
- return `${name} acknowledged`;
563
- }
564
- default:
565
- return `Tool ${toolName} not available`;
566
- }
567
- }
568
- async checkDeviceConnected() {
569
- try {
570
- const out = await this.driver.listTargets();
571
- const connected = new Set();
572
- for (const line of out.split('\n')) {
573
- const parts = line.trim().split(/\s+/).filter(Boolean);
574
- if (parts.length === 0)
575
- continue;
576
- if (/no\s+target|empty|nil/i.test(line))
577
- continue;
578
- const state = parts.slice(1).join(' ');
579
- if (/offline|unavailable|disconnect/i.test(state))
580
- continue;
581
- connected.add(parts[0]);
582
- }
583
- const sn = this.driver.deviceSn;
584
- if (sn && sn !== 'default') {
585
- return connected.has(sn);
586
- }
587
- return connected.size > 0;
588
- }
589
- catch {
590
- return false;
591
- }
592
- }
593
- async setScreenAlwaysOn(enable) {
594
- const action = enable ? '-t' : '-f';
595
- await this.driver.shell(`hidumper -s PowerManagerService -a ${action}`);
596
- this.screenAlwaysOn = enable;
597
- }
598
- async isDisplayLocked() {
599
- try {
600
- const echo = await this.driver.shell('hidumper -s ScreenlockService -a -all');
601
- return /screenlocked.*true/i.test(echo);
602
- }
603
- catch {
604
- return false;
605
- }
606
- }
607
- async getScreenSize() {
608
- if (this.screenWidth > 0 && this.screenHeight > 0) {
609
- return [this.screenWidth, this.screenHeight];
610
- }
611
- const shot = await (0, hdc_1.getScreenshot)(this.driver, false);
612
- if (shot.width > 0 && shot.height > 0) {
613
- this.screenWidth = shot.width;
614
- this.screenHeight = shot.height;
615
- }
616
- else {
617
- this.screenWidth = SCREEN_SIZE_DEFAULT.width;
618
- this.screenHeight = SCREEN_SIZE_DEFAULT.height;
619
- }
620
- return [this.screenWidth, this.screenHeight];
621
- }
622
- toAbsolute(rel) {
623
- const w = this.screenWidth || SCREEN_SIZE_DEFAULT.width;
624
- const h = this.screenHeight || SCREEN_SIZE_DEFAULT.height;
625
- const x = Math.floor(Math.max(0, Math.min(rel[0], 1)) * w);
626
- const y = Math.floor(Math.max(0, Math.min(rel[1], 1)) * h);
627
- return [x, y];
628
- }
629
- fmt(rel) {
630
- const round = (v) => String(Math.round(v * 1e4) / 1e4);
631
- return `${round(rel[0])},${round(rel[1])}`;
632
- }
633
- extractPoint(args, tupleKeys, splitKeys) {
634
- for (const key of tupleKeys) {
635
- const v = args[key];
636
- if (Array.isArray(v) && v.length === 2 && typeof v[0] === 'number' && typeof v[1] === 'number') {
637
- return [v[0], v[1]];
638
- }
639
- }
640
- const x = args[splitKeys[0]];
641
- const y = args[splitKeys[1]];
642
- if (typeof x === 'number' && typeof y === 'number') {
643
- return [x, y];
644
- }
645
- if (typeof x === 'number') {
646
- return [x, 0];
647
- }
648
- if (typeof y === 'number') {
649
- return [0, y];
650
- }
651
- return [0, 0];
652
- }
653
- keyNameToCode(keyName) {
654
- switch (keyName) {
655
- case 'home': return 1;
656
- case 'power': return 18;
657
- case 'volume_up': return 16;
658
- case 'volume_down': return 17;
659
- default: return null;
660
- }
661
- }
662
- async clearRecentTasks() {
663
- await (0, hdc_1.home)(this.driver, 1);
664
- await sleepSync(1);
665
- const output = await this.driver.shell('aa dump -l');
666
- const bundles = new Set();
667
- for (const line of output.split('\n')) {
668
- const m = line.match(/bundle name \[([^\]]+)\]/);
669
- if (m && m[1]) {
670
- bundles.add(m[1]);
671
- }
672
- }
673
- for (const bundle of bundles) {
674
- try {
675
- await this.driver.shell(`aa force-stop ${bundle}`);
676
- }
677
- catch {
678
- // best-effort stop
679
- }
680
- }
681
- }
682
- async pinchGesture(cx, cy, radius, scale) {
683
- const segments = 8;
684
- const startRadius = scale < 1 ? radius : Math.round(radius / scale);
685
- const endRadius = Math.round(startRadius * scale);
686
- const duration = 0.5;
687
- const intervalMs = Math.max(20, Math.round((duration / segments) * 1000));
688
- const pts0 = [];
689
- const pts1 = [];
690
- for (let i = 0; i <= segments; i++) {
691
- const t = i / segments;
692
- const r = startRadius + (endRadius - startRadius) * t;
693
- pts0.push([Math.round(cx - r), Math.round(cy)]);
694
- pts1.push([Math.round(cx + r), Math.round(cy)]);
695
- }
696
- await this.driver.shell(`uinput -T -d ${pts0[0][0]} ${pts0[0][1]} -i 0`);
697
- await this.driver.shell(`uinput -T -d ${pts1[0][0]} ${pts1[0][1]} -i 1`);
698
- for (let i = 1; i <= segments; i++) {
699
- await this.driver.shell(`uinput -T -m ${pts0[i - 1][0]} ${pts0[i - 1][1]} ${pts0[i][0]} ${pts0[i][1]} ${intervalMs} -i 0`);
700
- await this.driver.shell(`uinput -T -m ${pts1[i - 1][0]} ${pts1[i - 1][1]} ${pts1[i][0]} ${pts1[i][1]} ${intervalMs} -i 1`);
701
- }
702
- await this.driver.shell(`uinput -T -u ${pts0[segments][0]} ${pts0[segments][1]} -i 0`);
703
- await this.driver.shell(`uinput -T -u ${pts1[segments][0]} ${pts1[segments][1]} -i 1`);
704
- }
705
- async rotateGesture(cx, cy, angle, clockwise, radius) {
706
- const segments = 8;
707
- const angleRad = (angle * Math.PI) / 180;
708
- const speed = 600;
709
- const arcLength = Math.abs(angleRad) * radius;
710
- const duration = arcLength / speed;
711
- const intervalMs = Math.max(20, Math.round((duration / segments) * 1000));
712
- const startAngle0 = clockwise ? 0 : Math.PI;
713
- const startAngle1 = clockwise ? Math.PI : 0;
714
- const pts0 = [];
715
- const pts1 = [];
716
- for (let i = 0; i <= segments; i++) {
717
- const t = i / segments;
718
- const a0 = startAngle0 + angleRad * t;
719
- const a1 = startAngle1 + angleRad * t;
720
- pts0.push([Math.round(cx + radius * Math.cos(a0)), Math.round(cy + radius * Math.sin(a0))]);
721
- pts1.push([Math.round(cx + radius * Math.cos(a1)), Math.round(cy + radius * Math.sin(a1))]);
722
- }
723
- await this.driver.shell(`uinput -T -d ${pts0[0][0]} ${pts0[0][1]} -i 0`);
724
- await this.driver.shell(`uinput -T -d ${pts1[0][0]} ${pts1[0][1]} -i 1`);
725
- for (let i = 1; i <= segments; i++) {
726
- await this.driver.shell(`uinput -T -m ${pts0[i - 1][0]} ${pts0[i - 1][1]} ${pts0[i][0]} ${pts0[i][1]} ${intervalMs} -i 0`);
727
- await this.driver.shell(`uinput -T -m ${pts1[i - 1][0]} ${pts1[i - 1][1]} ${pts1[i][0]} ${pts1[i][1]} ${intervalMs} -i 1`);
728
- }
729
- await this.driver.shell(`uinput -T -u ${pts0[segments][0]} ${pts0[segments][1]} -i 0`);
730
- await this.driver.shell(`uinput -T -u ${pts1[segments][0]} ${pts1[segments][1]} -i 1`);
731
- }
732
- startToastListener() {
733
- this.stopToastListener();
734
- this.toastBuffer = [];
735
- this.toastListening = true;
736
- try {
737
- this.toastListener = (0, child_process_1.spawn)(this.hdcPath, [
738
- '-s', `${this.ip}:${this.port}`, '-t', this.driver.deviceSn,
739
- 'shell', 'hilog',
740
- ], {
741
- stdio: ['ignore', 'pipe', 'pipe'],
742
- windowsHide: true,
743
- });
744
- this.toastListener.stdout?.on('data', (chunk) => {
745
- const lines = chunk.toString('utf-8').split('\n');
746
- for (const line of lines) {
747
- if (/toast/i.test(line)) {
748
- this.toastBuffer.push(line.trim());
749
- if (this.toastBuffer.length > 50)
750
- this.toastBuffer.shift();
751
- }
752
- }
753
- });
754
- this.toastListener.on('error', (err) => {
755
- logger_1.logger.warn(`toast listener error: ${err.message}`);
756
- });
757
- }
758
- catch (e) {
759
- logger_1.logger.warn(`start_listen_toast failed: ${e instanceof Error ? e.message : String(e)}`);
760
- }
761
- }
762
- stopToastListener() {
763
- if (this.toastListener) {
764
- const pid = this.toastListener.pid;
765
- try {
766
- if (os.platform() === 'win32' && pid) {
767
- // Windows: kill the entire process tree (hdc may spawn child processes)
768
- (0, child_process_1.execSync)(`taskkill /F /T /PID ${pid}`, { timeout: 5000, windowsHide: true });
769
- }
770
- else {
771
- this.toastListener.kill('SIGTERM');
772
- }
773
- }
774
- catch { /* best-effort */ }
775
- this.toastListener = null;
776
- }
777
- this.toastListening = false;
778
- }
779
- async getLatestToast(timeout) {
780
- const deadline = Date.now() + timeout * 1000;
781
- while (Date.now() < deadline) {
782
- if (this.toastBuffer.length > 0) {
783
- const latest = this.toastBuffer[this.toastBuffer.length - 1];
784
- this.toastBuffer = [];
785
- this.toastListening = false;
786
- return this.extractToastText(latest);
787
- }
788
- await sleepSync(0.3);
789
- }
790
- this.toastListening = false;
791
- return '';
792
- }
793
- extractToastText(line) {
794
- const match = line.match(/["']([^"']+)["']/);
795
- return match?.[1] ?? line;
796
- }
797
- }
798
- exports.HarmonyHdcAdapter = HarmonyHdcAdapter;