@autotest/agent 0.0.3 → 0.0.4

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 (68) hide show
  1. package/README.md +130 -75
  2. package/dist/api/agent_api.d.ts +2 -6
  3. package/dist/api/agent_api.js +6 -11
  4. package/dist/autotest-cli.js +9 -2
  5. package/dist/common/config/config.yaml +134 -0
  6. package/dist/common/model/custom_model.js +24 -5
  7. package/dist/common/path_utils.d.ts +7 -3
  8. package/dist/common/path_utils.js +12 -5
  9. package/dist/common/result_parser.js +1 -1
  10. package/dist/core/agent/layered_agent/decision.js +61 -23
  11. package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.d.ts +1 -1
  12. package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.js +5 -5
  13. package/dist/core/agent/layered_agent/execute_agent/parser/general_parser.js +1 -1
  14. package/dist/core/agent/layered_agent/execute_agent/parser/glm_parser.js +1 -1
  15. package/dist/core/agent/layered_agent/execute_agent/parser/mai_ui_parser.js +1 -1
  16. package/dist/core/agent/layered_agent/execute_agent/prompts.d.ts +1 -1
  17. package/dist/core/agent/layered_agent/execute_agent/prompts.js +5 -5
  18. package/dist/core/mcp/mcp_tools.d.ts +19 -2
  19. package/dist/core/mcp/mcp_tools.js +40 -12
  20. package/dist/core/memory/_utils.d.ts +18 -0
  21. package/dist/core/memory/_utils.js +140 -0
  22. package/dist/core/memory/replan_manager.d.ts +9 -0
  23. package/dist/core/memory/replan_manager.js +12 -0
  24. package/dist/core/memory/tool_player_popup.d.ts +66 -0
  25. package/dist/core/memory/tool_player_popup.js +276 -0
  26. package/dist/core/memory/tool_player_replan.d.ts +49 -0
  27. package/dist/core/memory/tool_player_replan.js +226 -0
  28. package/dist/core/memory/tool_player_xpath.d.ts +52 -0
  29. package/dist/core/memory/tool_player_xpath.js +139 -0
  30. package/dist/core/prompt/prompt_loader.js +3 -1
  31. package/dist/core/prompt/templates/debug/hypium/hypium_v2.0_optimize_scroll_search.md +310 -0
  32. package/dist/core/prompt/templates/debug/hypium/hypium_v2.0_relative_1000.md +284 -0
  33. package/dist/core/prompt/templates/debug/planner/planner_v3.0.md +140 -0
  34. package/dist/core/prompt/templates/debug/single/single_v2.0_optimize_scroll_search.md +272 -0
  35. package/dist/core/prompt/templates/debug/single/single_v2.0_relative_1000.md +277 -0
  36. package/dist/core/prompt/templates/single/single_v2.0_0_1000.md +315 -0
  37. package/dist/core/skill/skill_manager.js +4 -1
  38. package/dist/core/skill/skills/cancel-all-follows/SKILL.md +23 -0
  39. package/dist/core/skill/skills/create-local-image/SKILL.md +12 -0
  40. package/dist/core/skill/skills/create-local-video/SKILL.md +12 -0
  41. package/dist/core/skill/skills/dismiss-popups/SKILL.md +39 -0
  42. package/dist/core/skill/skills/douyin_test_skills.md +16 -0
  43. package/dist/data_types/case.d.ts +32 -0
  44. package/dist/data_types/case.js +57 -0
  45. package/dist/data_types/index.d.ts +2 -0
  46. package/dist/data_types/index.js +6 -1
  47. package/dist/data_types/screen.d.ts +12 -0
  48. package/dist/data_types/screen.js +23 -0
  49. package/dist/mcp-server/types.js +72 -50
  50. package/dist/reporter/generator.d.ts +0 -14
  51. package/dist/reporter/generator.js +18 -504
  52. package/dist/reporter/html_template/index.d.ts +56 -0
  53. package/dist/reporter/html_template/index.js +524 -0
  54. package/dist/reporter/json_report.d.ts +1 -0
  55. package/dist/reporter/json_report.js +6 -0
  56. package/dist/reporter/types.d.ts +1 -0
  57. package/dist/reporter/types.js +1 -0
  58. package/dist/tools/batch_runner.d.ts +3 -1
  59. package/dist/tools/batch_runner.js +13 -6
  60. package/dist/tools/case_runner/report.d.ts +9 -0
  61. package/dist/tools/case_runner/report.js +264 -0
  62. package/dist/tools/case_runner/runner.d.ts +57 -0
  63. package/dist/tools/case_runner/runner.js +410 -0
  64. package/dist/tools/config/config_tool.d.ts +13 -0
  65. package/dist/tools/config/config_tool.js +339 -0
  66. package/dist/tools/prompt_compare/compare_runner.d.ts +13 -0
  67. package/dist/tools/prompt_compare/compare_runner.js +360 -0
  68. package/package.json +7 -3
@@ -40,14 +40,18 @@ const fs = __importStar(require("fs"));
40
40
  const path = __importStar(require("path"));
41
41
  const PROJECT_ROOT_MARKERS = ['package.json', 'pyproject.toml'];
42
42
  /**
43
- * 定位打包后 dist 根目录(含 common/config/config.yaml)。
44
- * 兼容普通构建(模块在 dist/core/... 子目录)与单文件 bundle(模块在 dist/index.js):
45
- * 从 __dirname 向上查找直到出现 common/config/config.yaml。
43
+ * 定位打包后 dist 根目录。
44
+ *
45
+ * 查找策略(从 __dirname 向上遍历):
46
+ * 1. 优先检查目录同时包含 common/ 和 core/ 子目录(最可靠,不依赖具体文件)
47
+ * 2. 回退检查 common/config/config.yaml 存在(兼容旧逻辑)
48
+ *
49
+ * 兼容普通构建(模块在 dist/core/... 子目录)与单文件 bundle(模块在 dist/index.js)。
46
50
  */
