@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,283 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.LanceDBManager = void 0;
37
- const fs = __importStar(require("fs"));
38
- const path = __importStar(require("path"));
39
- const logger_1 = require("../../common/logger");
40
- // ---- Tokenizer ----
41
- function tokenize(text) {
42
- return text
43
- .toLowerCase()
44
- .replace(/[^\p{L}\p{N}\s]/gu, ' ')
45
- .split(/\s+/)
46
- .filter((t) => t.length > 0);
47
- }
48
- // ---- IDF computation ----
49
- function computeIdf(docs) {
50
- const df = new Map();
51
- const N = docs.length;
52
- for (const doc of docs) {
53
- const seen = new Set(doc.tokens);
54
- for (const token of seen) {
55
- df.set(token, (df.get(token) ?? 0) + 1);
56
- }
57
- }
58
- const idf = new Map();
59
- for (const [token, freq] of df) {
60
- idf.set(token, Math.log((N + 1) / (freq + 1)) + 1);
61
- }
62
- return idf;
63
- }
64
- // ---- TF-IDF vector ----
65
- function buildTfIdfVector(tokens, idf) {
66
- const tf = new Map();
67
- for (const t of tokens) {
68
- tf.set(t, (tf.get(t) ?? 0) + 1);
69
- }
70
- const vec = new Map();
71
- for (const [token, freq] of tf) {
72
- const idfVal = idf.get(token) ?? 1;
73
- vec.set(token, freq * idfVal);
74
- }
75
- return vec;
76
- }
77
- // ---- Cosine similarity ----
78
- function cosineSim(a, b) {
79
- let dot = 0;
80
- let normA = 0;
81
- let normB = 0;
82
- for (const [k, v] of a) {
83
- normA += v * v;
84
- const bv = b.get(k);
85
- if (bv !== undefined)
86
- dot += v * bv;
87
- }
88
- for (const v of b.values()) {
89
- normB += v * v;
90
- }
91
- if (normA === 0 || normB === 0)
92
- return 0;
93
- return dot / (Math.sqrt(normA) * Math.sqrt(normB));
94
- }
95
- class LanceDBManager {
96
- static _instance = null;
97
- static _initialized = false;
98
- dbPath;
99
- knowledgeDir;
100
- tableName;
101
- docs = [];
102
- docTokens = [];
103
- idf = new Map();
104
- constructor(dbPath, knowledgeDir, tableName = 'rag_docs') {
105
- this.dbPath = dbPath ?? path.join(__dirname, 'knowledge_store.json');
106
- this.knowledgeDir = knowledgeDir ?? path.join(process.cwd(), 'resources', 'knowledge');
107
- this.tableName = tableName;
108
- }
109
- static getInstance(dbPath, knowledgeDir) {
110
- if (LanceDBManager._instance === null) {
111
- LanceDBManager._instance = new LanceDBManager(dbPath, knowledgeDir);
112
- }
113
- if (!LanceDBManager._initialized) {
114
- LanceDBManager._instance.init();
115
- LanceDBManager._initialized = true;
116
- }
117
- return LanceDBManager._instance;
118
- }
119
- init() {
120
- this.loadFromStore();
121
- this.loadFromKnowledgeDir();
122
- this.rebuildIndex();
123
- logger_1.logger.info(`LanceDBManager initialized: ${this.docs.length} docs (table=${this.tableName}), TF-IDF index ready`);
124
- }
125
- rebuildIndex() {
126
- this.docTokens = this.docs.map((d) => ({ tokens: tokenize(d.text) }));
127
- this.idf = computeIdf(this.docTokens);
128
- logger_1.logger.debug(`LanceDBManager: rebuilt TF-IDF index, vocab size=${this.idf.size}`);
129
- }
130
- loadFromStore() {
131
- try {
132
- if (fs.existsSync(this.dbPath)) {
133
- const raw = fs.readFileSync(this.dbPath, 'utf-8');
134
- const parsed = JSON.parse(raw);
135
- if (Array.isArray(parsed)) {
136
- this.docs = parsed;
137
- }
138
- }
139
- }
140
- catch (e) {
141
- logger_1.logger.warning(`LanceDBManager: failed to load store: ${e}`);
142
- }
143
- }
144
- loadFromKnowledgeDir() {
145
- if (!fs.existsSync(this.knowledgeDir))
146
- return;
147
- const existingTexts = new Set(this.docs.map((d) => d.text));
148
- try {
149
- const files = fs.readdirSync(this.knowledgeDir).filter((f) => f.endsWith('.md'));
150
- for (const file of files) {
151
- const filePath = path.join(this.knowledgeDir, file);
152
- try {
153
- const content = fs.readFileSync(filePath, 'utf-8').trim();
154
- if (content && !existingTexts.has(content)) {
155
- this.docs.push({ id: `file:${file}`, text: content, metadata: { source: file } });
156
- existingTexts.add(content);
157
- }
158
- }
159
- catch (e) {
160
- logger_1.logger.error(`LanceDBManager: failed to load knowledge file ${file}: ${e}`);
161
- }
162
- }
163
- }
164
- catch (e) {
165
- logger_1.logger.warning(`LanceDBManager: failed to read knowledge dir: ${e}`);
166
- }
167
- }
168
- insertDocuments(docs) {
169
- if (!docs || docs.length === 0) {
170
- logger_1.logger.warning('LanceDBManager: no documents to insert');
171
- return;
172
- }
173
- logger_1.logger.info(`LanceDBManager: inserting ${docs.length} docs`);
174
- this.docs = [...docs];
175
- this.persist();
176
- this.rebuildIndex();
177
- logger_1.logger.info(`LanceDBManager: wrote ${docs.length} records to table '${this.tableName}'`);
178
- }
179
- addDocument(doc) {
180
- if (!doc.text)
181
- return;
182
- const existing = this.docs.find((d) => d.text === doc.text);
183
- if (existing) {
184
- existing.metadata = { ...existing.metadata, ...doc.metadata };
185
- }
186
- else {
187
- this.docs.push(doc);
188
- }
189
- this.persist();
190
- this.rebuildIndex();
191
- }
192
- /**
193
- * Incremental single-doc write.
194
- * Non-destructive: appends to the in-memory store (dedup by text) without
195
- * clobbering existing records. Falls back to appending a `_pending.jsonl`
196
- * line when persistence fails, so records are never lost.
197
- */
198
- addSingle(doc) {
199
- if (!doc.text)
200
- return;
201
- const existing = this.docs.find((d) => d.text === doc.text);
202
- if (existing) {
203
- existing.metadata = { ...existing.metadata, ...doc.metadata };
204
- }
205
- else {
206
- this.docs.push(doc);
207
- }
208
- try {
209
- this.persist();
210
- this.rebuildIndex();
211
- }
212
- catch (e) {
213
- logger_1.logger.warning(`LanceDBManager.addSingle: persist failed, writing jsonl fallback: ${e}`);
214
- this._writeJsonlFallback(doc);
215
- }
216
- }
217
- /** Append a single doc to `_pending.jsonl` (crash-safe fallback). */
218
- _writeJsonlFallback(doc) {
219
- try {
220
- const fallbackPath = path.join(path.dirname(this.dbPath), '_pending.jsonl');
221
- const dir = path.dirname(fallbackPath);
222
- if (!fs.existsSync(dir))
223
- fs.mkdirSync(dir, { recursive: true });
224
- fs.appendFileSync(fallbackPath, JSON.stringify(doc) + '\n', 'utf-8');
225
- }
226
- catch (e) {
227
- logger_1.logger.warning(`LanceDBManager._writeJsonlFallback failed: ${e}`);
228
- }
229
- }
230
- deleteCollection() {
231
- this.docs = [];
232
- this.docTokens = [];
233
- this.idf = new Map();
234
- try {
235
- if (fs.existsSync(this.dbPath))
236
- fs.writeFileSync(this.dbPath, '[]', 'utf-8');
237
- }
238
- catch (e) {
239
- logger_1.logger.warning(`LanceDBManager: failed to clear store: ${e}`);
240
- }
241
- logger_1.logger.info(`LanceDBManager: cleared table '${this.tableName}'`);
242
- }
243
- searchRaw(query, limit = 2) {
244
- return this.searchWithScores(query, limit).map((r) => r.doc);
245
- }
246
- searchWithScores(query, limit = 2) {
247
- const queryTokens = tokenize(query);
248
- if (queryTokens.length === 0 || this.docs.length === 0)
249
- return [];
250
- const queryVec = buildTfIdfVector(queryTokens, this.idf);
251
- const scored = this.docs
252
- .map((doc, i) => ({
253
- doc,
254
- score: cosineSim(queryVec, buildTfIdfVector(this.docTokens[i].tokens, this.idf)),
255
- }))
256
- .filter((entry) => entry.score > 0)
257
- .sort((a, b) => b.score - a.score);
258
- return scored.slice(0, limit);
259
- }
260
- search(query, limit = 2) {
261
- const results = this.searchWithScores(query, limit);
262
- if (results.length === 0)
263
- return '';
264
- return results
265
- .slice(1)
266
- .reduce((acc, r) => acc + '并且' + r.doc.text, results[0].doc.text);
267
- }
268
- getDocCount() {
269
- return this.docs.length;
270
- }
271
- persist() {
272
- try {
273
- const dir = path.dirname(this.dbPath);
274
- if (!fs.existsSync(dir))
275
- fs.mkdirSync(dir, { recursive: true });
276
- fs.writeFileSync(this.dbPath, JSON.stringify(this.docs, null, 2), 'utf-8');
277
- }
278
- catch (e) {
279
- logger_1.logger.warning(`LanceDBManager: failed to persist store: ${e}`);
280
- }
281
- }
282
- }
283
- exports.LanceDBManager = LanceDBManager;
@@ -1,99 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createAdapterFromDeviceInfo = createAdapterFromDeviceInfo;
4
- exports.detectDevicePlatform = detectDevicePlatform;
5
- const child_process_1 = require("child_process");
6
- const harmony_hdc_adapter_1 = require("./harmony_hdc_adapter");
7
- const android_adapter_1 = require("./android_adapter");
8
- const ios_adapter_1 = require("./ios_adapter");
9
- function createAdapterFromDeviceInfo(deviceInfo, configManager) {
10
- const config = configManager.getEffectiveConfig();
11
- const hdcPath = config.device.hdcPath;
12
- switch (deviceInfo.platform) {
13
- case 'harmony':
14
- // 纯 TS 设备适配器,直接驱动 hdc
15
- return new harmony_hdc_adapter_1.HarmonyHdcAdapter(hdcPath, configManager);
16
- case 'android':
17
- return new android_adapter_1.AndroidMCPAdapter('adb', configManager);
18
- case 'ios':
19
- return new ios_adapter_1.IOSMCPAdapter('devicectl', configManager);
20
- default:
21
- throw new Error(`不支持的平台: ${deviceInfo.platform}`);
22
- }
23
- }
24
- function detectDevicePlatform(deviceSn, config) {
25
- if (config.platform && typeof config.platform === 'string') {
26
- const p = config.platform;
27
- if (p === 'harmony' || p === 'android' || p === 'ios') {
28
- return p;
29
- }
30
- }
31
- if (config.adapterType && typeof config.adapterType === 'string') {
32
- const t = config.adapterType;
33
- if (t.includes('android') || t.includes('adb'))
34
- return 'android';
35
- if (t.includes('ios') || t.includes('devicectl'))
36
- return 'ios';
37
- if (t.includes('harmony') || t.includes('hdc') || t.includes('hypium'))
38
- return 'harmony';
39
- }
40
- const platform = tryHdcDetect(deviceSn, config);
41
- if (platform)
42
- return platform;
43
- const androidPlatform = tryAdbDetect(deviceSn, config);
44
- if (androidPlatform)
45
- return androidPlatform;
46
- throw new Error(`无法识别设备类型。请检查:\n`
47
- + `1. 设备是否已连接(hdc list targets / adb devices)\n`
48
- + `2. device_sn是否正确: ${deviceSn}\n`
49
- + `3. HDC或ADB工具是否可用`);
50
- }
51
- function tryHdcDetect(deviceSn, config) {
52
- const ip = config.ip;
53
- const port = config.port;
54
- try {
55
- if (ip && port) {
56
- (0, child_process_1.execSync)(`hdc tconn ${ip}:${port}`, { timeout: 5000 });
57
- }
58
- const listResult = (0, child_process_1.execSync)('hdc list targets', { encoding: 'utf-8', timeout: 5000 });
59
- if (listResult.trim()) {
60
- const devices = listResult.trim().split('\n').map((d) => d.trim()).filter(Boolean);
61
- if (deviceSn) {
62
- if (devices.includes(deviceSn)) {
63
- return 'harmony';
64
- }
65
- return null;
66
- }
67
- if (devices.length > 0) {
68
- return 'harmony';
69
- }
70
- }
71
- }
72
- catch {
73
- }
74
- return null;
75
- }
76
- function tryAdbDetect(deviceSn, config) {
77
- const ip = config.ip;
78
- const port = config.port;
79
- try {
80
- if (ip && port) {
81
- (0, child_process_1.execSync)(`adb connect ${ip}:${port}`, { timeout: 5000 });
82
- }
83
- if (deviceSn) {
84
- const result = (0, child_process_1.execSync)(`adb -s ${deviceSn} shell getprop ro.build.version.release`, { timeout: 5000 });
85
- if (result)
86
- return 'android';
87
- return null;
88
- }
89
- const listResult = (0, child_process_1.execSync)('adb devices', { encoding: 'utf-8', timeout: 5000 });
90
- const lines = listResult.trim().split('\n').slice(1);
91
- const deviceLines = lines.filter((l) => l.includes('device') && !l.includes('offline'));
92
- if (deviceLines.length > 0) {
93
- return 'android';
94
- }
95
- }
96
- catch {
97
- }
98
- return null;
99
- }
@@ -1,286 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.AndroidMCPAdapter = void 0;
37
- const net = __importStar(require("net"));
38
- const path = __importStar(require("path"));
39
- const fs = __importStar(require("fs"));
40
- const os = __importStar(require("os"));
41
- const child_process_1 = require("child_process");
42
- const base_adapter_1 = require("./base_adapter");
43
- const common_errors_1 = require("../../common/common_errors");
44
- class AndroidMCPAdapter extends base_adapter_1.MCPDeviceAdapterBase {
45
- platform = 'android';
46
- adbPath;
47
- mcpProcess = null;
48
- mcpServerUrl = null;
49
- logFilePath = null;
50
- logStream = null;
51
- static MCP_SERVICE_PORT = 8711;
52
- static SCREENSHOT_TOOL_NAME = 'mobile_take_screenshot';
53
- static PRESS_BUTTON_TOOL = 'mobile_press_button';
54
- constructor(adbPath = 'adb', configManager) {
55
- super(configManager);
56
- this.adbPath = adbPath;
57
- }
58
- getDefaultServerUrl() {
59
- return `http://127.0.0.1:${AndroidMCPAdapter.MCP_SERVICE_PORT}/mcp`;
60
- }
61
- getMcpServicePort() {
62
- return AndroidMCPAdapter.MCP_SERVICE_PORT;
63
- }
64
- useSseTransport() {
65
- return true;
66
- }
67
- async startMcpService() {
68
- const config = this.configManager.getEffectiveConfig();
69
- const port = AndroidMCPAdapter.MCP_SERVICE_PORT;
70
- await this.killProcessByPort(port);
71
- await new Promise((r) => setTimeout(r, 1000));
72
- const env = {
73
- ...Object.fromEntries(Object.entries(process.env).filter(([, v]) => v != null)),
74
- };
75
- if (config.device.deviceSn) {
76
- env.ANDROID_SERIAL = config.device.deviceSn;
77
- }
78
- const logDir = path.join(config.output.rootDir, 'log');
79
- fs.mkdirSync(logDir, { recursive: true });
80
- const timestamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
81
- this.logFilePath = path.join(logDir, `mobile_mcp_android_${timestamp}.log`);
82
- this.logStream = fs.createWriteStream(this.logFilePath, { flags: 'w' });
83
- const npxCmd = os.platform() === 'win32' ? 'npx.cmd' : 'npx';
84
- try {
85
- this.mcpProcess = (0, child_process_1.spawn)(npxCmd, ['-y', '@mobilenext/mobile-mcp@latest', '--listen', `0.0.0.0:${port}`], { env, cwd: process.cwd(), stdio: ['ignore', 'pipe', 'pipe'] });
86
- this.mcpProcess.stdout?.pipe(this.logStream);
87
- this.mcpProcess.stderr?.pipe(this.logStream);
88
- this.mcpProcess.on('error', (err) => {
89
- if (this.logFilePath) {
90
- fs.appendFileSync(this.logFilePath, `mobile_mcp process error: ${err.message}\n`);
91
- }
92
- });
93
- }
94
- catch (err) {
95
- this.closeLogStream();
96
- throw new common_errors_1.AgentError('MCP_SERVICE_TIMEOUT', `mobile-mcp start failed: ${err instanceof Error ? err.message : String(err)}`);
97
- }
98
- const serverUrl = this.getDefaultServerUrl();
99
- for (let attempt = 0; attempt < 20; attempt++) {
100
- await new Promise((r) => setTimeout(r, 1000));
101
- if (await this.isPortListening('127.0.0.1', port)) {
102
- return serverUrl;
103
- }
104
- }
105
- throw new common_errors_1.AgentError('MCP_SERVICE_TIMEOUT', `mobile-mcp service start timeout (20s), port ${port} not listening`);
106
- }
107
- async checkServiceHealth(serverUrl) {
108
- if (this.mcpProcess && this.mcpProcess.exitCode !== null) {
109
- return { isHealthy: false, status: 'notRunning' };
110
- }
111
- const portListening = await this.isPortListening('127.0.0.1', AndroidMCPAdapter.MCP_SERVICE_PORT);
112
- if (!portListening) {
113
- return { isHealthy: false, status: 'notRunning' };
114
- }
115
- try {
116
- const response = await fetch(serverUrl, {
117
- method: 'POST',
118
- headers: { 'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream' },
119
- body: JSON.stringify({ jsonrpc: '2.0', method: 'ping', id: 1 }),
120
- signal: AbortSignal.timeout(5000),
121
- });
122
- if (response.ok) {
123
- return { isHealthy: true, status: 'healthy' };
124
- }
125
- return { isHealthy: false, status: 'error' };
126
- }
127
- catch {
128
- return { isHealthy: false, status: 'error' };
129
- }
130
- }
131
- async killProcessByPort(port) {
132
- const sys = os.platform();
133
- try {
134
- if (sys === 'win32') {
135
- const result = (0, child_process_1.execSync)('netstat -ano', { encoding: 'utf-8', timeout: 5000 });
136
- for (const line of result.split('\n')) {
137
- if (line.includes(`:${port}`) && line.includes('LISTENING')) {
138
- const parts = line.trim().split(/\s+/);
139
- const pid = parts[parts.length - 1];
140
- (0, child_process_1.execSync)(`taskkill /F /PID ${pid}`, { timeout: 5000 });
141
- return;
142
- }
143
- }
144
- }
145
- else {
146
- const result = (0, child_process_1.execSync)(`lsof -ti:${port}`, { encoding: 'utf-8', timeout: 5000 });
147
- if (result.trim()) {
148
- const pid = result.trim().split('\n')[0];
149
- (0, child_process_1.execSync)(`kill -9 ${pid}`, { timeout: 5000 });
150
- }
151
- }
152
- }
153
- catch {
154
- // port cleanup failed, not blocking main flow
155
- }
156
- }
157
- async callTool(toolName, args, timeout, retryOnFailure) {
158
- if (!this.connected) {
159
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', 'Adapter not connected');
160
- }
161
- const config = this.configManager.getEffectiveConfig();
162
- const effectiveArgs = { ...(args ?? {}) };
163
- if (!effectiveArgs.device && config.device.deviceSn) {
164
- effectiveArgs.device = config.device.deviceSn;
165
- }
166
- const serverUrl = this.mcpServerUrl ?? this.getDefaultServerUrl();
167
- const effectiveTimeout = timeout ?? 60;
168
- const shouldRetry = retryOnFailure ?? true;
169
- try {
170
- const response = await fetch(serverUrl, {
171
- method: 'POST',
172
- headers: { 'Content-Type': 'application/json' },
173
- body: JSON.stringify({
174
- jsonrpc: '2.0',
175
- method: 'tools/call',
176
- id: Date.now(),
177
- params: { name: toolName, arguments: effectiveArgs },
178
- }),
179
- signal: this.getCallSignal(effectiveTimeout * 1000),
180
- });
181
- if (!response.ok) {
182
- throw new Error(`MCP tool call HTTP error: ${response.status}`);
183
- }
184
- const json = await response.json();
185
- if (json.error) {
186
- throw new Error(json.error.message);
187
- }
188
- return json.result;
189
- }
190
- catch (err) {
191
- if (!shouldRetry || this.isAborted()) {
192
- throw new common_errors_1.AgentError('MCP_SERVICE_TIMEOUT', err instanceof Error ? err.message : String(err));
193
- }
194
- try {
195
- await this.ensureServiceRunning(true);
196
- const retryUrl = this.getDefaultServerUrl();
197
- const retryResponse = await fetch(retryUrl, {
198
- method: 'POST',
199
- headers: { 'Content-Type': 'application/json' },
200
- body: JSON.stringify({
201
- jsonrpc: '2.0',
202
- method: 'tools/call',
203
- id: Date.now(),
204
- params: { name: toolName, arguments: effectiveArgs },
205
- }),
206
- signal: this.getCallSignal(effectiveTimeout * 1000),
207
- });
208
- const retryJson = await retryResponse.json();
209
- if (retryJson.error) {
210
- throw new Error(retryJson.error.message);
211
- }
212
- return retryJson.result;
213
- }
214
- catch (retryErr) {
215
- throw new common_errors_1.AgentError('MCP_SERVICE_TIMEOUT', `tool call failed and reconnect failed: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`);
216
- }
217
- }
218
- }
219
- async getScreenshot() {
220
- if (!this.connected) {
221
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', 'Adapter not connected');
222
- }
223
- let base64Data = '';
224
- const result = await this.callTool(AndroidMCPAdapter.SCREENSHOT_TOOL_NAME);
225
- if (result && typeof result === 'object') {
226
- const content = result.content;
227
- if (Array.isArray(content) && content.length > 0) {
228
- const item = content[0];
229
- if (item.data) {
230
- base64Data = item.data;
231
- }
232
- }
233
- }
234
- return {
235
- base64Data,
236
- layoutData: '',
237
- width: 1080,
238
- height: 1920,
239
- isSensitive: false,
240
- screenshotPath: null,
241
- };
242
- }
243
- async reset() {
244
- if (!this.connected) {
245
- throw new common_errors_1.AgentError('DEVICE_NOT_CONNECTED', 'Adapter not connected');
246
- }
247
- try {
248
- await this.callTool(AndroidMCPAdapter.PRESS_BUTTON_TOOL, { button: 'HOME' }, 30, false);
249
- }
250
- catch {
251
- // timeout not treated as failure
252
- }
253
- }
254
- async connect() {
255
- await this.ensureServiceRunning();
256
- this.mcpServerUrl = this.getDefaultServerUrl();
257
- this.connected = true;
258
- }
259
- async disconnect() {
260
- await super.disconnect();
261
- this.mcpServerUrl = null;
262
- this.closeLogStream();
263
- if (this.mcpProcess) {
264
- this.mcpProcess.kill();
265
- this.mcpProcess = null;
266
- }
267
- this.logFilePath = null;
268
- }
269
- closeLogStream() {
270
- if (this.logStream) {
271
- this.logStream.end();
272
- this.logStream = null;
273
- }
274
- }
275
- async isPortListening(host, port) {
276
- return new Promise((resolve) => {
277
- const socket = new net.Socket();
278
- socket.setTimeout(2000);
279
- socket.on('connect', () => { socket.destroy(); resolve(true); });
280
- socket.on('error', () => { socket.destroy(); resolve(false); });
281
- socket.on('timeout', () => { socket.destroy(); resolve(false); });
282
- socket.connect(port, host);
283
- });
284
- }
285
- }
286
- exports.AndroidMCPAdapter = AndroidMCPAdapter;