@autotest/agent 0.0.5 → 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.
- package/README.md +10 -0
- package/dist/api/agent_api.d.ts +2 -2
- package/dist/autotest-cli.js +1 -397
- package/dist/common/config/config.yaml +5 -0
- package/dist/common/config/manager.d.ts +7 -7
- package/dist/common/config/types.d.ts +33 -1
- package/dist/common/dfx/index.d.ts +1 -1
- package/dist/common/image_helper.d.ts +2 -2
- package/dist/common/llm_cache/cache_transport.d.ts +1 -1
- package/dist/common/llm_cache/prompt_cache.d.ts +2 -2
- package/dist/common/utils.d.ts +5 -5
- package/dist/core/agent/layered_agent/agent_registry.d.ts +3 -1
- package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.d.ts +1 -1
- package/dist/core/agent/layered_agent/execute_agent/prompts.d.ts +1 -1
- package/dist/core/agent/report_analyzer_agent/prompt.d.ts +1 -1
- package/dist/core/agent/report_analyzer_agent/tools.d.ts +1 -1
- package/dist/core/agent/rewrite_agent/agent.d.ts +5 -5
- package/dist/core/agent/rewrite_agent/guardrails.d.ts +1 -1
- package/dist/core/agent/rewrite_agent/mapping.d.ts +1 -1
- package/dist/core/agent/rewrite_agent/parse.d.ts +1 -1
- package/dist/core/agent/rewrite_agent/types.d.ts +1 -1
- package/dist/core/agent/single_agent/agent.d.ts +2 -2
- package/dist/core/agent/single_agent/hook_manager.d.ts +1 -2
- package/dist/core/agent/single_agent/image_utils.d.ts +1 -2
- package/dist/core/agent/single_agent/scroll_search_agent.d.ts +5 -5
- package/dist/core/agent/single_agent/subagent_manager.d.ts +1 -2
- package/dist/core/agent/single_agent/tool_recorder_hook.d.ts +3 -3
- package/dist/core/device/device_protocol.d.ts +1 -1
- package/dist/core/device/hdc/device.d.ts +1 -1
- package/dist/core/device/index.d.ts +2 -2
- package/dist/core/knowledge/knowledge_manager.d.ts +1 -1
- package/dist/core/knowledge/vectordb.d.ts +1 -1
- package/dist/core/mcp/harmony_hdc_adapter.d.ts +1 -0
- package/dist/core/mcp/mcp_tools.d.ts +11 -2
- package/dist/core/mcp/verify_tool.d.ts +12 -0
- package/dist/core/memory/_utils.d.ts +1 -1
- package/dist/core/memory/index.d.ts +1 -1
- package/dist/core/memory/memory_manager.d.ts +1 -1
- package/dist/core/memory/replan_manager.d.ts +1 -1
- package/dist/core/memory/tool_player.d.ts +5 -5
- package/dist/core/memory/tool_player_popup.d.ts +1 -1
- package/dist/core/memory/tool_player_replan.d.ts +1 -1
- package/dist/core/memory/tool_player_xpath.d.ts +3 -3
- package/dist/core/prompt/prompt_loader.d.ts +1 -1
- package/dist/core/prompt/templates/single/single_v2.0.md +15 -0
- package/dist/core/skill/skill_manager.d.ts +2 -2
- package/dist/data_types/device.d.ts +1 -1
- package/dist/data_types/index.d.ts +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +1 -164
- package/dist/loop/cli.d.ts +4 -4
- package/dist/loop/orchestrator.d.ts +6 -6
- package/dist/loop/result_writer.d.ts +1 -1
- package/dist/loop/types.d.ts +1 -1
- package/dist/tools/batch_runner.js +1 -745
- package/dist/tools/case_runner/report.d.ts +1 -1
- package/dist/tools/case_runner/runner.d.ts +3 -3
- package/dist/tools/case_runner/runner.js +1 -410
- package/dist/tools/config/config_tool.d.ts +6 -6
- package/dist/tools/config/config_tool.js +1 -339
- package/dist/tools/prompt_compare/compare_runner.d.ts +2 -2
- package/dist/tools/prompt_compare/compare_runner.js +1 -360
- package/package.json +2 -2
- package/dist/api/agent_api.js +0 -550
- package/dist/api/autotest_agent.js +0 -205
- package/dist/api/types.js +0 -11
- package/dist/common/case_manager.js +0 -91
- package/dist/common/collect_case.js +0 -128
- package/dist/common/common_errors.js +0 -66
- package/dist/common/config/config_validator.js +0 -28
- package/dist/common/config/manager.js +0 -257
- package/dist/common/config/output.js +0 -59
- package/dist/common/config/types.js +0 -184
- package/dist/common/dfx/client_factory.js +0 -62
- package/dist/common/dfx/context.js +0 -23
- package/dist/common/dfx/index.js +0 -15
- package/dist/common/dfx/recorder.js +0 -191
- package/dist/common/dfx/recording_fetch.js +0 -228
- package/dist/common/dfx/source.js +0 -13
- package/dist/common/image_cacher.js +0 -36
- package/dist/common/image_helper.js +0 -128
- package/dist/common/image_similarity.js +0 -171
- package/dist/common/llm_cache/cache_transport.js +0 -102
- package/dist/common/llm_cache/prompt_cache.js +0 -113
- package/dist/common/logger.js +0 -158
- package/dist/common/model/custom_model.js +0 -525
- package/dist/common/model/index.js +0 -5
- package/dist/common/path_utils.js +0 -88
- package/dist/common/result_parser.js +0 -49
- package/dist/common/usage/token_usage.js +0 -117
- package/dist/common/utils.js +0 -125
- package/dist/core/agent/layered_agent/ability_helper.js +0 -125
- package/dist/core/agent/layered_agent/agent.js +0 -37
- package/dist/core/agent/layered_agent/agent_registry.js +0 -75
- package/dist/core/agent/layered_agent/decision.js +0 -516
- package/dist/core/agent/layered_agent/execute_agent/action_handler.js +0 -155
- package/dist/core/agent/layered_agent/execute_agent/agent_factory.js +0 -41
- package/dist/core/agent/layered_agent/execute_agent/base_agent.js +0 -112
- package/dist/core/agent/layered_agent/execute_agent/general_agent.js +0 -207
- package/dist/core/agent/layered_agent/execute_agent/glm_agent.js +0 -241
- package/dist/core/agent/layered_agent/execute_agent/i18n.js +0 -34
- package/dist/core/agent/layered_agent/execute_agent/index.js +0 -67
- package/dist/core/agent/layered_agent/execute_agent/mai_ui_agent.js +0 -316
- package/dist/core/agent/layered_agent/execute_agent/mcp_prompts.js +0 -154
- package/dist/core/agent/layered_agent/execute_agent/parser/general_parser.js +0 -243
- package/dist/core/agent/layered_agent/execute_agent/parser/glm_parser.js +0 -139
- package/dist/core/agent/layered_agent/execute_agent/parser/index.js +0 -9
- package/dist/core/agent/layered_agent/execute_agent/parser/mai_ui_parser.js +0 -94
- package/dist/core/agent/layered_agent/execute_agent/prompts.js +0 -109
- package/dist/core/agent/layered_agent/execute_agent/simple_reporter.js +0 -33
- package/dist/core/agent/layered_agent/execute_agent/utils.js +0 -52
- package/dist/core/agent/report_analyzer_agent/agent.js +0 -565
- package/dist/core/agent/report_analyzer_agent/config.js +0 -22
- package/dist/core/agent/report_analyzer_agent/data_loader.js +0 -255
- package/dist/core/agent/report_analyzer_agent/guardrails.js +0 -99
- package/dist/core/agent/report_analyzer_agent/hooks.js +0 -31
- package/dist/core/agent/report_analyzer_agent/index.js +0 -52
- package/dist/core/agent/report_analyzer_agent/key_steps_builder.js +0 -42
- package/dist/core/agent/report_analyzer_agent/mapping.js +0 -133
- package/dist/core/agent/report_analyzer_agent/parse.js +0 -375
- package/dist/core/agent/report_analyzer_agent/prompt.js +0 -300
- package/dist/core/agent/report_analyzer_agent/report_writer.js +0 -558
- package/dist/core/agent/report_analyzer_agent/tools.js +0 -150
- package/dist/core/agent/report_analyzer_agent/types.js +0 -274
- package/dist/core/agent/rewrite_agent/agent.js +0 -209
- package/dist/core/agent/rewrite_agent/guardrails.js +0 -95
- package/dist/core/agent/rewrite_agent/mapping.js +0 -56
- package/dist/core/agent/rewrite_agent/parse.js +0 -121
- package/dist/core/agent/rewrite_agent/types.js +0 -37
- package/dist/core/agent/single_agent/agent.js +0 -798
- package/dist/core/agent/single_agent/hook_manager.js +0 -60
- package/dist/core/agent/single_agent/hooks.js +0 -288
- package/dist/core/agent/single_agent/image_utils.js +0 -159
- package/dist/core/agent/single_agent/scroll_search_agent.js +0 -376
- package/dist/core/agent/single_agent/subagent_manager.js +0 -73
- package/dist/core/agent/single_agent/tool_recorder_hook.js +0 -42
- package/dist/core/agent/types.js +0 -2
- package/dist/core/agent/utils/message_builder.js +0 -138
- package/dist/core/device/device_protocol.js +0 -2
- package/dist/core/device/hdc/apps.js +0 -437
- package/dist/core/device/hdc/device.js +0 -219
- package/dist/core/device/hdc/index.js +0 -31
- package/dist/core/device/hdc/input.js +0 -74
- package/dist/core/device/hdc/screenshot.js +0 -171
- package/dist/core/device/index.js +0 -70
- package/dist/core/device/types.js +0 -2
- package/dist/core/knowledge/knowledge_manager.js +0 -70
- package/dist/core/knowledge/vectordb.js +0 -283
- package/dist/core/mcp/adapter_factory.js +0 -99
- package/dist/core/mcp/android_adapter.js +0 -286
- package/dist/core/mcp/base_adapter.js +0 -86
- package/dist/core/mcp/harmony_hdc_adapter.js +0 -782
- package/dist/core/mcp/ios_adapter.js +0 -286
- package/dist/core/mcp/local_tools.js +0 -41
- package/dist/core/mcp/mcp_tools.js +0 -410
- package/dist/core/mcp/types.js +0 -6
- package/dist/core/memory/_utils.js +0 -140
- package/dist/core/memory/compressed_session.js +0 -182
- package/dist/core/memory/context_compressor.js +0 -176
- package/dist/core/memory/index.js +0 -22
- package/dist/core/memory/memory_manager.js +0 -28
- package/dist/core/memory/reflector.js +0 -95
- package/dist/core/memory/replan_manager.js +0 -12
- package/dist/core/memory/session_factory.js +0 -29
- package/dist/core/memory/tool_player.js +0 -225
- package/dist/core/memory/tool_player_popup.js +0 -276
- package/dist/core/memory/tool_player_replan.js +0 -226
- package/dist/core/memory/tool_player_xpath.js +0 -139
- package/dist/core/memory/tool_recorder.js +0 -126
- package/dist/core/preprocessor/task_splitter.js +0 -112
- package/dist/core/prompt/prompt_loader.js +0 -315
- package/dist/core/skill/skill_manager.js +0 -302
- package/dist/data_types/action.js +0 -2
- package/dist/data_types/agent.js +0 -2
- package/dist/data_types/case.js +0 -57
- package/dist/data_types/device.js +0 -2
- package/dist/data_types/index.js +0 -11
- package/dist/data_types/report.js +0 -6
- package/dist/data_types/screen.js +0 -23
- package/dist/data_types/task.js +0 -2
- package/dist/loop/cli.js +0 -127
- package/dist/loop/orchestrator.js +0 -314
- package/dist/loop/result_writer.js +0 -260
- package/dist/loop/types.js +0 -82
- package/dist/mcp-server/server.js +0 -341
- package/dist/mcp-server/types.js +0 -224
- package/dist/reporter/batch_summary.js +0 -197
- package/dist/reporter/generator.js +0 -286
- package/dist/reporter/html_template/index.js +0 -524
- package/dist/reporter/json_report.js +0 -6
- package/dist/reporter/types.js +0 -45
- package/dist/tools/case_runner/report.js +0 -264
|
@@ -1,376 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* ScrollSearchAgent — 滚动查找子代理(对齐 python custom_scroll_search)。
|
|
4
|
-
*
|
|
5
|
-
* 在列表、导航栏、时间/日期/数字选择器等滚动场景中,
|
|
6
|
-
* 自动滑动查找目标元素使其进入可见区域。
|
|
7
|
-
*
|
|
8
|
-
* 核心流程:
|
|
9
|
-
* Phase 1: 截图 → LLM 分析滑动区域/方向/目标
|
|
10
|
-
* 主循环: 截图 → LLM 判断(目标找到?内容变化?弹窗?) → 计算滑动距离 → 执行滑动 → 等待稳定 → 边界/区域检查
|
|
11
|
-
* 退出: 目标找到 或 达到最大步数
|
|
12
|
-
*/
|
|
13
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
-
exports.ScrollSearchAgent = exports.DEFAULT_SCROLL_CONFIG = void 0;
|
|
15
|
-
const logger_1 = require("../../../common/logger");
|
|
16
|
-
const custom_model_1 = require("../../../common/model/custom_model");
|
|
17
|
-
const image_helper_1 = require("../../../common/image_helper");
|
|
18
|
-
exports.DEFAULT_SCROLL_CONFIG = {
|
|
19
|
-
maxSteps: 10,
|
|
20
|
-
screenshotMaxPixels: 1500,
|
|
21
|
-
farDistanceRatio: 0.7,
|
|
22
|
-
nearDistanceRatio: 0.4,
|
|
23
|
-
closeDistanceRatio: 0.15,
|
|
24
|
-
swipeDelayMs: 1000,
|
|
25
|
-
defaultDistanceRatio: 0.5, // Aligned with python: 0.6→0.5
|
|
26
|
-
minDistanceRatio: 0.08,
|
|
27
|
-
swipeWaitMs: 800,
|
|
28
|
-
};
|
|
29
|
-
function opposite(dir) {
|
|
30
|
-
return { up: 'down', down: 'up', left: 'right', right: 'left' }[dir];
|
|
31
|
-
}
|
|
32
|
-
function isVertical(dir) {
|
|
33
|
-
return dir === 'up' || dir === 'down';
|
|
34
|
-
}
|
|
35
|
-
// ---- Prompts (copied from python tools/prompts.py) ----
|
|
36
|
-
const SYSTEM_PROMPT = `你是一个专业的移动端UI分析助手,专门辅助滑动查找任务。
|
|
37
|
-
你需要分析截图并返回严格的JSON格式结果,不要输出任何其他内容。`;
|
|
38
|
-
function initAnalysisPrompt(taskDesc, userDir) {
|
|
39
|
-
return `## 任务
|
|
40
|
-
分析当前截图,验证用户描述的滑动区域是否存在,并确定可滑动区域的范围和初始滑动方向。
|
|
41
|
-
|
|
42
|
-
## 查找目标
|
|
43
|
-
${taskDesc}
|
|
44
|
-
|
|
45
|
-
## 用户指定的滑动方向
|
|
46
|
-
${userDir || '(未指定,请自动判断)'}
|
|
47
|
-
|
|
48
|
-
## 要求
|
|
49
|
-
请分析截图,确定:
|
|
50
|
-
1. region_valid: 用户描述的物理区域是否在当前页面上可见(true/false)
|
|
51
|
-
2. failure_reason: 如果 region_valid 为 false,说明失败原因
|
|
52
|
-
3. bounding_box: 可滑动内容区域的边界框 [left, top, right, bottom](0-1000整数)
|
|
53
|
-
4. direction: 初始滑动方向(up/down/left/right)
|
|
54
|
-
5. user_specified_direction: 用户是否明确指定了方向(true/false)
|
|
55
|
-
6. is_numeric_adjustment: 是否是数字调节场景(true/false)
|
|
56
|
-
7. region_description: 滑动区域描述
|
|
57
|
-
8. target_description: 查找目标描述
|
|
58
|
-
9. target_number: 如果目标能解析为数字则返回数字,否则null
|
|
59
|
-
|
|
60
|
-
## 输出格式
|
|
61
|
-
只返回JSON:
|
|
62
|
-
{"region_valid": true/false, "failure_reason": "", "bounding_box": [l,t,r,b], "direction": "up|down|left|right", "user_specified_direction": true/false, "is_numeric_adjustment": true/false, "region_description": "", "target_description": "", "target_number": 数字或null}`;
|
|
63
|
-
}
|
|
64
|
-
function judgmentPrompt(taskDesc, bbox, dir) {
|
|
65
|
-
return `## 任务
|
|
66
|
-
对比滑动前后的两张截图,仅关注滑动区域内的变化,判断滑动效果和目标查找状态。
|
|
67
|
-
|
|
68
|
-
## 查找目标
|
|
69
|
-
${taskDesc}
|
|
70
|
-
|
|
71
|
-
## 滑动区域
|
|
72
|
-
bounding_box: [${bbox.join(', ')}](0-1000整数坐标)
|
|
73
|
-
你只需要关注这个矩形区域内的内容,完全忽略区域外的一切。
|
|
74
|
-
|
|
75
|
-
## 滑动方向
|
|
76
|
-
${dir}(手指移动方向)
|
|
77
|
-
|
|
78
|
-
## 截图说明
|
|
79
|
-
- 第一张图:滑动前的屏幕
|
|
80
|
-
- 第二张图:滑动后的屏幕
|
|
81
|
-
|
|
82
|
-
## 判断要求
|
|
83
|
-
1. content_changed: 滑动后滑动区域内内容是否变化(true/false)
|
|
84
|
-
2. target_found: 是否在第二张截图的滑动区域内看到目标(true/false)
|
|
85
|
-
3. target_coords: 如果找到目标,返回目标坐标 [x, y](0-1000整数);未找到返回null
|
|
86
|
-
4. current_number: 数字调节场景返回当前选中数值;非数字场景返回null
|
|
87
|
-
5. blocking_popup: 是否有阻挡滑动的弹窗(true/false)
|
|
88
|
-
6. blocking_popup_close: 如果有弹窗,返回关闭按钮坐标 [x, y];无返回null
|
|
89
|
-
|
|
90
|
-
## 输出格式
|
|
91
|
-
只返回JSON:
|
|
92
|
-
{"content_changed": true/false, "target_found": true/false, "target_coords": [x,y]或null, "current_number": 数字或null, "blocking_popup": true/false, "blocking_popup_close": [x,y]或null}`;
|
|
93
|
-
}
|
|
94
|
-
// ---- ScrollSearchAgent ----
|
|
95
|
-
class ScrollSearchAgent {
|
|
96
|
-
name = 'scroll_search';
|
|
97
|
-
description = '滑动查找目标使其进入可见区域,用于列表、导航栏、时间选择器等滚动场景。';
|
|
98
|
-
_llmCaller;
|
|
99
|
-
_adapter;
|
|
100
|
-
_config;
|
|
101
|
-
_reportGenerator;
|
|
102
|
-
_modelConfig;
|
|
103
|
-
_noChangeCount = 0;
|
|
104
|
-
constructor(adapter, modelConfig, config, reportGenerator) {
|
|
105
|
-
this._adapter = adapter;
|
|
106
|
-
this._modelConfig = modelConfig;
|
|
107
|
-
this._config = { ...exports.DEFAULT_SCROLL_CONFIG, ...config };
|
|
108
|
-
this._reportGenerator = reportGenerator ?? null;
|
|
109
|
-
this._llmCaller = new custom_model_1.LLMCaller();
|
|
110
|
-
}
|
|
111
|
-
async run(taskDescription, userDirection = '') {
|
|
112
|
-
logger_1.logger.info(`[ScrollSearch] Starting: task="${taskDescription.slice(0, 80)}" dir="${userDirection || '(auto)'}"`);
|
|
113
|
-
// Phase 1: Init — screenshot + LLM analysis
|
|
114
|
-
const initScreenshot = await this._takeScreenshot();
|
|
115
|
-
if (!initScreenshot) {
|
|
116
|
-
return { success: false, targetCoords: null, totalSteps: 0, message: '初始截图失败', summary: '截图失败' };
|
|
117
|
-
}
|
|
118
|
-
const initAnalysis = await this._vlmInitAnalysis(initScreenshot, taskDescription, userDirection);
|
|
119
|
-
if (!initAnalysis) {
|
|
120
|
-
return { success: false, targetCoords: null, totalSteps: 0, message: 'VLM 初始分析失败', summary: 'LLM分析失败' };
|
|
121
|
-
}
|
|
122
|
-
if (!initAnalysis.regionValid) {
|
|
123
|
-
const reason = initAnalysis.failureReason || '区域不存在';
|
|
124
|
-
return { success: false, targetCoords: null, totalSteps: 0, message: `区域验证失败: ${reason}`, summary: `区域不存在: ${reason}` };
|
|
125
|
-
}
|
|
126
|
-
logger_1.logger.info(`[ScrollSearch] Region: [${initAnalysis.boundingBox.join(', ')}] dir=${initAnalysis.direction} target="${initAnalysis.targetDescription}"`);
|
|
127
|
-
// Check if target already visible in init screenshot
|
|
128
|
-
const initJudgment = await this._vlmJudgment(initScreenshot, initScreenshot, taskDescription, initAnalysis.boundingBox, initAnalysis.direction);
|
|
129
|
-
if (initJudgment?.targetFound && initJudgment.targetCoords) {
|
|
130
|
-
logger_1.logger.info(`[ScrollSearch] Target found in initial screenshot at [${initJudgment.targetCoords.join(', ')}]`);
|
|
131
|
-
return this._success(initJudgment.targetCoords, 0, '目标在初始截图中已可见');
|
|
132
|
-
}
|
|
133
|
-
// Main loop
|
|
134
|
-
let prevScreenshot = initScreenshot;
|
|
135
|
-
let direction = initAnalysis.direction;
|
|
136
|
-
let consecutiveNoChange = 0;
|
|
137
|
-
for (let step = 1; step <= this._config.maxSteps; step++) {
|
|
138
|
-
logger_1.logger.info(`[ScrollSearch] Step ${step}/${this._config.maxSteps}`);
|
|
139
|
-
// 1. Execute swipe
|
|
140
|
-
const swipeDistance = this._calculateSwipeDistance(initAnalysis, direction, step);
|
|
141
|
-
await this._executeSwipe(direction, initAnalysis.boundingBox, swipeDistance);
|
|
142
|
-
await this._sleep(this._config.swipeWaitMs);
|
|
143
|
-
// 2. Take screenshot after swipe
|
|
144
|
-
const afterScreenshot = await this._takeScreenshot();
|
|
145
|
-
if (!afterScreenshot) {
|
|
146
|
-
logger_1.logger.warn(`[ScrollSearch] Step ${step}: 截图失败,跳过`);
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
// 3. VLM judgment
|
|
150
|
-
const judgment = await this._vlmJudgment(prevScreenshot, afterScreenshot, taskDescription, initAnalysis.boundingBox, direction);
|
|
151
|
-
if (!judgment) {
|
|
152
|
-
logger_1.logger.warn(`[ScrollSearch] Step ${step}: VLM 判断失败`);
|
|
153
|
-
prevScreenshot = afterScreenshot;
|
|
154
|
-
continue;
|
|
155
|
-
}
|
|
156
|
-
// 4. Handle popup
|
|
157
|
-
if (judgment.blockingPopup && judgment.blockingPopupClose) {
|
|
158
|
-
const [px, py] = this._scaleFrom1000(judgment.blockingPopupClose);
|
|
159
|
-
await this._adapter.callTool('click', { pos: [px, py] });
|
|
160
|
-
logger_1.logger.info(`[ScrollSearch] Step ${step}: 关闭弹窗 at [${px}, ${py}]`);
|
|
161
|
-
await this._sleep(500);
|
|
162
|
-
prevScreenshot = afterScreenshot;
|
|
163
|
-
continue;
|
|
164
|
-
}
|
|
165
|
-
// 5. Target found?
|
|
166
|
-
if (judgment.targetFound && judgment.targetCoords) {
|
|
167
|
-
const [tx, ty] = this._scaleFrom1000(judgment.targetCoords);
|
|
168
|
-
logger_1.logger.info(`[ScrollSearch] Target found at step ${step}! coords=[${tx}, ${ty}]`);
|
|
169
|
-
return this._success([tx, ty], step, `在第 ${step} 步找到目标`);
|
|
170
|
-
}
|
|
171
|
-
// 6. Content changed?
|
|
172
|
-
if (!judgment.contentChanged) {
|
|
173
|
-
consecutiveNoChange++;
|
|
174
|
-
logger_1.logger.info(`[ScrollSearch] Step ${step}: 内容未变化 (连续 ${consecutiveNoChange} 次)`);
|
|
175
|
-
if (consecutiveNoChange >= 1) {
|
|
176
|
-
// Switch direction
|
|
177
|
-
const newDir = opposite(direction);
|
|
178
|
-
logger_1.logger.info(`[ScrollSearch] Step ${step}: 切换方向 ${direction} → ${newDir}`);
|
|
179
|
-
direction = newDir;
|
|
180
|
-
consecutiveNoChange = 0;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
else {
|
|
184
|
-
consecutiveNoChange = 0;
|
|
185
|
-
}
|
|
186
|
-
// 7. Numeric adjustment (picker)
|
|
187
|
-
if (initAnalysis.isNumericAdjustment && judgment.currentNumber !== null && initAnalysis.targetNumber !== null) {
|
|
188
|
-
const adjusted = this._adjustNumericSwipe(judgment.currentNumber, initAnalysis.targetNumber, direction, initAnalysis.boundingBox);
|
|
189
|
-
if (adjusted) {
|
|
190
|
-
direction = adjusted.direction;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
prevScreenshot = afterScreenshot;
|
|
194
|
-
}
|
|
195
|
-
// Max steps reached
|
|
196
|
-
return {
|
|
197
|
-
success: false,
|
|
198
|
-
targetCoords: null,
|
|
199
|
-
totalSteps: this._config.maxSteps,
|
|
200
|
-
message: `达到最大步数 ${this._config.maxSteps},未找到目标`,
|
|
201
|
-
summary: `未找到目标(${this._config.maxSteps}步)`,
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
// ---- VLM interactions ----
|
|
205
|
-
async _vlmInitAnalysis(screenshot, taskDesc, userDir) {
|
|
206
|
-
try {
|
|
207
|
-
const result = await this._llmCaller.call({
|
|
208
|
-
systemPrompt: SYSTEM_PROMPT,
|
|
209
|
-
userPrompt: initAnalysisPrompt(taskDesc, userDir),
|
|
210
|
-
images: [{ base64Data: screenshot, mimeType: 'image/jpeg' }],
|
|
211
|
-
modelConfig: this._modelConfig,
|
|
212
|
-
});
|
|
213
|
-
return this._parseInitAnalysis(result.text);
|
|
214
|
-
}
|
|
215
|
-
catch (e) {
|
|
216
|
-
logger_1.logger.error(`[ScrollSearch] VLM init analysis failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
217
|
-
return null;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
async _vlmJudgment(before, after, taskDesc, bbox, dir) {
|
|
221
|
-
try {
|
|
222
|
-
const result = await this._llmCaller.call({
|
|
223
|
-
systemPrompt: SYSTEM_PROMPT,
|
|
224
|
-
userPrompt: judgmentPrompt(taskDesc, bbox, dir),
|
|
225
|
-
images: [
|
|
226
|
-
{ base64Data: before, mimeType: 'image/jpeg' },
|
|
227
|
-
{ base64Data: after, mimeType: 'image/jpeg' },
|
|
228
|
-
],
|
|
229
|
-
modelConfig: this._modelConfig,
|
|
230
|
-
});
|
|
231
|
-
return this._parseStepJudgment(result.text);
|
|
232
|
-
}
|
|
233
|
-
catch (e) {
|
|
234
|
-
logger_1.logger.error(`[ScrollSearch] VLM judgment failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
235
|
-
return null;
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
// ---- JSON parsing ----
|
|
239
|
-
_parseJson(text) {
|
|
240
|
-
// Strip markdown code fences if present
|
|
241
|
-
let s = text.trim();
|
|
242
|
-
s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
|
|
243
|
-
// Find first { and last }
|
|
244
|
-
const start = s.indexOf('{');
|
|
245
|
-
const end = s.lastIndexOf('}');
|
|
246
|
-
if (start < 0 || end < 0)
|
|
247
|
-
return null;
|
|
248
|
-
try {
|
|
249
|
-
return JSON.parse(s.slice(start, end + 1));
|
|
250
|
-
}
|
|
251
|
-
catch {
|
|
252
|
-
return null;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
_parseInitAnalysis(text) {
|
|
256
|
-
const j = this._parseJson(text);
|
|
257
|
-
if (!j)
|
|
258
|
-
return null;
|
|
259
|
-
const bbox = Array.isArray(j.bounding_box) ? j.bounding_box : [0, 0, 0, 0];
|
|
260
|
-
return {
|
|
261
|
-
regionValid: Boolean(j.region_valid),
|
|
262
|
-
failureReason: String(j.failure_reason ?? ''),
|
|
263
|
-
boundingBox: [bbox[0] ?? 0, bbox[1] ?? 0, bbox[2] ?? 0, bbox[3] ?? 0],
|
|
264
|
-
direction: (['up', 'down', 'left', 'right'].includes(String(j.direction)) ? String(j.direction) : 'up'),
|
|
265
|
-
userSpecifiedDirection: Boolean(j.user_specified_direction),
|
|
266
|
-
isNumericAdjustment: Boolean(j.is_numeric_adjustment),
|
|
267
|
-
regionDescription: String(j.region_description ?? ''),
|
|
268
|
-
targetDescription: String(j.target_description ?? ''),
|
|
269
|
-
targetNumber: typeof j.target_number === 'number' ? j.target_number : null,
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
_parseStepJudgment(text) {
|
|
273
|
-
const j = this._parseJson(text);
|
|
274
|
-
if (!j)
|
|
275
|
-
return null;
|
|
276
|
-
const tc = Array.isArray(j.target_coords) ? j.target_coords : null;
|
|
277
|
-
const pc = Array.isArray(j.blocking_popup_close) ? j.blocking_popup_close : null;
|
|
278
|
-
return {
|
|
279
|
-
contentChanged: Boolean(j.content_changed),
|
|
280
|
-
targetFound: Boolean(j.target_found),
|
|
281
|
-
targetCoords: tc ? [tc[0], tc[1]] : null,
|
|
282
|
-
currentNumber: typeof j.current_number === 'number' ? j.current_number : null,
|
|
283
|
-
blockingPopup: Boolean(j.blocking_popup),
|
|
284
|
-
blockingPopupClose: pc ? [pc[0], pc[1]] : null,
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
// ---- Swipe calculation (aligned with python swipe_calculator.py) ----
|
|
288
|
-
_calculateSwipeDistance(init, dir, _step) {
|
|
289
|
-
// Default distance based on config
|
|
290
|
-
let ratio = this._config.defaultDistanceRatio;
|
|
291
|
-
// For numeric adjustment, calculate based on current vs target
|
|
292
|
-
if (init.isNumericAdjustment && init.targetNumber !== null) {
|
|
293
|
-
// Use close distance for fine-tuning
|
|
294
|
-
ratio = this._config.closeDistanceRatio;
|
|
295
|
-
}
|
|
296
|
-
return Math.max(ratio, this._config.minDistanceRatio);
|
|
297
|
-
}
|
|
298
|
-
_adjustNumericSwipe(current, target, dir, _bbox) {
|
|
299
|
-
if (current === target)
|
|
300
|
-
return null;
|
|
301
|
-
// If current > target and scrolling up increases value → keep direction
|
|
302
|
-
// If current > target and scrolling up decreases value → flip direction
|
|
303
|
-
// For pickers: up usually increases, down decreases
|
|
304
|
-
const needIncrease = target > current;
|
|
305
|
-
const upIncreases = isVertical(dir) && dir === 'up';
|
|
306
|
-
if (needIncrease !== upIncreases) {
|
|
307
|
-
const newDir = opposite(dir);
|
|
308
|
-
logger_1.logger.info(`[ScrollSearch] Numeric: current=${current} target=${target}, flip ${dir}→${newDir}`);
|
|
309
|
-
return { direction: newDir };
|
|
310
|
-
}
|
|
311
|
-
return { direction: dir };
|
|
312
|
-
}
|
|
313
|
-
// ---- Swipe execution (aligned with python screen_executor.py) ----
|
|
314
|
-
async _executeSwipe(dir, bbox, distanceRatio) {
|
|
315
|
-
const [l, t, r, b] = bbox;
|
|
316
|
-
// Center of bounding box (0-1000 scale → 0-1 relative)
|
|
317
|
-
const cx = ((l + r) / 2) / 1000;
|
|
318
|
-
const cy = ((t + b) / 2) / 1000;
|
|
319
|
-
const regionHeight = (b - t) / 1000;
|
|
320
|
-
const regionWidth = (r - l) / 1000;
|
|
321
|
-
let sx = cx, sy = cy, ex = cx, ey = cy;
|
|
322
|
-
if (dir === 'up') {
|
|
323
|
-
// Finger moves up: start below center, end above
|
|
324
|
-
sy = cy + regionHeight * distanceRatio * 0.5;
|
|
325
|
-
ey = cy - regionHeight * distanceRatio * 0.5;
|
|
326
|
-
}
|
|
327
|
-
else if (dir === 'down') {
|
|
328
|
-
sy = cy - regionHeight * distanceRatio * 0.5;
|
|
329
|
-
ey = cy + regionHeight * distanceRatio * 0.5;
|
|
330
|
-
}
|
|
331
|
-
else if (dir === 'left') {
|
|
332
|
-
sx = cx + regionWidth * distanceRatio * 0.5;
|
|
333
|
-
ex = cx - regionWidth * distanceRatio * 0.5;
|
|
334
|
-
}
|
|
335
|
-
else {
|
|
336
|
-
sx = cx - regionWidth * distanceRatio * 0.5;
|
|
337
|
-
ex = cx + regionWidth * distanceRatio * 0.5;
|
|
338
|
-
}
|
|
339
|
-
// Clamp to 0-1
|
|
340
|
-
sx = Math.max(0, Math.min(1, sx));
|
|
341
|
-
sy = Math.max(0, Math.min(1, sy));
|
|
342
|
-
ex = Math.max(0, Math.min(1, ex));
|
|
343
|
-
ey = Math.max(0, Math.min(1, ey));
|
|
344
|
-
logger_1.logger.debug(`[ScrollSearch] Swipe ${dir}: [${sx.toFixed(3)},${sy.toFixed(3)}] → [${ex.toFixed(3)},${ey.toFixed(3)}]`);
|
|
345
|
-
await this._adapter.callTool('swipe', { start: [sx, sy], end: [ex, ey], direction: dir, log: `scroll_search ${dir}` });
|
|
346
|
-
}
|
|
347
|
-
// ---- Helpers ----
|
|
348
|
-
async _takeScreenshot() {
|
|
349
|
-
try {
|
|
350
|
-
const shot = await this._adapter.getScreenshot();
|
|
351
|
-
if (!shot.base64Data)
|
|
352
|
-
return null;
|
|
353
|
-
// Compress before returning (reduces LLM input tokens → faster response)
|
|
354
|
-
return await (0, image_helper_1.compressBase64Image)(shot.base64Data, this._config.screenshotMaxPixels, 70);
|
|
355
|
-
}
|
|
356
|
-
catch {
|
|
357
|
-
return null;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
_scaleFrom1000(coords) {
|
|
361
|
-
return [coords[0] / 1000, coords[1] / 1000];
|
|
362
|
-
}
|
|
363
|
-
_success(coords, steps, msg) {
|
|
364
|
-
return {
|
|
365
|
-
success: true,
|
|
366
|
-
targetCoords: coords,
|
|
367
|
-
totalSteps: steps,
|
|
368
|
-
message: msg,
|
|
369
|
-
summary: `找到目标: ${msg}`,
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
_sleep(ms) {
|
|
373
|
-
return new Promise(r => setTimeout(r, ms));
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
exports.ScrollSearchAgent = ScrollSearchAgent;
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Subagent infrastructure (aligned with python hybrid_agent/agent/base.py +
|
|
4
|
-
* hybrid_hooks.py register_subagent_hooks).
|
|
5
|
-
*
|
|
6
|
-
* SubagentManager allows the parent agent to delegate work to child agents
|
|
7
|
-
* via a `run_subagent` tool call. Child steps are offset from the parent's
|
|
8
|
-
* step counter for correct numbering in reports.
|
|
9
|
-
*
|
|
10
|
-
* NOTE: Full event buffering (start_buffering/drain_buffer/attach_sub_events)
|
|
11
|
-
* is deferred — this version provides the registration + invocation + step
|
|
12
|
-
* offset infrastructure.
|
|
13
|
-
*/
|
|
14
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.SubagentManager = void 0;
|
|
16
|
-
exports.getSubagentManager = getSubagentManager;
|
|
17
|
-
const logger_1 = require("../../../common/logger");
|
|
18
|
-
class SubagentManager {
|
|
19
|
-
_subagents = new Map();
|
|
20
|
-
_parentStep = 0;
|
|
21
|
-
/** Register a sub-agent by name with a runner function. */
|
|
22
|
-
register(name, description, runner, defaultTaskDescription) {
|
|
23
|
-
this._subagents.set(name, { name, description, runner, defaultTaskDescription });
|
|
24
|
-
logger_1.logger.debug(`[SubagentManager] registered sub-agent '${name}'`);
|
|
25
|
-
}
|
|
26
|
-
/** Unregister a sub-agent. */
|
|
27
|
-
unregister(name) {
|
|
28
|
-
this._subagents.delete(name);
|
|
29
|
-
}
|
|
30
|
-
/** List registered sub-agent names + descriptions (for tool schema). */
|
|
31
|
-
listSubagents() {
|
|
32
|
-
return Array.from(this._subagents.values()).map((s) => ({ name: s.name, description: s.description }));
|
|
33
|
-
}
|
|
34
|
-
/** Set the parent's current step (for step offset calculation). */
|
|
35
|
-
setParentStep(step) {
|
|
36
|
-
this._parentStep = step;
|
|
37
|
-
}
|
|
38
|
-
/** Run a sub-agent by name. Step offset = parent step (child steps start from parent+1). */
|
|
39
|
-
async runSubagent(name, task, reportGenerator) {
|
|
40
|
-
const sub = this._subagents.get(name);
|
|
41
|
-
if (!sub) {
|
|
42
|
-
return { name, success: false, output: `Sub-agent '${name}' not found`, stepsUsed: 0 };
|
|
43
|
-
}
|
|
44
|
-
const stepOffset = this._parentStep;
|
|
45
|
-
logger_1.logger.info(`[SubagentManager] running sub-agent '${name}' (step offset=${stepOffset}): ${task.slice(0, 80)}`);
|
|
46
|
-
try {
|
|
47
|
-
const result = await sub.runner(task, { stepOffset, reportGenerator });
|
|
48
|
-
logger_1.logger.info(`[SubagentManager] sub-agent '${name}' completed: success=${result.success}, steps=${result.stepsUsed}`);
|
|
49
|
-
return result;
|
|
50
|
-
}
|
|
51
|
-
catch (e) {
|
|
52
|
-
const msg = e instanceof Error ? e.message : String(e);
|
|
53
|
-
logger_1.logger.error(`[SubagentManager] sub-agent '${name}' failed: ${msg}`);
|
|
54
|
-
return { name, success: false, output: msg, stepsUsed: 0 };
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
/** Build a tool description string for the LLM (lists available sub-agents). */
|
|
58
|
-
getToolDescription() {
|
|
59
|
-
const subs = this.listSubagents();
|
|
60
|
-
if (subs.length === 0)
|
|
61
|
-
return 'No sub-agents available.';
|
|
62
|
-
return subs.map((s) => `- ${s.name}: ${s.description}`).join('\n');
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
exports.SubagentManager = SubagentManager;
|
|
66
|
-
/** Singleton instance (aligned with python agent_registry pattern). */
|
|
67
|
-
let _instance = null;
|
|
68
|
-
function getSubagentManager() {
|
|
69
|
-
if (!_instance) {
|
|
70
|
-
_instance = new SubagentManager();
|
|
71
|
-
}
|
|
72
|
-
return _instance;
|
|
73
|
-
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* ToolRecorderHook — cross-cutting hook that auto-records every tool call via
|
|
4
|
-
* the global HookManager (aligned with python hybrid_agent/hooks/tool_recorder_hook.py).
|
|
5
|
-
*
|
|
6
|
-
* Register once at agent startup:
|
|
7
|
-
* const recorder = new ToolRecorder(taskId, storageDir);
|
|
8
|
-
* hookManager.register('tool_recorder', new ToolRecorderHook(recorder));
|
|
9
|
-
* Call finalize() at agent end to persist.
|
|
10
|
-
*/
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.ToolRecorderHook = void 0;
|
|
13
|
-
const logger_1 = require("../../../common/logger");
|
|
14
|
-
class ToolRecorderHook {
|
|
15
|
-
recorder;
|
|
16
|
-
_finalized = false;
|
|
17
|
-
constructor(recorder) {
|
|
18
|
-
this.recorder = recorder;
|
|
19
|
-
}
|
|
20
|
-
async onToolEnd(ctx) {
|
|
21
|
-
const toolName = ctx.toolName ?? '';
|
|
22
|
-
const toolArgs = ctx.toolArgs ?? {};
|
|
23
|
-
const result = ctx.result ?? '';
|
|
24
|
-
const step = ctx.step ?? 0;
|
|
25
|
-
const success = !/error|fail|exception/i.test(result);
|
|
26
|
-
this.recorder.record(toolName, toolArgs, result, success, step);
|
|
27
|
-
}
|
|
28
|
-
/** Persist the recorded session to disk. Call at agent end. */
|
|
29
|
-
finalize() {
|
|
30
|
-
if (this._finalized)
|
|
31
|
-
return null;
|
|
32
|
-
this._finalized = true;
|
|
33
|
-
try {
|
|
34
|
-
return this.recorder.save();
|
|
35
|
-
}
|
|
36
|
-
catch (e) {
|
|
37
|
-
logger_1.logger.error(`ToolRecorderHook: finalize failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
38
|
-
return null;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
exports.ToolRecorderHook = ToolRecorderHook;
|
package/dist/core/agent/types.js
DELETED
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MessageBuilder = void 0;
|
|
4
|
-
exports.toModelMessages = toModelMessages;
|
|
5
|
-
const logger_1 = require("../../../common/logger");
|
|
6
|
-
function toModelMessages(messages) {
|
|
7
|
-
return messages.map((m) => {
|
|
8
|
-
if (m.role === 'tool') {
|
|
9
|
-
const text = typeof m.content === 'string' ? m.content : JSON.stringify(m.content);
|
|
10
|
-
return { role: 'user', content: `Tool result (${m.name ?? 'tool'}): ${text}` };
|
|
11
|
-
}
|
|
12
|
-
if (typeof m.content === 'string') {
|
|
13
|
-
return { role: m.role, content: m.content };
|
|
14
|
-
}
|
|
15
|
-
const parts = m.content.map((c) => {
|
|
16
|
-
if (c.type === 'image_url') {
|
|
17
|
-
return { type: 'image', image: c.image_url.url };
|
|
18
|
-
}
|
|
19
|
-
return { type: 'text', text: c.text };
|
|
20
|
-
});
|
|
21
|
-
return { role: m.role, content: parts };
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
class MessageBuilder {
|
|
25
|
-
messages = [];
|
|
26
|
-
static createSystemMessage(content) {
|
|
27
|
-
return { role: 'system', content };
|
|
28
|
-
}
|
|
29
|
-
static createUserMessage(text, imageBase64, mimeType = 'image/jpeg') {
|
|
30
|
-
const content = [];
|
|
31
|
-
if (imageBase64) {
|
|
32
|
-
let url;
|
|
33
|
-
if (imageBase64.startsWith('data:')) {
|
|
34
|
-
url = imageBase64;
|
|
35
|
-
}
|
|
36
|
-
else {
|
|
37
|
-
url = `data:${mimeType};base64,${imageBase64}`;
|
|
38
|
-
}
|
|
39
|
-
content.push({ type: 'image_url', image_url: { url } });
|
|
40
|
-
}
|
|
41
|
-
content.push({ type: 'text', text });
|
|
42
|
-
return { role: 'user', content };
|
|
43
|
-
}
|
|
44
|
-
static createAssistantMessage(content) {
|
|
45
|
-
return { role: 'assistant', content };
|
|
46
|
-
}
|
|
47
|
-
static removeImagesFromMessage(message) {
|
|
48
|
-
if (Array.isArray(message.content)) {
|
|
49
|
-
message.content = message.content.filter((item) => item.type === 'text');
|
|
50
|
-
}
|
|
51
|
-
return message;
|
|
52
|
-
}
|
|
53
|
-
static buildScreenInfo(currentApp, extraInfo = {}) {
|
|
54
|
-
const info = { current_app: currentApp, ...extraInfo };
|
|
55
|
-
return JSON.stringify(info);
|
|
56
|
-
}
|
|
57
|
-
addSystemPrompt(prompt) {
|
|
58
|
-
this.messages.push({ role: 'system', content: prompt });
|
|
59
|
-
}
|
|
60
|
-
addUserMessage(content) {
|
|
61
|
-
this.messages.push({ role: 'user', content });
|
|
62
|
-
}
|
|
63
|
-
addScreenshot(base64Data, mimeType = 'image/jpeg') {
|
|
64
|
-
const lastUser = this.findLastUserMessage();
|
|
65
|
-
if (lastUser && typeof lastUser.content !== 'string') {
|
|
66
|
-
lastUser.content.push({
|
|
67
|
-
type: 'image_url',
|
|
68
|
-
image_url: { url: `data:${mimeType};base64,${base64Data}` },
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
else {
|
|
72
|
-
this.messages.push({
|
|
73
|
-
role: 'user',
|
|
74
|
-
content: [
|
|
75
|
-
{
|
|
76
|
-
type: 'image_url',
|
|
77
|
-
image_url: { url: `data:${mimeType};base64,${base64Data}` },
|
|
78
|
-
},
|
|
79
|
-
],
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
addAssistantMessage(content) {
|
|
84
|
-
this.messages.push({ role: 'assistant', content });
|
|
85
|
-
}
|
|
86
|
-
addProgressHint(stepCount, historyActions) {
|
|
87
|
-
const hint = `[Progress] Step ${stepCount}. Previous actions: ${historyActions.join(', ')}`;
|
|
88
|
-
this.addUserMessage(hint);
|
|
89
|
-
}
|
|
90
|
-
getMessages() {
|
|
91
|
-
return [...this.messages];
|
|
92
|
-
}
|
|
93
|
-
clear() {
|
|
94
|
-
this.messages = [];
|
|
95
|
-
}
|
|
96
|
-
compressHistory(maxImageMessages = 3) {
|
|
97
|
-
if (maxImageMessages <= 0) {
|
|
98
|
-
for (const msg of this.messages) {
|
|
99
|
-
MessageBuilder.removeImagesFromMessage(msg);
|
|
100
|
-
}
|
|
101
|
-
return this.messages;
|
|
102
|
-
}
|
|
103
|
-
const userIndices = [];
|
|
104
|
-
this.messages.forEach((msg, idx) => {
|
|
105
|
-
if (msg.role === 'user' && Array.isArray(msg.content)) {
|
|
106
|
-
userIndices.push(idx);
|
|
107
|
-
}
|
|
108
|
-
});
|
|
109
|
-
const keepFromIndex = userIndices.length - maxImageMessages;
|
|
110
|
-
const indicesToStrip = new Set();
|
|
111
|
-
userIndices.forEach((msgIdx, order) => {
|
|
112
|
-
if (order < keepFromIndex) {
|
|
113
|
-
indicesToStrip.add(msgIdx);
|
|
114
|
-
}
|
|
115
|
-
});
|
|
116
|
-
let strippedCount = 0;
|
|
117
|
-
for (const idx of indicesToStrip) {
|
|
118
|
-
const msg = this.messages[idx];
|
|
119
|
-
const beforeLen = Array.isArray(msg.content) ? msg.content.length : 0;
|
|
120
|
-
MessageBuilder.removeImagesFromMessage(msg);
|
|
121
|
-
const afterLen = Array.isArray(msg.content) ? msg.content.length : 0;
|
|
122
|
-
if (afterLen < beforeLen)
|
|
123
|
-
strippedCount++;
|
|
124
|
-
}
|
|
125
|
-
if (strippedCount > 0) {
|
|
126
|
-
logger_1.logger.debug(`MessageBuilder.compressHistory: stripped images from ${strippedCount} messages (kept last ${maxImageMessages})`);
|
|
127
|
-
}
|
|
128
|
-
return this.messages;
|
|
129
|
-
}
|
|
130
|
-
findLastUserMessage() {
|
|
131
|
-
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
132
|
-
if (this.messages[i].role === 'user')
|
|
133
|
-
return this.messages[i];
|
|
134
|
-
}
|
|
135
|
-
return null;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
exports.MessageBuilder = MessageBuilder;
|