47
51
  function findDistRoot() {
48
52
  let current = __dirname;
49
53
  for (let i = 0; i < 10; i++) {
50
- if (fs.existsSync(path.join(current, 'common', 'config', 'config.yaml'))) {
54
+ if (_isDistRoot(current)) {
51
55
  return current;
52
56
  }
53
57
  const parent = path.dirname(current);
@@ -57,6 +61,10 @@ function findDistRoot() {
57
61
  }
58
62
  return __dirname;
59
63
  }
64
+ function _isDistRoot(dir) {
65
+ return fs.existsSync(path.join(dir, 'common'))
66
+ && fs.existsSync(path.join(dir, 'core'));
67
+ }
60
68
  function findProjectRoot() {
61
69
  let current = path.resolve(process.cwd());
62
70
  for (let i = 0; i < 10; i++) {
@@ -70,7 +78,6 @@ function findProjectRoot() {
70
78
  break;
71
79
  current = parent;
72
80
  }
73
- // 与 Python 对齐:找不到 marker 时回退到 cwd(安装/打包运行场景),而非抛错
74
81
  return path.resolve(process.cwd());
75
82
  }
76
83
  function getReportBaseDir(config) {
@@ -4,7 +4,7 @@ exports.LONG_PRESS_ACTIONS = exports.DOUBLE_CLICK_ACTIONS = exports.SWIPE_LIKE_T
4
4
  exports.parseTaskResult = parseTaskResult;
5
5
  exports.hasVerdict = hasVerdict;
6
6
  const PASS_KEYWORDS = ['pass', 'passed', 'success', 'successful', 'complete', 'completed', '通过', '成功', '完成'];
7
- const FAIL_KEYWORDS = ['fail', 'failed', 'failure', 'incomplete', 'unsuccessful', '不通过', '失败', '未完成', '未成功'];
7
+ const FAIL_KEYWORDS = ['fail', 'failed', 'failure', 'incomplete', 'unsuccessful', '不通过', '失败', '未完成', '未成功', 'max steps', '最大步数', '步数超过'];
8
8
  function parseTaskResult(agentStatus, resultText) {
9
9
  if (agentStatus) {
10
10
  const lower = agentStatus.toLowerCase();
@@ -12,6 +12,7 @@ const model_1 = require("../../../common/model");
12
12
  const cache_transport_1 = require("../../../common/llm_cache/cache_transport");
13
13
  const prompt_loader_1 = require("../../prompt/prompt_loader");
14
14
  const skill_manager_1 = require("../../skill/skill_manager");
15
+ const utils_1 = require("../../../common/utils");
15
16
  const agent_registry_1 = require("./agent_registry");
16
17
  const agent_factory_1 = require("./execute_agent/agent_factory");
17
18
  function mkEvent(eventType, content, opts) {
@@ -34,14 +35,15 @@ function createClientConfig(config) {
34
35
  return config.model.decision;
35
36
  }
36
37
  const DEFAULT_MCP_TOOLS = [
37
- { name: 'tap', description: 'Tap at the given coordinates', parameters: { x: 'number', y: 'number' } },
38
- { name: 'double_tap', description: 'Double tap at the given coordinates', parameters: { x: 'number', y: 'number' } },
39
- { name: 'long_press', description: 'Long press at the given coordinates', parameters: { x: 'number', y: 'number' } },
40
- { name: 'swipe', description: 'Swipe from start to end coordinates', parameters: { start_x: 'number', start_y: 'number', end_x: 'number', end_y: 'number' } },
38
+ { name: 'tap', description: 'Tap at the given coordinates. Coordinates are normalized decimals 0.0~1.0: (0.0,0.0)=top-left, (1.0,1.0)=bottom-right. Do NOT output integers like 499; use 0.499 instead', parameters: { x: 'number', y: 'number' } },
39
+ { name: 'double_tap', description: 'Double tap at the given coordinates. Coordinates are normalized decimals 0.0~1.0', parameters: { x: 'number', y: 'number' } },
40
+ { name: 'long_press', description: 'Long press at the given coordinates. Coordinates are normalized decimals 0.0~1.0', parameters: { x: 'number', y: 'number' } },
41
+ { name: 'swipe', description: 'Swipe from start to end coordinates. Coordinates are normalized decimals 0.0~1.0: (0.0,0.0)=top-left, (1.0,1.0)=bottom-right. Do NOT output integers', parameters: { start_x: 'number', start_y: 'number', end_x: 'number', end_y: 'number' } },
41
42
  { name: 'back', description: 'Press back key', parameters: {} },
42
43
  { name: 'go_home', description: 'Go to home screen', parameters: {} },
43
44
  { name: 'start_app', description: 'Start an application by name', parameters: { app_name: 'string' } },
44
45
  { name: 'type_text', description: 'Type text into the focused input', parameters: { text: 'string' } },
46
+ { name: 'chat', description: 'Send a sub-task instruction to the executor (describe what to do in natural language, e.g. click a button, swipe, input text). The executor will look at the screen and perform the actual operation', parameters: { message: 'string' } },
45
47
  { name: 'finish', description: 'Finish the task with a result message', parameters: { message: 'string' } },
46
48
  ];
47
49
  function collectAllTools(adapter) {
@@ -118,22 +120,41 @@ function extractFirstJsonObject(text) {
118
120
  }
119
121
  return null;
120
122
  }
123
+ function tryParseToolCall(jsonText, fallback) {
124
+ try {
125
+ const parsed = JSON.parse(jsonText);
126
+ const name = parsed.name ?? parsed.action ?? '';
127
+ const argumentsObj = parsed.arguments ?? {};
128
+ const reasoning = parsed.reasoning ?? undefined;
129
+ if (name === 'finish' || name === 'answer' || name === 'terminate' || !name) {
130
+ return { isFinish: true, message: argumentsObj.message ?? fallback, reasoning };
131
+ }
132
+ return { toolCall: { name, arguments: argumentsObj }, isFinish: false, reasoning };
133
+ }
134
+ catch {
135
+ return null;
136
+ }
137
+ }
138
+ function repairCoordinateJson(text) {
139
+ let out = text;
140
+ out = out.replace(/"x"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\}/g, '"x": $1, "y": $2}');
141
+ out = out.replace(/"start_x"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*,\s*"end_x"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\}/g, '"start_x": $1, "start_y": $2, "end_x": $3, "end_y": $4}');
142
+ return out;
143
+ }
121
144
  function parsePlannerOutput(text) {
122
145
  const fenceMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
123
146
  const jsonText = fenceMatch?.[1]?.trim() ?? extractFirstJsonObject(text);
124
147
  if (jsonText) {
125
- try {
126
- const parsed = JSON.parse(jsonText);
127
- const name = parsed.name ?? parsed.action ?? '';
128
- const argumentsObj = parsed.arguments ?? {};
129
- if (name === 'finish' || name === 'answer' || name === 'terminate' || !name) {
130
- return { isFinish: true, message: argumentsObj.message ?? text };
131
- }
132
- return { toolCall: { name, arguments: argumentsObj }, isFinish: false };
133
- }
134
- catch {
135
- // fall through
148
+ const direct = tryParseToolCall(jsonText, text);
149
+ if (direct)
150
+ return direct;
151
+ const repaired = repairCoordinateJson(jsonText);
152
+ if (repaired !== jsonText) {
153
+ const fixed = tryParseToolCall(repaired, text);
154
+ if (fixed)
155
+ return fixed;
136
156
  }
157
+ return { isFinish: false, parseError: `Malformed planner JSON: ${jsonText}` };
137
158
  }
138
159
  return { isFinish: true, message: text };
139
160
  }
@@ -266,7 +287,7 @@ class DecisionPlanner {
266
287
  if (skillsMetadata) {
267
288
  systemPrompt += `\n\n## Available Skills\n${skillsMetadata}`;
268
289
  }
269
- systemPrompt += `\n\n## Available Tools\n${toolsText}\n\n## Output Format\nReturn a single tool call inside a json code fence: \`{"name": "tool_name", "arguments": {...}}\`. To finish, use the "finish" tool with a "message" argument that starts with PASS or FAIL.`;
290
+ systemPrompt += `\n\n## Available Tools\n${toolsText}\n\n## Output Format\nReturn a single JSON object inside a json code fence: \`{"reasoning": "<先简述当前屏幕观察,再声明完成条件/异常条件检查结论>", "name": "tool_name", "arguments": {...}}\`. The "reasoning" field is mandatory — every step must state your observation and judgment before the action. To finish, use \`{"reasoning": "<判定依据>", "name": "finish", "arguments": {"message": "PASS 或 FAIL - 原因"}}\`.\n\n## Coordinate System\nAll tap/swipe coordinates MUST be normalized decimals in 0.0~1.0: (0.0,0.0)=screen top-left, (1.0,1.0)=bottom-right. Never output integers (e.g. write 0.499, not 499) — integer coordinates will be mapped off-screen and the tap will miss.`;
270
291
  if (this.hooks) {
271
292
  await this.hooks.onAgentStart('layered');
272
293
  }
@@ -289,14 +310,29 @@ class DecisionPlanner {
289
310
  logger_1.logger.warn(`Failed to capture screenshot: ${e instanceof Error ? e.message : String(e)}`);
290
311
  }
291
312
  const decision = await this.planStep(task, systemPrompt, decisionModelConfig, screenshot);
292
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_OUTPUT, `Planner decision: ${decision.toolCall?.name ?? 'finish'}`, {
313
+ this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_OUTPUT, `Planner decision: ${decision.toolCall?.name ?? (decision.parseError ? 'parse_error' : 'finish')}`, {
293
314
  data: {
294
- action: decision.toolCall?.name ?? 'finish',
315
+ action: decision.toolCall?.name ?? (decision.parseError ? 'parse_error' : 'finish'),
295
316
  shouldFinish: decision.isFinish,
296
- reasoning: decision.message ?? '',
317
+ reasoning: decision.parseError ?? decision.reasoning ?? decision.message ?? '',
297
318
  },
298
319
  stepNumber: this.stepNumber,
299
320
  }));
321
+ if (decision.parseError) {
322
+ this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_PARSE_ERROR, `Planner output parse error at step ${this.stepNumber}`, {
323
+ data: { parseError: decision.parseError },
324
+ stepNumber: this.stepNumber,
325
+ }));
326
+ this.reportGenerator.addEvent(mkEvent(types_1.EventType.STEP_END, `Step ${this.stepNumber} skipped (planner output parse error, will retry next step)`, {
327
+ data: { status: 'ERROR', parseError: decision.parseError },
328
+ stepNumber: this.stepNumber,
329
+ }));
330
+ this.history.push(`Step ${this.stepNumber}: [parse error] ${decision.parseError}`);
331
+ if (this.hooks) {
332
+ await this.hooks.onLLMEnd('layered', this.stepNumber, { decision, executorResult: null });
333
+ }
334
+ continue;
335
+ }
300
336
  if (decision.isFinish) {
301
337
  finalOutput = decision.message ?? '';
302
338
  const extracted = extractResult(finalOutput);
@@ -326,6 +362,7 @@ class DecisionPlanner {
326
362
  if (this.hooks) {
327
363
  await this.hooks.onAgentEnd('layered', { finalOutput, status: finalStatus });
328
364
  }
365
+ this.reportGenerator.endTask(finalOutput, finalStatus);
329
366
  const savedFiles = await this.reportGenerator.saveAll();
330
367
  return { finalOutput, status: finalStatus, savedFiles };
331
368
  }
@@ -345,7 +382,7 @@ class DecisionPlanner {
345
382
  this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_START, `Planner observing screenshot for step ${this.stepNumber}`, { stepNumber: this.stepNumber }));
346
383
  this.reportGenerator.addEvent(mkEvent(types_1.EventType.LLM_CALL, `Planner LLM call for step ${this.stepNumber}`, { data: { role: 'planner' }, stepNumber: this.stepNumber }));
347
384
  const historyText = this.history.length > 0 ? this.history.join('\n') : 'none';
348
- const userPrompt = `Task: ${task}\n\nAction History:\n${historyText}\n\nObserve the current screenshot and decide the next action to advance the task. Return a single tool call in a json code fence.`;
385
+ const userPrompt = `Task: ${task}\n\nAction History:\n${historyText}\n\nObserve the current screenshot, state your observation and judgment (completion/exception check) in the "reasoning" field, then decide the next action. Return a single JSON object in a json code fence.`;
349
386
  const images = [];
350
387
  if (screenshot?.base64Data) {
351
388
  images.push({ base64Data: screenshot.base64Data, mimeType: 'image/jpeg' });
@@ -364,7 +401,8 @@ class DecisionPlanner {
364
401
  this.reportGenerator.addEvent(mkEvent(types_1.EventType.LLM_RESPONSE, `Planner LLM error: ${errMsg}`, { data: { simulated: true, role: 'planner' }, stepNumber: this.stepNumber }));
365
402
  return { isFinish: true, message: `Planner error: ${errMsg}` };
366
403
  }
367
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, llmResult.reasoning ?? llmResult.text, { stepNumber: this.stepNumber }));
404
+ const decision = parsePlannerOutput(llmResult.text);
405
+ this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_THINKING, decision.reasoning ?? llmResult.reasoning ?? llmResult.text, { stepNumber: this.stepNumber }));
368
406
  this.reportGenerator.addEvent(mkEvent(types_1.EventType.LLM_RESPONSE, `Planner LLM response for step ${this.stepNumber}`, {
369
407
  data: { text: llmResult.text.slice(0, 200), finishReason: llmResult.finishReason, role: 'planner' },
370
408
  stepNumber: this.stepNumber,
@@ -372,11 +410,12 @@ class DecisionPlanner {
372
410
  if (llmResult.tokenUsage) {
373
411
  this.reportGenerator.addTokenUsage(llmResult.tokenUsage, 'DecisionAgent', this.stepNumber);
374
412
  }
375
- return parsePlannerOutput(llmResult.text);
413
+ return decision;
376
414
  }
377
415
  async executeStep(toolCall, screenshot) {
378
416
  const toolName = toolCall.name;
379
417
  const toolArgs = toolCall.arguments;
418
+ (0, utils_1.normalizeToolCoordinates)(toolName, toolArgs);
380
419
  this.reportGenerator.addEvent(mkEvent(types_1.EventType.PLANNER_TOOL_CALL, `Planner delegated to executor: ${toolName}`, {
381
420
  data: { tool_name: toolName, arguments: toolArgs, delegated: this.executorAgent != null },
382
421
  stepNumber: this.stepNumber,
@@ -456,7 +495,6 @@ async function decisionChat(chatArgs) {
456
495
  }
457
496
  result = await planner.run(args.task);
458
497
  logger_1.logger.info(`Final Result: ${result.finalOutput}`);
459
- reportGenerator.endTask(result.finalOutput, result.status);
460
498
  }
461
499
  catch (e) {
462
500
  const errMsg = e instanceof Error ? e.message : String(e);
@@ -1,3 +1,3 @@
1
- export declare const MCP_SYSTEM_PROMPT_BASIC = "You are a GUI operation agent. You will receive a task description, an action history, a screen screenshot, and a set of tools used for device operations. You need to decide the next action to take to complete the task based on the current interface state. Please operate based on the current interface and the given task, do not speculate about user intent.\n\n# Output Format Requirements\n- Must include a thinking section that first summarizes the history of operations, especially repeatedly retried operations, the decision reason for the current operation step, and the operation description.\n- The thinking section should summarize in one sentence.\n\n# Notes\n## Decide based on screenshot and history\n - Please analyze the current interface content based on the provided screenshot and user instruction, and select the most appropriate operation from the tools. Your judgment must be based on visual recognition of the controls on the interface.\n## Retry principle\n - Please pay attention to the operation history; the same operation sequence should be retried at most 2 times. If the operation does not achieve the expected result, terminate execution directly and report the failure reason.\n## Execution conditions\n - Please confirm whether the execution conditions are met before execution. If the execution conditions are not met, terminate execution directly and report the failure reason.\n## Target description\n - Please confirm the operations required by the target description in the task list, and only complete the operations specified in the target description.\n## Expected result\n - Please confirm the expected result before execution. If the expected result has been achieved, report completion directly.\n## Swipe description\n - Swipe from left to right -> right\n - Swipe from top to bottom -> down\n - Swipe from bottom to top -> up\n - Swipe from right to left -> left\n## Coordinate description\n - The coordinate format is (x, y), the coordinate range is (0, 1000), do not exceed the coordinate range.\n\n## Supported MCP Tools\n";
1
+ export declare const MCP_SYSTEM_PROMPT_BASIC = "You are a GUI operation agent. You will receive a task description, an action history, a screen screenshot, and a set of tools used for device operations. You need to decide the next action to take to complete the task based on the current interface state. Please operate based on the current interface and the given task, do not speculate about user intent.\n\n# Output Format Requirements\n- Must include a thinking section that first summarizes the history of operations, especially repeatedly retried operations, the decision reason for the current operation step, and the operation description.\n- The thinking section should summarize in one sentence.\n\n# Notes\n## Decide based on screenshot and history\n - Please analyze the current interface content based on the provided screenshot and user instruction, and select the most appropriate operation from the tools. Your judgment must be based on visual recognition of the controls on the interface.\n## Retry principle\n - Please pay attention to the operation history; the same operation sequence should be retried at most 2 times. If the operation does not achieve the expected result, terminate execution directly and report the failure reason.\n## Execution conditions\n - Please confirm whether the execution conditions are met before execution. If the execution conditions are not met, terminate execution directly and report the failure reason.\n## Target description\n - Please confirm the operations required by the target description in the task list, and only complete the operations specified in the target description.\n## Expected result\n - Please confirm the expected result before execution. If the expected result has been achieved, report completion directly.\n## Swipe description\n - Swipe from left to right -> right\n - Swipe from top to bottom -> down\n - Swipe from bottom to top -> up\n - Swipe from right to left -> left\n## Coordinate description\n - The coordinate format is (x, y), the coordinate range is (0.000, 1.000), do not exceed the coordinate range.\n\n## Supported MCP Tools\n";
2
2
  export declare const MCP_SYSTEM_PROMPT_ALL: string;
3
3
  export declare const MCP_SYSTEM_PROMPT: string;
@@ -38,7 +38,7 @@ exports.MCP_SYSTEM_PROMPT_BASIC = `You are a GUI operation agent. You will recei
38
38
  - Swipe from bottom to top -> up
39
39
  - Swipe from right to left -> left
40
40
  ## Coordinate description
41
- - The coordinate format is (x, y), the coordinate range is (0, 1000), do not exceed the coordinate range.
41
+ - The coordinate format is (x, y), the coordinate range is (0.000, 1.000), do not exceed the coordinate range.
42
42
 
43
43
  ## Supported MCP Tools
44
44
  `;
@@ -82,11 +82,11 @@ ${'<thinking>\n' +
82
82
  '**Observation**: The current screen shows the Meituan home page, with address, search bar, scan icon, menu bar, image list, etc.\n' +
83
83
  '**Analysis**: I need to click the top search box and enter "Bawang Chaji".\n' +
84
84
  '**Usability check**: The page elements are available, without any occlusion.\n' +
85
- '**Decision**: The search box is located in the upper center of the screen, the coordinate is about [500, 100].\n' +
85
+ '**Decision**: The search box is located in the upper center of the screen, the coordinate is about [0.5, 0.1].\n' +
86
86
  '**Summary**: Next operation: click the search box.\n' +
87
87
  '</thinking>\n' +
88
88
  '```json\n' +
89
- '{"name": "tap", "arguments": {"x": 500, "y": 100}}\n' +
89
+ '{"name": "tap", "arguments": {"x": 0.5, "y": 0.1}}\n' +
90
90
  '```'}
91
91
 
92
92
  # Notes
@@ -113,7 +113,7 @@ ${'<thinking>\n' +
113
113
  - Swipe from bottom to top -> up, the X coordinate should remain unchanged.
114
114
  - Swipe from right to left -> left, the Y coordinate should remain unchanged.
115
115
  ## Coordinate description
116
- - The coordinate format is (x, y), the coordinate range is (0, 1000), do not exceed the coordinate range.
116
+ - The coordinate format is (x, y), the coordinate range is (0.000, 1.000), do not exceed the coordinate range.
117
117
  ## Operation guide
118
118
  - Special characters such as quotes and newlines in text input must be escaped.
119
119
  - Only return one action at a time, do not try to batch operations.
@@ -136,7 +136,7 @@ The thinking section should include:
136
136
 
137
137
  ### Common mistakes to avoid
138
138
  - Do not type directly without clicking the input box first.
139
- - Do not use coordinates outside the [0, 999] range.
139
+ - Do not use coordinates outside the [0.000, 1.000] range.
140
140
  - Do not omit the thinking tags.
141
141
  - Do not use comments or extra fields in the JSON.
142
142
  - Do not continuously perform multiple identical invalid operations.
@@ -24,7 +24,7 @@ function lenientParse(text) {
24
24
  }
25
25
  class GeneralParser {
26
26
  get coordinateScale() {
27
- return 1000;
27
+ return 1;
28
28
  }
29
29
  parse(rawResponse, screenWidth, screenHeight) {
30
30
  const content = rawResponse.trim();
@@ -26,7 +26,7 @@ function lenientParseValue(valueStr) {
26
26
  }
27
27
  class GLMParser {
28
28
  get coordinateScale() {
29
- return 1000;
29
+ return 1;
30
30
  }
31
31
  parse(rawResponse, screenWidth, screenHeight) {
32
32
  const actionStr = rawResponse.trim();
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MaiUiParser = void 0;
4
4
  class MaiUiParser {
5
5
  get coordinateScale() {
6
- return 1000;
6
+ return 1;
7
7
  }
8
8
  parse(llmOutput, _screenWidth, _screenHeight) {
9
9
  const result = this.parseTaggedText(llmOutput);
@@ -1 +1 @@
1
- export declare const SYSTEM_PROMPT = "You are the execution-layer Agent, responsible for strictly executing instructions from the superior (decision layer).\n\n## Core Positioning (Highest Priority)\n\nYou are the execution layer, not the decision layer.\n- Your responsibility: execute instructions from the superior, do not judge whether the instruction is meaningful.\n- Your superior (Planner): responsible for decisions, judging whether the task is complete.\n- Your role: tool executor, not task decision-maker.\n\n---\n\n## Mandatory Execution Rules (Must Follow)\n\nMust execute:\n- Receive an instruction from the superior then must execute, do not judge whether it is meaningful.\n- The superior asks to swipe then must swipe, do not judge whether there is content.\n- The superior asks to click then must click, do not judge whether it is correct.\n\nForbidden autonomous behaviors:\n- Forbidden to autonomously terminate (task completion is judged by the superior).\n- Forbidden to autonomously go back (going back is decided by the superior).\n- Forbidden to autonomously explore (exploration is planned by the superior).\n- Forbidden to judge whether an operation is meaningful.\n- Forbidden to think about whether you should go back to the previous level.\n- Forbidden to think about whether the task is complete.\n\n---\n\n## Output Format\n\nEach operation must contain two parts:\n1. Thinking process: describe observation and localization inside thinking tags.\n2. Action instruction: return a JSON function call inside a json code fence.\n\nExample:\n\n<thinking>\n**Observation**: The current screen shows a short-video playback interface, the superior asks to swipe up.\n**Localization**: The superior asks to swipe in the middle area of the screen, the coordinate area is about [300-700, 400-600].\n**Execution**: Swipe from bottom to top in the middle of the screen.\n</thinking>\n```json\n{\"name\": \"swipe\", \"arguments\": {\"direction\": \"up\", \"coordinate\": [500, 500]}}\n```\n\n---\n\n## Action Space (Strictly Follow)\n\n### Basic Operations\n- Click: {\"name\": \"click\", \"arguments\": {\"coordinate\": [x, y]}}\n Used to click the UI element specified by the superior.\n\n- Long press: {\"name\": \"long_press\", \"arguments\": {\"coordinate\": [x, y]}}\n Used to long-press the element specified by the superior.\n\n- Type text: {\"name\": \"type\", \"arguments\": {\"text\": \"text to input\"}}\n You must click the input box to focus it first, then use this action to input text.\n\n### Swipe Operations\n- Swipe: {\"name\": \"swipe\", \"arguments\": {\"direction\": \"up|down|left|right\", \"coordinate\": [x, y]}}\n direction options: up (swipe up), down (swipe down), left (swipe left), right (swipe right).\n coordinate: specifies the swipe start point (the position specified by the superior).\n\n- Drag: {\"name\": \"drag\", \"arguments\": {\"start_coordinate\": [x1, y1], \"end_coordinate\": [x2, y2]}}\n Used to drag an element to a new position (the start and end points specified by the superior).\n\n### System Operations\n- Open app: {\"name\": \"open\", \"arguments\": {\"text\": \"app name\"}}\n Used to open the app specified by the superior.\n\n### Wait Operations\n- Wait: {\"name\": \"wait\", \"arguments\": {}}\n Used to wait for the page to load (only used when the superior instruction includes waiting).\n\n---\n\n## Coordinate System\n- Range: both x and y are between [0, 999].\n- Origin: (0, 0) is the top-left corner of the screen.\n- Boundary: (999, 999) is the bottom-right corner of the screen.\n- Precision: coordinates are normalized and will be automatically mapped to the actual screen resolution.\n\n---\n\n## Thinking Process Template (Strictly Follow)\n\nOnly three parts:\n1. Observation: What does the current screen show? What is the operation target requested by the superior?\n2. Localization: Where is the element the superior asks to operate on? What are the coordinates?\n3. Execution: Return the execution instruction.\n\nForbidden to include:\n- Whether this operation is meaningful.\n- Whether you should go back to the previous level.\n- Whether the task is complete.\n- What to do when the target element cannot be found.\n- Slide to view when the page content is not fully displayed.\n\n---\n\n## Mandatory Principles Reiteration (Must Strictly Follow)\n\n- Strict execution: receive the instruction and must execute, do not judge the meaning.\n- No autonomy: no terminate, no autonomous back, no autonomous explore.\n- Observe-Locate-Execute: the thinking process only includes the three steps of observation, localization, and execution.";
1
+ export declare const SYSTEM_PROMPT = "You are the execution-layer Agent, responsible for strictly executing instructions from the superior (decision layer).\n\n## Core Positioning (Highest Priority)\n\nYou are the execution layer, not the decision layer.\n- Your responsibility: execute instructions from the superior, do not judge whether the instruction is meaningful.\n- Your superior (Planner): responsible for decisions, judging whether the task is complete.\n- Your role: tool executor, not task decision-maker.\n\n---\n\n## Mandatory Execution Rules (Must Follow)\n\nMust execute:\n- Receive an instruction from the superior then must execute, do not judge whether it is meaningful.\n- The superior asks to swipe then must swipe, do not judge whether there is content.\n- The superior asks to click then must click, do not judge whether it is correct.\n\nForbidden autonomous behaviors:\n- Forbidden to autonomously terminate (task completion is judged by the superior).\n- Forbidden to autonomously go back (going back is decided by the superior).\n- Forbidden to autonomously explore (exploration is planned by the superior).\n- Forbidden to judge whether an operation is meaningful.\n- Forbidden to think about whether you should go back to the previous level.\n- Forbidden to think about whether the task is complete.\n\n---\n\n## Output Format\n\nEach operation must contain two parts:\n1. Thinking process: describe observation and localization inside thinking tags.\n2. Action instruction: return a JSON function call inside a json code fence.\n\nExample:\n\n<thinking>\n**Observation**: The current screen shows a short-video playback interface, the superior asks to swipe up.\n**Localization**: The superior asks to swipe in the middle area of the screen, the coordinate area is about [0.3-0.7, 0.4-0.6].\n**Execution**: Swipe from bottom to top in the middle of the screen.\n</thinking>\n```json\n{\"name\": \"swipe\", \"arguments\": {\"direction\": \"up\", \"coordinate\": [0.5, 0.5]}}\n```\n\n---\n\n## Action Space (Strictly Follow)\n\n### Basic Operations\n- Click: {\"name\": \"click\", \"arguments\": {\"coordinate\": [x, y]}}\n Used to click the UI element specified by the superior.\n\n- Long press: {\"name\": \"long_press\", \"arguments\": {\"coordinate\": [x, y]}}\n Used to long-press the element specified by the superior.\n\n- Type text: {\"name\": \"type\", \"arguments\": {\"text\": \"text to input\"}}\n You must click the input box to focus it first, then use this action to input text.\n\n### Swipe Operations\n- Swipe: {\"name\": \"swipe\", \"arguments\": {\"direction\": \"up|down|left|right\", \"coordinate\": [x, y]}}\n direction options: up (swipe up), down (swipe down), left (swipe left), right (swipe right).\n coordinate: specifies the swipe start point (the position specified by the superior).\n\n- Drag: {\"name\": \"drag\", \"arguments\": {\"start_coordinate\": [x1, y1], \"end_coordinate\": [x2, y2]}}\n Used to drag an element to a new position (the start and end points specified by the superior).\n\n### System Operations\n- Open app: {\"name\": \"open\", \"arguments\": {\"text\": \"app name\"}}\n Used to open the app specified by the superior.\n\n### Wait Operations\n- Wait: {\"name\": \"wait\", \"arguments\": {}}\n Used to wait for the page to load (only used when the superior instruction includes waiting).\n\n---\n\n## Coordinate System\n- Range: both x and y are between [0.000, 1.000].\n- Origin: (0.000, 0.000) is the top-left corner of the screen.\n- Boundary: (1.000, 1.000) is the bottom-right corner of the screen.\n- Precision: coordinates are normalized and will be automatically mapped to the actual screen resolution.\n\n---\n\n## Thinking Process Template (Strictly Follow)\n\nOnly three parts:\n1. Observation: What does the current screen show? What is the operation target requested by the superior?\n2. Localization: Where is the element the superior asks to operate on? What are the coordinates?\n3. Execution: Return the execution instruction.\n\nForbidden to include:\n- Whether this operation is meaningful.\n- Whether you should go back to the previous level.\n- Whether the task is complete.\n- What to do when the target element cannot be found.\n- Slide to view when the page content is not fully displayed.\n\n---\n\n## Mandatory Principles Reiteration (Must Strictly Follow)\n\n- Strict execution: receive the instruction and must execute, do not judge the meaning.\n- No autonomy: no terminate, no autonomous back, no autonomous explore.\n- Observe-Locate-Execute: the thinking process only includes the three steps of observation, localization, and execution.";
@@ -39,11 +39,11 @@ Example:
39
39
 
40
40
  ${'<thinking>\n' +
41
41
  '**Observation**: The current screen shows a short-video playback interface, the superior asks to swipe up.\n' +
42
- '**Localization**: The superior asks to swipe in the middle area of the screen, the coordinate area is about [300-700, 400-600].\n' +
42
+ '**Localization**: The superior asks to swipe in the middle area of the screen, the coordinate area is about [0.3-0.7, 0.4-0.6].\n' +
43
43
  '**Execution**: Swipe from bottom to top in the middle of the screen.\n' +
44
44
  '</thinking>\n' +
45
45
  '```json\n' +
46
- '{"name": "swipe", "arguments": {"direction": "up", "coordinate": [500, 500]}}\n' +
46
+ '{"name": "swipe", "arguments": {"direction": "up", "coordinate": [0.5, 0.5]}}\n' +
47
47
  '```'}
48
48
 
49
49
  ---
@@ -79,9 +79,9 @@ ${'<thinking>\n' +
79
79
  ---
80
80
 
81
81
  ## Coordinate System
82
- - Range: both x and y are between [0, 999].
83
- - Origin: (0, 0) is the top-left corner of the screen.
84
- - Boundary: (999, 999) is the bottom-right corner of the screen.
82
+ - Range: both x and y are between [0.000, 1.000].
83
+ - Origin: (0.000, 0.000) is the top-left corner of the screen.
84
+ - Boundary: (1.000, 1.000) is the bottom-right corner of the screen.
85
85
  - Precision: coordinates are normalized and will be automatically mapped to the actual screen resolution.
86
86
 
87
87
  ---
@@ -7,12 +7,29 @@
7
7
  */
8
8
  /** A registered async tool function. */
9
9
  export type ToolFunction = (...args: any[]) => Promise<string>;
10
+ /** Metadata for a registered tool (aligned with python GlobalToolEntry). */
11
+ export interface ToolEntry {
12
+ name: string;
13
+ description: string;
14
+ parameters: Record<string, string>;
15
+ fn: ToolFunction;
16
+ }
10
17
  /** Registry of all collected tool functions, keyed by name. */
11
18
  export declare const TOOL_REGISTRY: Record<string, ToolFunction>;
19
+ /** Add tool names to the blacklist. */
20
+ export declare function addToBlacklist(...names: string[]): void;
12
21
  /**
13
- * Register a tool function into {@link TOOL_REGISTRY} and return it.
22
+ * Register a tool function with metadata into the registry.
23
+ * Aligned with python collect_function_tool — stores both the function and
24
+ * its description/parameters so collectAllTools can build the Available Tools
25
+ * list dynamically instead of a hardcoded array.
14
26
  */
15
- export declare function collectFunctionTool<T extends ToolFunction>(name: string, fn: T): T;
27
+ export declare function collectFunctionTool<T extends ToolFunction>(name: string, fn: T, meta?: {
28
+ description?: string;
29
+ parameters?: Record<string, string>;
30
+ }): T;
31
+ /** Get all registered tool entries, excluding blacklisted ones. */
32
+ export declare function getToolEntries(): ToolEntry[];
16
33
  /** Get all registered tool functions. */
17
34
  export declare function getRegisteredTools(): ToolFunction[];
18
35
  export declare const chat: (message: string) => Promise<string>;
@@ -41,7 +41,9 @@ var __importStar = (this && this.__importStar) || (function () {
41
41
  })();
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
43
  exports.loadSkill = exports.login = exports.goHome = exports.wait = exports.goBackTwice = exports.goBack = exports.clearApp = exports.stopApp = exports.startApp = exports.chat = exports.TOOL_REGISTRY = void 0;
44
+ exports.addToBlacklist = addToBlacklist;
44
45
  exports.collectFunctionTool = collectFunctionTool;
46
+ exports.getToolEntries = getToolEntries;
45
47
  exports.getRegisteredTools = getRegisteredTools;
46
48
  exports.getPackageNameMap = getPackageNameMap;
47
49
  exports.getMainAbilityForBundle = getMainAbilityForBundle;
@@ -55,13 +57,39 @@ const types_1 = require("../../reporter/types");
55
57
  const custom_model_1 = require("../../common/model/custom_model");
56
58
  /** Registry of all collected tool functions, keyed by name. */
57
59
  exports.TOOL_REGISTRY = {};
60
+ /** Ordered list of tool entries with metadata (aligned with python _GLOBAL_TOOL_REGISTRY). */
61
+ const _TOOL_ENTRIES = [];
62
+ /** Tool blacklist — names excluded from getToolEntries() (aligned with python _TOOL_BLACKLIST). */
63
+ const _TOOL_BLACKLIST = new Set(['login']);
64
+ /** Add tool names to the blacklist. */
65
+ function addToBlacklist(...names) {
66
+ for (const n of names)
67
+ _TOOL_BLACKLIST.add(n);
68
+ logger_1.logger.debug(`[ToolRegistry] Blacklisted: ${names.join(', ')}`);
69
+ }
58
70
  /**
59
- * Register a tool function into {@link TOOL_REGISTRY} and return it.
71
+ * Register a tool function with metadata into the registry.
72
+ * Aligned with python collect_function_tool — stores both the function and
73
+ * its description/parameters so collectAllTools can build the Available Tools
74
+ * list dynamically instead of a hardcoded array.
60
75
  */
61
- function collectFunctionTool(name, fn) {
76
+ function collectFunctionTool(name, fn, meta) {
62
77
  exports.TOOL_REGISTRY[name] = fn;
78
+ _TOOL_ENTRIES.push({
79
+ name,
80
+ description: meta?.description ?? `${name} tool`,
81
+ parameters: meta?.parameters ?? {},
82
+ fn,
83
+ });
84
+ logger_1.logger.debug(`[ToolRegistry] Registered: ${name}`);
63
85
  return fn;
64
86
  }
87
+ /** Get all registered tool entries, excluding blacklisted ones. */
88
+ function getToolEntries() {
89
+ if (_TOOL_BLACKLIST.size === 0)
90
+ return [..._TOOL_ENTRIES];
91
+ return _TOOL_ENTRIES.filter((e) => !_TOOL_BLACKLIST.has(e.name));
92
+ }
65
93
  /** Get all registered tool functions. */
66
94
  function getRegisteredTools() {
67
95
  return Object.values(exports.TOOL_REGISTRY);
@@ -108,7 +136,7 @@ exports.chat = collectFunctionTool('chat', async (message) => {
108
136
  _chatLock = null;
109
137
  resolveLock('');
110
138
  }
111
- });
139
+ }, { description: 'Send a sub-task instruction to the executor (describe what to do in natural language, e.g. click a button, swipe, input text). The executor will look at the screen and perform the actual operation', parameters: { message: 'string' } });
112
140
  async function _doChat(message) {
113
141
  logger_1.logger.info(`\n[Executor] Running: ${message}`);
114
142
  const executorAgent = getExecutorAgent();
@@ -207,7 +235,7 @@ async function doStartApp(appName) {
207
235
  /** Start an app by display name or bundle name. */
208
236
  exports.startApp = collectFunctionTool('start_app', async (appName) => {
209
237
  return doStartApp(appName);
210
- });
238
+ }, { description: 'Start an application by display name or bundle name', parameters: { app_name: 'string' } });
211
239
  /** Stop an app by display name or bundle name. */
212
240
  exports.stopApp = collectFunctionTool('stop_app', async (appName) => {
213
241
  const device = getExecutorDevice();
@@ -219,7 +247,7 @@ exports.stopApp = collectFunctionTool('stop_app', async (appName) => {
219
247
  await device.home();
220
248
  }
221
249
  return `stop ${appName} successfully. Task finished. Please output the final result now.`;
222
- });
250
+ }, { description: 'Stop an application by display name or bundle name', parameters: { app_name: 'string' } });
223
251
  /** Clear an app's data to simulate a first-install state. */
224
252
  exports.clearApp = collectFunctionTool('clear_app', async (appName) => {
225
253
  const device = getExecutorDevice();
@@ -230,12 +258,12 @@ exports.clearApp = collectFunctionTool('clear_app', async (appName) => {
230
258
  // ignore
231
259
  }
232
260
  return `clear ${appName} successfully`;
233
- });
261
+ }, { description: 'Clear an application data to simulate first-install state', parameters: { app_name: 'string' } });
234
262
  /** Press the back button once. */
235
263
  exports.goBack = collectFunctionTool('go_back', async () => {
236
264
  await getExecutorDevice().back();
237
265
  return 'go back successfully';
238
- });
266
+ }, { description: 'Press the back button once', parameters: {} });
239
267
  /** Press the back button twice. */
240
268
  exports.goBackTwice = collectFunctionTool('go_back_twice', async () => {
241
269
  const device = getExecutorDevice();
@@ -243,7 +271,7 @@ exports.goBackTwice = collectFunctionTool('go_back_twice', async () => {
243
271
  await sleep(1);
244
272
  await device.back();
245
273
  return 'go back twice successfully';
246
- });
274
+ }, { description: 'Press the back button twice', parameters: {} });
247
275
  /** Wait for a number of seconds. */
248
276
  exports.wait = collectFunctionTool('wait', async (times) => {
249
277
  await sleep(times);
@@ -252,16 +280,16 @@ exports.wait = collectFunctionTool('wait', async (times) => {
252
280
  seconds: times,
253
281
  message: `wait ${times} seconds successfully`,
254
282
  });
255
- });
283
+ }, { description: 'Wait for a specified number of seconds', parameters: { times: 'number' } });
256
284
  /** Press the home button to return to the desktop. */
257
285
  exports.goHome = collectFunctionTool('go_home', async () => {
258
286
  await getExecutorDevice().home();
259
287
  return 'go home successfully';
260
- });
288
+ }, { description: 'Press the home button to return to the desktop', parameters: {} });
261
289
  /** Login placeholder tool. */
262
290
  exports.login = collectFunctionTool('login', async () => {
263
291
  return JSON.stringify({ action: 'login', message: 'login successfully' });
264
- });
292
+ }, { description: 'Login placeholder tool', parameters: {} });
265
293
  /** Resolve the main ability name for a bundle name. */
266
294
  function getMainAbilityForBundle(bundleName) {
267
295
  return getMainAbility(bundleName);
@@ -278,7 +306,7 @@ exports.loadSkill = collectFunctionTool('load_skill', async (skillName) => {
278
306
  return `Skill '${skillName}' loaded successfully. Content:\n\n${content}`;
279
307
  }
280
308
  return `Skill '${skillName}' not found. Please check the skill name.`;
281
- });
309
+ }, { description: 'Load the detailed steps for a named skill', parameters: { skill_name: 'string' } });
282
310
  /**
283
311
  * Verify the task result based on recent execution history (screenshots + logs).
284
312
  * @param verificationDescription What to verify.
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Internal utility functions shared across memory module.
3
+ *
4
+ * Ported from python core/memory/_utils.py.
5
+ * Provides helpers for response text extraction, message filtering, retry
6
+ * decoration, and a lightweight TimeCalculate class used by ToolPlayer.
7
+ */
8
+ export declare function fallbackToGlobal<T>(config: unknown, extractor: (cfg: unknown) => T, validator?: ((value: T) => boolean) | null, label?: string, globalConfig?: unknown): T | null;
9
+ export declare function isValidModelConfig(modelConfig: unknown): boolean;
10
+ export declare function extractTextFromResponse(response: unknown): string;
11
+ export declare function filterImagesFromMessage(message: unknown): unknown;
12
+ export declare function retryOnException<T>(fn: () => Promise<T>, maxRetries?: number, delay?: number, backoff?: number): Promise<T>;
13
+ export declare class TimeCalculate {
14
+ startTime: Date;
15
+ endTime: Date;
16
+ constructor(startTime?: Date, endTime?: Date);
17
+ get duration(): number;
18
+ }