@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,41 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentFactory = void 0;
4
- exports.createAgent = createAgent;
5
- const general_agent_1 = require("./general_agent");
6
- const glm_agent_1 = require("./glm_agent");
7
- const mai_ui_agent_1 = require("./mai_ui_agent");
8
- class AgentFactory {
9
- static registry = {};
10
- static loaded = false;
11
- static register(name, factory) {
12
- AgentFactory.registry[name] = factory;
13
- }
14
- static getAgentFactory(provider) {
15
- if (!AgentFactory.loaded) {
16
- AgentFactory.loadBuiltinAgents();
17
- }
18
- const factory = AgentFactory.registry[provider] ?? AgentFactory.registry['general'];
19
- if (!factory) {
20
- throw new Error(`No agent found for provider '${provider}' and default 'general' not available.`);
21
- }
22
- return factory;
23
- }
24
- static create(provider = 'glm', opts) {
25
- const factory = AgentFactory.getAgentFactory(provider);
26
- return factory(opts);
27
- }
28
- static loadBuiltinAgents() {
29
- if (AgentFactory.loaded) {
30
- return;
31
- }
32
- AgentFactory.loaded = true;
33
- AgentFactory.register('general', (opts) => new general_agent_1.GeneralAgent(opts));
34
- AgentFactory.register('glm', (opts) => new glm_agent_1.GLMAgent(opts));
35
- AgentFactory.register('mai-ui', (opts) => new mai_ui_agent_1.MaiUiAgent(opts));
36
- }
37
- }
38
- exports.AgentFactory = AgentFactory;
39
- function createAgent(provider = 'glm') {
40
- return AgentFactory.getAgentFactory(provider);
41
- }
@@ -1,112 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseAgent = void 0;
4
- const types_1 = require("../../../../reporter/types");
5
- class BaseAgent {
6
- modelConfig;
7
- agentConfig;
8
- device;
9
- confirmationCallback;
10
- thinkingCallback;
11
- takeoverCallback;
12
- reportGenerator;
13
- constructor(opts) {
14
- this.modelConfig = opts.modelConfig;
15
- this.agentConfig = opts.agentConfig;
16
- this.device = opts.device;
17
- this.confirmationCallback = opts.confirmationCallback ?? this.defaultConfirmation.bind(this);
18
- this.thinkingCallback = opts.thinkingCallback;
19
- this.takeoverCallback = opts.takeoverCallback ?? this.defaultTakeover.bind(this);
20
- this.reportGenerator = opts.reportGenerator ?? null;
21
- }
22
- /** Public accessor for the executor device (used by MCP tools). */
23
- getDevice() {
24
- return this.device;
25
- }
26
- /** Public accessor for the agent config (used by MCP tools). */
27
- getAgentConfig() {
28
- return this.agentConfig;
29
- }
30
- /** Public accessor for the model config (used by MCP tools). */
31
- getModelConfig() {
32
- return this.modelConfig;
33
- }
34
- /** Public accessor for the report generator (used by MCP tools). */
35
- getReportGenerator() {
36
- return this.reportGenerator;
37
- }
38
- init() {
39
- // default no-op
40
- }
41
- cleanUp() {
42
- return Promise.resolve();
43
- }
44
- defaultConfirmation(_message) {
45
- return true;
46
- }
47
- defaultTakeover(_message) {
48
- // default no-op
49
- }
50
- makeStepResult(success, finished, action, thinking, message) {
51
- return { success, finished, action: action ?? undefined, thinking, message };
52
- }
53
- async executeToolCall(toolCall, _screenshot) {
54
- const toolName = toolCall.name;
55
- const toolArgs = toolCall.arguments;
56
- if (this.reportGenerator) {
57
- this.reportGenerator.addEvent({
58
- eventType: types_1.EventType.GLM_STEP_START,
59
- timestamp: new Date().toISOString(),
60
- content: `Executor executing tool: ${toolName}`,
61
- data: { toolName, args: toolArgs, role: 'executor' },
62
- screenshotPath: null,
63
- stepNumber: null,
64
- });
65
- }
66
- try {
67
- const result = await this.device.callTool(toolName, toolArgs);
68
- const observation = result.output || (result.success ? 'OK' : result.errorMsg);
69
- let postScreenshotPath = null;
70
- try {
71
- const postScreenshot = await this.device.getScreenshot(undefined, true);
72
- postScreenshotPath = postScreenshot.screenshotPath ?? null;
73
- }
74
- catch {
75
- // post-screenshot capture failure is non-blocking
76
- }
77
- if (this.reportGenerator) {
78
- this.reportGenerator.addEvent({
79
- eventType: types_1.EventType.GLM_STEP_END,
80
- timestamp: new Date().toISOString(),
81
- content: `Executor finished tool: ${toolName}`,
82
- data: { success: result.success, observation },
83
- screenshotPath: postScreenshotPath,
84
- stepNumber: null,
85
- });
86
- }
87
- if (toolName === 'start_app' && observation.includes('failed!')) {
88
- throw new Error(`Task terminated: ${observation}, start_app timed out`);
89
- }
90
- return {
91
- success: result.success,
92
- observation,
93
- screenshotChanged: true,
94
- };
95
- }
96
- catch (e) {
97
- const errMsg = e instanceof Error ? e.message : String(e);
98
- if (this.reportGenerator) {
99
- this.reportGenerator.addEvent({
100
- eventType: types_1.EventType.GLM_STEP_END,
101
- timestamp: new Date().toISOString(),
102
- content: `Executor error: ${toolName} - ${errMsg}`,
103
- data: { success: false, observation: errMsg },
104
- screenshotPath: null,
105
- stepNumber: null,
106
- });
107
- }
108
- return { success: false, observation: errMsg, screenshotChanged: false };
109
- }
110
- }
111
- }
112
- exports.BaseAgent = BaseAgent;
@@ -1,207 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GeneralAgent = void 0;
4
- exports.getMessagesForAgent = getMessagesForAgent;
5
- const types_1 = require("../../../../reporter/types");
6
- const logger_1 = require("../../../../common/logger");
7
- const model_1 = require("../../../../common/model");
8
- const cache_transport_1 = require("../../../../common/llm_cache/cache_transport");
9
- const message_builder_1 = require("../../utils/message_builder");
10
- const base_agent_1 = require("./base_agent");
11
- const action_handler_1 = require("./action_handler");
12
- const parser_1 = require("./parser");
13
- const prompts_1 = require("./prompts");
14
- const i18n_1 = require("./i18n");
15
- function mkEvent(eventType, content, opts) {
16
- return {
17
- eventType,
18
- timestamp: new Date().toISOString(),
19
- content,
20
- data: opts?.data ?? {},
21
- screenshotPath: opts?.screenshotPath ?? null,
22
- stepNumber: opts?.stepNumber ?? null,
23
- };
24
- }
25
- class GeneralAgent extends base_agent_1.BaseAgent {
26
- llmCaller;
27
- parser;
28
- actionHandler;
29
- _context = [];
30
- _screenshot = [];
31
- _stepCount = 0;
32
- _isRunning = false;
33
- constructor(opts) {
34
- super(opts);
35
- this.llmCaller = opts.llmCaller ?? new model_1.LLMCaller(new cache_transport_1.CacheTransport(this.agentConfig.enableCache));
36
- this.parser = new parser_1.GeneralParser();
37
- this.actionHandler = new action_handler_1.ActionHandler(this.device, opts.confirmationCallback);
38
- }
39
- async run(task) {
40
- this._context = [];
41
- this._stepCount = 0;
42
- this._isRunning = true;
43
- try {
44
- let result = await this.executeStep(task, true);
45
- if (result.finished) {
46
- return result.message ?? 'Task completed';
47
- }
48
- while (this._stepCount < this.agentConfig.maxSteps && this._isRunning) {
49
- result = await this.executeStep(undefined, false);
50
- if (result.finished) {
51
- return result.message ?? 'Task completed';
52
- }
53
- }
54
- return 'Max steps reached';
55
- }
56
- finally {
57
- this._isRunning = false;
58
- }
59
- }
60
- reset() {
61
- this._context = [];
62
- this._screenshot = [];
63
- this._stepCount = 0;
64
- this._isRunning = false;
65
- }
66
- async streamRequest(messages, onThinkingChunk) {
67
- const llmResult = await this.llmCaller.callWithMessages({
68
- messages: (0, message_builder_1.toModelMessages)(messages),
69
- modelConfig: this.modelConfig,
70
- });
71
- const thinking = llmResult.reasoning ?? '';
72
- const content = llmResult.text;
73
- const rawContent = llmResult.text;
74
- if (llmResult.tokenUsage && this.reportGenerator) {
75
- this.reportGenerator.addTokenUsage(llmResult.tokenUsage, 'Executor(General)', this._stepCount);
76
- }
77
- if (onThinkingChunk) {
78
- if (thinking) {
79
- onThinkingChunk(thinking);
80
- }
81
- else {
82
- onThinkingChunk(content);
83
- }
84
- }
85
- return { thinking, content, rawContent };
86
- }
87
- async executeStep(userPrompt, isFirst = false) {
88
- this._stepCount += 1;
89
- if (this.reportGenerator) {
90
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.GLM_STEP_START, `Step ${this._stepCount} started`, { stepNumber: this._stepCount }));
91
- }
92
- const screenshot = await this.device.getScreenshot(undefined, true);
93
- const screenshotPath = screenshot.screenshotPath ?? '';
94
- this._screenshot.push(screenshotPath);
95
- const currentApp = await this.device.getCurrentApp();
96
- if (isFirst) {
97
- const systemPrompt = this.agentConfig.systemPrompt ?? prompts_1.SYSTEM_PROMPT;
98
- this._context.push(message_builder_1.MessageBuilder.createSystemMessage(systemPrompt));
99
- const screenInfo = message_builder_1.MessageBuilder.buildScreenInfo(currentApp);
100
- const textContent = `${userPrompt ?? ''}\n\n${screenInfo}`;
101
- this._context.push(message_builder_1.MessageBuilder.createUserMessage(textContent, screenshot.base64Data));
102
- }
103
- else {
104
- const screenInfo = message_builder_1.MessageBuilder.buildScreenInfo(currentApp);
105
- const textContent = `** Screen Info **\n\n${screenInfo}`;
106
- this._context.push(message_builder_1.MessageBuilder.createUserMessage(textContent, screenshot.base64Data));
107
- }
108
- this.manageHistoryImages(this.agentConfig.maxHistoryImage);
109
- let thinking = '';
110
- let content = '';
111
- let rawContent = '';
112
- try {
113
- let callback = this.thinkingCallback ?? undefined;
114
- if (!callback && this.agentConfig.streamLog) {
115
- callback = (chunk) => process.stdout.write(chunk);
116
- }
117
- const res = await this.streamRequest(this._context, callback ?? null);
118
- thinking = res.thinking;
119
- content = res.content;
120
- rawContent = res.rawContent;
121
- if (this.agentConfig.streamLog) {
122
- process.stdout.write('\n');
123
- }
124
- logger_1.logger.info(`Thinking: ${thinking}`);
125
- }
126
- catch (e) {
127
- logger_1.logger.error(`Model error: ${e instanceof Error ? e.message : String(e)}`);
128
- return this.makeStepResult(false, true, null, '', `Model error: ${e instanceof Error ? e.message : String(e)}`);
129
- }
130
- let action;
131
- try {
132
- action = this.parser.parse(content, screenshot.width, screenshot.height);
133
- }
134
- catch (e) {
135
- action = { _metadata: 'finish', message: e instanceof Error ? e.message : String(e) };
136
- }
137
- if (this.reportGenerator) {
138
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.GLM_THINKING, thinking, { stepNumber: this._stepCount }));
139
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.GLM_ACTION, `Action: ${JSON.stringify(action)}`, {
140
- data: { action, screen_width: screenshot.width, screen_height: screenshot.height },
141
- screenshotPath,
142
- stepNumber: this._stepCount,
143
- }));
144
- }
145
- this._context.push(message_builder_1.MessageBuilder.createAssistantMessage(rawContent));
146
- let result;
147
- try {
148
- result = await this.actionHandler.execute(action);
149
- }
150
- catch (e) {
151
- result = { success: false, shouldFinish: true, message: e instanceof Error ? e.message : String(e) };
152
- }
153
- if (this.reportGenerator) {
154
- const postScreenshot = await this.device.getScreenshot(undefined, true);
155
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.GLM_STEP_END, `Step ${this._stepCount} completed`, {
156
- data: { result: result.message, success: result.success },
157
- screenshotPath: postScreenshot.screenshotPath,
158
- stepNumber: this._stepCount,
159
- }));
160
- }
161
- const finished = action._metadata === 'finish' || result.shouldFinish;
162
- return this.makeStepResult(result.success, finished, action, thinking, result.message ?? action.message ?? '');
163
- }
164
- manageHistoryImages(keepCount) {
165
- if (keepCount < 0) {
166
- return;
167
- }
168
- const imageMsgIndices = [];
169
- for (let i = 0; i < this._context.length; i++) {
170
- const msg = this._context[i];
171
- if (msg.role === 'user' && Array.isArray(msg.content)) {
172
- const hasImage = msg.content.some((item) => item.type === 'image_url');
173
- if (hasImage) {
174
- imageMsgIndices.push(i);
175
- }
176
- }
177
- }
178
- if (imageMsgIndices.length > keepCount) {
179
- let indicesToPrune;
180
- if (keepCount === 0) {
181
- indicesToPrune = imageMsgIndices;
182
- }
183
- else {
184
- indicesToPrune = imageMsgIndices.slice(0, imageMsgIndices.length - keepCount);
185
- }
186
- for (const idx of indicesToPrune) {
187
- this._context[idx] = message_builder_1.MessageBuilder.removeImagesFromMessage(this._context[idx]);
188
- }
189
- }
190
- }
191
- get stepCount() {
192
- return this._stepCount;
193
- }
194
- get screenshot() {
195
- return [...this._screenshot];
196
- }
197
- get context() {
198
- return this._context.map((m) => m);
199
- }
200
- get isRunning() {
201
- return this._isRunning;
202
- }
203
- }
204
- exports.GeneralAgent = GeneralAgent;
205
- function getMessagesForAgent(lang) {
206
- return (0, i18n_1.getMessages)(lang);
207
- }
@@ -1,241 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GLMAgent = void 0;
4
- const types_1 = require("../../../../reporter/types");
5
- const logger_1 = require("../../../../common/logger");
6
- const model_1 = require("../../../../common/model");
7
- const cache_transport_1 = require("../../../../common/llm_cache/cache_transport");
8
- const message_builder_1 = require("../../utils/message_builder");
9
- const base_agent_1 = require("./base_agent");
10
- const action_handler_1 = require("./action_handler");
11
- const parser_1 = require("./parser");
12
- const prompts_1 = require("./prompts");
13
- const mcp_prompts_1 = require("./mcp_prompts");
14
- const i18n_1 = require("./i18n");
15
- function mkEvent(eventType, content, opts) {
16
- return {
17
- eventType,
18
- timestamp: new Date().toISOString(),
19
- content,
20
- data: opts?.data ?? {},
21
- screenshotPath: opts?.screenshotPath ?? null,
22
- stepNumber: opts?.stepNumber ?? null,
23
- };
24
- }
25
- function getSystemPrompt(lang = 'en', mode) {
26
- if (mode === 'mcp') {
27
- return mcp_prompts_1.MCP_SYSTEM_PROMPT;
28
- }
29
- return prompts_1.SYSTEM_PROMPT;
30
- }
31
- class GLMAgent extends base_agent_1.BaseAgent {
32
- llmCaller;
33
- parser;
34
- actionHandler;
35
- _context = [];
36
- _screenshot = [];
37
- _stepCount = 0;
38
- _isRunning = false;
39
- constructor(opts) {
40
- super(opts);
41
- this.llmCaller = opts.llmCaller ?? new model_1.LLMCaller(new cache_transport_1.CacheTransport(this.agentConfig.enableCache));
42
- this.parser = new parser_1.GLMParser();
43
- this.actionHandler = new action_handler_1.ActionHandler(this.device, opts.confirmationCallback, opts.takeoverCallback);
44
- }
45
- async run(task) {
46
- this._context = [];
47
- this._stepCount = 0;
48
- this._isRunning = true;
49
- try {
50
- let result = await this.executeStep(task, true);
51
- if (result.finished) {
52
- return result.message ?? 'Task completed';
53
- }
54
- while (this._stepCount < this.agentConfig.maxSteps && this._isRunning) {
55
- result = await this.executeStep(undefined, false);
56
- if (result.finished) {
57
- return result.message ?? 'Task completed';
58
- }
59
- }
60
- return 'Max steps reached';
61
- }
62
- finally {
63
- this._isRunning = false;
64
- }
65
- }
66
- step(task) {
67
- const isFirst = this._context.length === 0;
68
- if (isFirst && !task) {
69
- throw new Error('Task is required for the first step');
70
- }
71
- return this.executeStep(task, isFirst);
72
- }
73
- reset() {
74
- this._context = [];
75
- this._screenshot = [];
76
- this._stepCount = 0;
77
- this._isRunning = false;
78
- }
79
- abort() {
80
- this._isRunning = false;
81
- logger_1.logger.info('Agent aborted by user');
82
- }
83
- parseRawResponse(content) {
84
- const markerFinish = 'finish(message=';
85
- const idxFinish = content.indexOf(markerFinish);
86
- if (idxFinish >= 0) {
87
- const thinking = content.slice(0, idxFinish).trim();
88
- const action = markerFinish + content.slice(idxFinish + markerFinish.length);
89
- return { thinking, action };
90
- }
91
- const markerDo = 'do(action=';
92
- const idxDo = content.indexOf(markerDo);
93
- if (idxDo >= 0) {
94
- const thinking = content.slice(0, idxDo).trim();
95
- const action = markerDo + content.slice(idxDo + markerDo.length);
96
- return { thinking, action };
97
- }
98
- const tagOpen = '<answer>';
99
- const tagClose = '</answer>';
100
- const idxAnswer = content.indexOf(tagOpen);
101
- if (idxAnswer >= 0) {
102
- const thinking = content.slice(0, idxAnswer).replace(/<answer>/g, '').replace(/<\/answer>/g, '').trim();
103
- const action = content.slice(idxAnswer + tagOpen.length).replace(tagClose, '').trim();
104
- return { thinking, action };
105
- }
106
- return { thinking: '', action: content };
107
- }
108
- async streamRequest(messages, onThinkingChunk) {
109
- const llmResult = await this.llmCaller.callWithMessages({
110
- messages: (0, message_builder_1.toModelMessages)(messages),
111
- modelConfig: this.modelConfig,
112
- });
113
- if (llmResult.tokenUsage && this.reportGenerator) {
114
- this.reportGenerator.addTokenUsage(llmResult.tokenUsage, 'Executor(GLM)', this._stepCount);
115
- }
116
- const rawContent = llmResult.text;
117
- const { thinking, action } = this.parseRawResponse(rawContent);
118
- if (onThinkingChunk && thinking) {
119
- onThinkingChunk(thinking);
120
- }
121
- return { thinking, action, rawContent };
122
- }
123
- async executeStep(userPrompt, isFirst = false) {
124
- this._stepCount += 1;
125
- if (this.reportGenerator) {
126
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.GLM_STEP_START, `Step ${this._stepCount} started`, { stepNumber: this._stepCount }));
127
- }
128
- const screenshot = await this.device.getScreenshot(undefined, true);
129
- const screenshotPath = screenshot.screenshotPath ?? '';
130
- this._screenshot.push(screenshotPath);
131
- const currentApp = await this.device.getCurrentApp();
132
- if (isFirst) {
133
- let systemPrompt = this.agentConfig.systemPrompt;
134
- if (!systemPrompt) {
135
- systemPrompt = getSystemPrompt(this.agentConfig.lang, this.agentConfig.mode);
136
- }
137
- this._context.push(message_builder_1.MessageBuilder.createSystemMessage(systemPrompt));
138
- const screenInfo = message_builder_1.MessageBuilder.buildScreenInfo(currentApp);
139
- const textContent = `${userPrompt ?? ''}\n\n${screenInfo}`;
140
- this._context.push(message_builder_1.MessageBuilder.createUserMessage(textContent, screenshot.base64Data));
141
- }
142
- else {
143
- const screenInfo = message_builder_1.MessageBuilder.buildScreenInfo(currentApp);
144
- let textContent;
145
- if (userPrompt) {
146
- textContent = `${userPrompt}\n\n** Screen Info **\n\n${screenInfo}`;
147
- }
148
- else {
149
- textContent = `** Screen Info **\n\n${screenInfo}`;
150
- }
151
- this._context.push(message_builder_1.MessageBuilder.createUserMessage(textContent, screenshot.base64Data));
152
- }
153
- let thinking = '';
154
- let actionStr = '';
155
- let rawContent = '';
156
- try {
157
- const msgs = (0, i18n_1.getMessages)(this.agentConfig.lang);
158
- if (this.agentConfig.verbose) {
159
- logger_1.logger.info('Thinking:');
160
- }
161
- let callback = this.thinkingCallback ?? undefined;
162
- if (!callback && this.agentConfig.streamLog) {
163
- callback = (chunk) => process.stdout.write(chunk);
164
- }
165
- const res = await this.streamRequest(this._context, callback ?? null);
166
- thinking = res.thinking;
167
- actionStr = res.action;
168
- rawContent = res.rawContent;
169
- logger_1.logger.info(`Thinking: ${thinking}`);
170
- if (this.agentConfig.streamLog) {
171
- process.stdout.write('\n');
172
- }
173
- }
174
- catch (e) {
175
- logger_1.logger.error(`Model error: ${e instanceof Error ? e.message : String(e)}`);
176
- return this.makeStepResult(false, true, null, '', `Model error: ${e instanceof Error ? e.message : String(e)}`);
177
- }
178
- let action;
179
- try {
180
- action = this.parser.parse(actionStr, screenshot.width, screenshot.height);
181
- }
182
- catch (e) {
183
- if (this.agentConfig.verbose) {
184
- logger_1.logger.warn(`Failed to parse action: ${e instanceof Error ? e.message : String(e)}, treating as finish`);
185
- }
186
- action = { _metadata: 'finish', message: actionStr };
187
- }
188
- if (this.reportGenerator) {
189
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.GLM_THINKING, thinking, { stepNumber: this._stepCount }));
190
- }
191
- if (this.agentConfig.verbose) {
192
- logger_1.logger.info(`Action: ${JSON.stringify(action)}`);
193
- }
194
- if (this.reportGenerator) {
195
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.GLM_ACTION, `Action: ${JSON.stringify(action)}`, {
196
- data: { action, screen_width: screenshot.width, screen_height: screenshot.height },
197
- screenshotPath,
198
- stepNumber: this._stepCount,
199
- }));
200
- }
201
- const lastIndex = this._context.length - 1;
202
- if (lastIndex >= 0) {
203
- this._context[lastIndex] = message_builder_1.MessageBuilder.removeImagesFromMessage(this._context[lastIndex]);
204
- }
205
- let result;
206
- try {
207
- result = await this.actionHandler.execute(action);
208
- }
209
- catch (e) {
210
- result = { success: false, shouldFinish: true, message: e instanceof Error ? e.message : String(e) };
211
- }
212
- if (this.reportGenerator) {
213
- const postScreenshot = await this.device.getScreenshot(undefined, true);
214
- this.reportGenerator.addEvent(mkEvent(types_1.EventType.GLM_STEP_END, `Step ${this._stepCount} completed`, {
215
- data: { result: result.message, success: result.success },
216
- screenshotPath: postScreenshot.screenshotPath,
217
- stepNumber: this._stepCount,
218
- }));
219
- }
220
- this._context.push(message_builder_1.MessageBuilder.createAssistantMessage(`<answer>${thinking}</answer><answer>${actionStr}</answer>`));
221
- const finished = action._metadata === 'finish' || result.shouldFinish;
222
- if (finished && this.agentConfig.verbose) {
223
- const msgs = (0, i18n_1.getMessages)(this.agentConfig.lang);
224
- logger_1.logger.info(`${msgs.taskCompleted}: ${result.message ?? action.message ?? msgs.done}`);
225
- }
226
- return this.makeStepResult(result.success, finished, action, thinking, result.message ?? action.message);
227
- }
228
- get context() {
229
- return this._context.map((m) => m);
230
- }
231
- get stepCount() {
232
- return this._stepCount;
233
- }
234
- get screenshot() {
235
- return [...this._screenshot];
236
- }
237
- get isRunning() {
238
- return this._isRunning;
239
- }
240
- }
241
- exports.GLMAgent = GLMAgent;
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getMessages = getMessages;
4
- exports.getMessage = getMessage;
5
- const MESSAGES_EN = {
6
- thinking: 'Thinking',
7
- action: 'Action',
8
- taskCompleted: 'Task Completed',
9
- done: 'Done',
10
- startingTask: 'Starting task',
11
- finalResult: 'Final Result',
12
- taskResult: 'Task Result',
13
- confirmationRequired: 'Confirmation Required',
14
- continuePrompt: 'Continue? (y/n)',
15
- manualOperationRequired: 'Manual Operation Required',
16
- manualOperationHint: 'Please complete the operation manually...',
17
- pressEnterWhenDone: 'Press Enter when done',
18
- connectionFailed: 'Connection Failed',
19
- connectionSuccessful: 'Connection Successful',
20
- step: 'Step',
21
- task: 'Task',
22
- result: 'Result',
23
- performanceMetrics: 'Performance Metrics',
24
- timeToFirstToken: 'Time to First Token (TTFT)',
25
- timeToThinkingEnd: 'Time to Thinking End',
26
- totalInferenceTime: 'Total Inference Time',
27
- };
28
- function getMessages(lang = 'en') {
29
- return MESSAGES_EN;
30
- }
31
- function getMessage(key, lang = 'en') {
32
- const messages = getMessages(lang);
33
- return messages[key] ?? String(key);
34
- }