@autotest/agent 0.0.3 → 0.0.5
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.
- package/README.md +130 -75
- package/dist/api/agent_api.d.ts +2 -6
- package/dist/api/agent_api.js +6 -11
- package/dist/autotest-cli.js +9 -2
- package/dist/common/config/config.yaml +134 -0
- package/dist/common/model/custom_model.js +63 -5
- package/dist/common/path_utils.d.ts +7 -3
- package/dist/common/path_utils.js +12 -5
- package/dist/common/result_parser.js +1 -1
- package/dist/core/agent/layered_agent/decision.js +61 -23
- package/dist/core/agent/layered_agent/execute_agent/general_agent.js +1 -1
- package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.d.ts +1 -1
- package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.js +5 -5
- package/dist/core/agent/layered_agent/execute_agent/parser/general_parser.js +1 -1
- package/dist/core/agent/layered_agent/execute_agent/parser/glm_parser.js +1 -1
- package/dist/core/agent/layered_agent/execute_agent/parser/mai_ui_parser.js +1 -1
- package/dist/core/agent/layered_agent/execute_agent/prompts.d.ts +1 -1
- package/dist/core/agent/layered_agent/execute_agent/prompts.js +5 -5
- package/dist/core/mcp/mcp_tools.d.ts +19 -2
- package/dist/core/mcp/mcp_tools.js +40 -12
- package/dist/core/memory/_utils.d.ts +18 -0
- package/dist/core/memory/_utils.js +140 -0
- package/dist/core/memory/replan_manager.d.ts +9 -0
- package/dist/core/memory/replan_manager.js +12 -0
- package/dist/core/memory/tool_player_popup.d.ts +66 -0
- package/dist/core/memory/tool_player_popup.js +276 -0
- package/dist/core/memory/tool_player_replan.d.ts +49 -0
- package/dist/core/memory/tool_player_replan.js +226 -0
- package/dist/core/memory/tool_player_xpath.d.ts +52 -0
- package/dist/core/memory/tool_player_xpath.js +139 -0
- package/dist/core/prompt/prompt_loader.js +3 -1
- package/dist/core/prompt/templates/debug/hypium/hypium_v2.0_optimize_scroll_search.md +310 -0
- package/dist/core/prompt/templates/debug/hypium/hypium_v2.0_relative_1000.md +284 -0
- package/dist/core/prompt/templates/debug/planner/planner_v3.0.md +140 -0
- package/dist/core/prompt/templates/debug/single/single_v2.0_optimize_scroll_search.md +272 -0
- package/dist/core/prompt/templates/debug/single/single_v2.0_relative_1000.md +277 -0
- package/dist/core/prompt/templates/single/single_v2.0_0_1000.md +315 -0
- package/dist/core/skill/skill_manager.js +4 -1
- package/dist/core/skill/skills/cancel-all-follows/SKILL.md +23 -0
- package/dist/core/skill/skills/create-local-image/SKILL.md +12 -0
- package/dist/core/skill/skills/create-local-video/SKILL.md +12 -0
- package/dist/core/skill/skills/dismiss-popups/SKILL.md +39 -0
- package/dist/core/skill/skills/douyin_test_skills.md +16 -0
- package/dist/data_types/case.d.ts +32 -0
- package/dist/data_types/case.js +57 -0
- package/dist/data_types/index.d.ts +2 -0
- package/dist/data_types/index.js +6 -1
- package/dist/data_types/screen.d.ts +12 -0
- package/dist/data_types/screen.js +23 -0
- package/dist/mcp-server/types.js +72 -50
- package/dist/reporter/generator.d.ts +0 -14
- package/dist/reporter/generator.js +18 -504
- package/dist/reporter/html_template/index.d.ts +56 -0
- package/dist/reporter/html_template/index.js +524 -0
- package/dist/reporter/json_report.d.ts +1 -0
- package/dist/reporter/json_report.js +6 -0
- package/dist/reporter/types.d.ts +1 -0
- package/dist/reporter/types.js +1 -0
- package/dist/tools/batch_runner.d.ts +3 -1
- package/dist/tools/batch_runner.js +21 -6
- package/dist/tools/case_runner/report.d.ts +9 -0
- package/dist/tools/case_runner/report.js +264 -0
- package/dist/tools/case_runner/runner.d.ts +57 -0
- package/dist/tools/case_runner/runner.js +410 -0
- package/dist/tools/config/config_tool.d.ts +13 -0
- package/dist/tools/config/config_tool.js +339 -0
- package/dist/tools/prompt_compare/compare_runner.d.ts +13 -0
- package/dist/tools/prompt_compare/compare_runner.js +360 -0
- package/package.json +7 -3
|
@@ -88,6 +88,37 @@ function summarizeMessageContent(content) {
|
|
|
88
88
|
});
|
|
89
89
|
return `[${summaries.join(' | ')}]`;
|
|
90
90
|
}
|
|
91
|
+
const MAX_IMAGES_PER_REQUEST = 3;
|
|
92
|
+
function capImagesInMessages(messages) {
|
|
93
|
+
const imagePositions = [];
|
|
94
|
+
for (let i = 0; i < messages.length; i++) {
|
|
95
|
+
const content = messages[i].content;
|
|
96
|
+
if (Array.isArray(content)) {
|
|
97
|
+
for (let j = 0; j < content.length; j++) {
|
|
98
|
+
const part = content[j];
|
|
99
|
+
if (part && typeof part === 'object') {
|
|
100
|
+
const type = part.type;
|
|
101
|
+
if (type === 'image_url' || type === 'image' || type === 'file') {
|
|
102
|
+
imagePositions.push([i, j]);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (imagePositions.length <= MAX_IMAGES_PER_REQUEST)
|
|
109
|
+
return messages;
|
|
110
|
+
const toRemove = new Set(imagePositions.slice(0, imagePositions.length - MAX_IMAGES_PER_REQUEST).map(([i, j]) => `${i},${j}`));
|
|
111
|
+
if (toRemove.size === 0)
|
|
112
|
+
return messages;
|
|
113
|
+
logger_1.logger.warn(`LLMCaller: capping ${imagePositions.length} images to ${MAX_IMAGES_PER_REQUEST} (removing ${toRemove.size} oldest)`);
|
|
114
|
+
return messages.map((msg, i) => {
|
|
115
|
+
const content = msg.content;
|
|
116
|
+
if (!Array.isArray(content))
|
|
117
|
+
return msg;
|
|
118
|
+
const newContent = content.filter((_, j) => !toRemove.has(`${i},${j}`));
|
|
119
|
+
return { ...msg, content: newContent };
|
|
120
|
+
});
|
|
121
|
+
}
|
|
91
122
|
class LLMCaller {
|
|
92
123
|
cacheTransport;
|
|
93
124
|
recordingFetch;
|
|
@@ -205,6 +236,10 @@ class LLMCaller {
|
|
|
205
236
|
return crypto.createHash('sha256').update(raw).digest('hex');
|
|
206
237
|
}
|
|
207
238
|
async call(opts) {
|
|
239
|
+
if (opts.images && opts.images.length > MAX_IMAGES_PER_REQUEST) {
|
|
240
|
+
logger_1.logger.warn(`LLMCaller: capping ${opts.images.length} images to ${MAX_IMAGES_PER_REQUEST}`);
|
|
241
|
+
opts = { ...opts, images: opts.images.slice(-MAX_IMAGES_PER_REQUEST) };
|
|
242
|
+
}
|
|
208
243
|
const cacheKey = this.computeCacheKey(opts);
|
|
209
244
|
const cached = await this.cacheTransport.getCachedResponse(cacheKey);
|
|
210
245
|
if (cached) {
|
|
@@ -245,8 +280,17 @@ class LLMCaller {
|
|
|
245
280
|
if (opts.systemPrompt)
|
|
246
281
|
logger_1.logger.debug(`LLM call() system prompt: ${opts.systemPrompt}`);
|
|
247
282
|
for (const m of messages) {
|
|
248
|
-
const content = typeof m.content === 'string'
|
|
249
|
-
|
|
283
|
+
const content = typeof m.content === 'string'
|
|
284
|
+
? m.content
|
|
285
|
+
: Array.isArray(m.content)
|
|
286
|
+
? m.content.filter((p) => p.type === 'text').map((p) => p.text ?? '').join('\n') || '[multimodal]'
|
|
287
|
+
: '[multimodal]';
|
|
288
|
+
if (m.role === 'user') {
|
|
289
|
+
logger_1.logger.info(`LLM call() message [user]: ${content}`);
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
logger_1.logger.debug(`LLM call() message [${m.role}]: ${content}`);
|
|
293
|
+
}
|
|
250
294
|
}
|
|
251
295
|
if (opts.tools)
|
|
252
296
|
logger_1.logger.debug(`LLM call() tools: ${Object.keys(opts.tools).join(', ')}`);
|
|
@@ -264,7 +308,7 @@ class LLMCaller {
|
|
|
264
308
|
generateOpts.tools = opts.tools;
|
|
265
309
|
}
|
|
266
310
|
const result = await (0, ai_1.generateText)(generateOpts);
|
|
267
|
-
logger_1.logger.
|
|
311
|
+
logger_1.logger.info(`LLM call() output → finishReason=${result.finishReason} text=${result.text}`);
|
|
268
312
|
if (result.toolCalls && result.toolCalls.length > 0) {
|
|
269
313
|
logger_1.logger.debug(`LLM call() toolCalls: ${result.toolCalls.map(tc => tc.toolName).join(', ')}`);
|
|
270
314
|
}
|
|
@@ -365,8 +409,22 @@ class LLMCaller {
|
|
|
365
409
|
const model = provider.chat(opts.modelConfig.name);
|
|
366
410
|
const tokenType = (0, token_usage_1.resolveTokenType)(opts.modelConfig.baseUrl);
|
|
367
411
|
logger_1.logger.debug(`LLM callWithMessages() input → model=${opts.modelConfig.name} messages=${opts.messages.length}`);
|
|
412
|
+
const cappedMessages = capImagesInMessages(opts.messages);
|
|
413
|
+
if (cappedMessages !== opts.messages) {
|
|
414
|
+
opts = { ...opts, messages: cappedMessages };
|
|
415
|
+
}
|
|
368
416
|
for (const m of opts.messages) {
|
|
369
|
-
|
|
417
|
+
const content = typeof m.content === 'string'
|
|
418
|
+
? m.content
|
|
419
|
+
: Array.isArray(m.content)
|
|
420
|
+
? m.content.filter((p) => p.type === 'text').map((p) => p.text ?? '').join('\n') || '[multimodal]'
|
|
421
|
+
: summarizeMessageContent(m.content);
|
|
422
|
+
if (m.role === 'user') {
|
|
423
|
+
logger_1.logger.info(`LLM callWithMessages() message [user]: ${content}`);
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
logger_1.logger.debug(`LLM callWithMessages() message [${m.role}]: ${summarizeMessageContent(m.content)}`);
|
|
427
|
+
}
|
|
370
428
|
}
|
|
371
429
|
if (opts.tools)
|
|
372
430
|
logger_1.logger.debug(`LLM callWithMessages() tools: ${Object.keys(opts.tools).join(', ')}`);
|
|
@@ -387,7 +445,7 @@ class LLMCaller {
|
|
|
387
445
|
generateOpts.tools = opts.tools;
|
|
388
446
|
}
|
|
389
447
|
const result = await (0, ai_1.generateText)(generateOpts);
|
|
390
|
-
logger_1.logger.
|
|
448
|
+
logger_1.logger.info(`LLM callWithMessages() output → finishReason=${result.finishReason} text=${result.text}`);
|
|
391
449
|
if (result.reasoningText)
|
|
392
450
|
logger_1.logger.debug(`LLM callWithMessages() reasoningText: ${result.reasoningText}`);
|
|
393
451
|
if (result.toolCalls && result.toolCalls.length > 0) {
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 定位打包后 dist
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* 定位打包后 dist 根目录。
|
|
3
|
+
*
|
|
4
|
+
* 查找策略(从 __dirname 向上遍历):
|
|
5
|
+
* 1. 优先检查目录同时包含 common/ 和 core/ 子目录(最可靠,不依赖具体文件)
|
|
6
|
+
* 2. 回退检查 common/config/config.yaml 存在(兼容旧逻辑)
|
|
7
|
+
*
|
|
8
|
+
* 兼容普通构建(模块在 dist/core/... 子目录)与单文件 bundle(模块在 dist/index.js)。
|
|
5
9
|
*/
|
|
6
10
|
export declare function findDistRoot(): string;
|
|
7
11
|
export declare function findProjectRoot(): string;
|
|
@@ -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
|
|
44
|
-
*
|
|
45
|
-
*
|
|
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 (
|
|
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
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
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);
|
|
@@ -105,6 +105,7 @@ class GeneralAgent extends base_agent_1.BaseAgent {
|
|
|
105
105
|
const textContent = `** Screen Info **\n\n${screenInfo}`;
|
|
106
106
|
this._context.push(message_builder_1.MessageBuilder.createUserMessage(textContent, screenshot.base64Data));
|
|
107
107
|
}
|
|
108
|
+
this.manageHistoryImages(this.agentConfig.maxHistoryImage);
|
|
108
109
|
let thinking = '';
|
|
109
110
|
let content = '';
|
|
110
111
|
let rawContent = '';
|
|
@@ -141,7 +142,6 @@ class GeneralAgent extends base_agent_1.BaseAgent {
|
|
|
141
142
|
stepNumber: this._stepCount,
|
|
142
143
|
}));
|
|
143
144
|
}
|
|
144
|
-
this.manageHistoryImages(this.agentConfig.maxHistoryImage);
|
|
145
145
|
this._context.push(message_builder_1.MessageBuilder.createAssistantMessage(rawContent));
|
|
146
146
|
let result;
|
|
147
147
|
try {
|
|
@@ -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,
|
|
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,
|
|
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 [
|
|
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":
|
|
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,
|
|
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,
|
|
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.
|
|
@@ -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
|
|
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 [
|
|
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 [
|
|
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": [
|
|
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,
|
|
83
|
-
- Origin: (0, 0) is the top-left corner of the screen.
|
|
84
|
-
- Boundary: (
|
|
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
|
|
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
|
|
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>;
|