@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.
- package/README.md +7 -0
- package/dist/api/agent_api.d.ts +2 -2
- package/dist/autotest-cli.js +1 -397
- package/dist/common/config/config.yaml +4 -0
- package/dist/common/config/manager.d.ts +4 -4
- package/dist/common/config/types.d.ts +5 -0
- package/dist/common/dfx/index.d.ts +1 -1
- package/dist/core/agent/single_agent/agent.d.ts +1 -0
- package/dist/core/device/device_protocol.d.ts +1 -1
- package/dist/core/knowledge/knowledge_manager.d.ts +3 -3
- package/dist/core/knowledge/vectordb.d.ts +5 -5
- package/dist/core/mcp/harmony_hdc_adapter.d.ts +1 -0
- package/dist/core/mcp/mcp_tools.d.ts +1 -0
- package/dist/core/mcp/verify_tool.d.ts +12 -0
- package/dist/core/prompt/templates/single/single_v2.0.md +15 -0
- package/dist/data_types/device.d.ts +1 -1
- package/dist/data_types/index.d.ts +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -163
- package/dist/tools/batch_runner.js +1 -745
- package/dist/tools/case_runner/runner.js +1 -410
- package/dist/tools/config/config_tool.js +1 -339
- 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 -185
- 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 -487
- 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 -82
- package/dist/core/agent/layered_agent/decision.js +0 -518
- 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 -801
- package/dist/core/agent/single_agent/hook_manager.js +0 -59
- package/dist/core/agent/single_agent/hooks.js +0 -288
- package/dist/core/agent/single_agent/image_utils.js +0 -158
- package/dist/core/agent/single_agent/scroll_search_agent.js +0 -405
- package/dist/core/agent/single_agent/subagent_manager.js +0 -72
- 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 -798
- 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 -473
- 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 -529
- 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,405 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* ScrollSearchAgent — 滚动查找子代理(
|
|
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, //
|
|
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 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
|
-
- 示例:用户说"在搜索栏下方的导航栏滑动",只要搜索栏下方的导航栏在页面上可见,就返回 true
|
|
52
|
-
- 示例:用户说"在小时调节区域滑动",只要时间选择器/小时调节区域在页面上可见,就返回 true
|
|
53
|
-
- 示例:用户说"在推荐列表中查找",只要列表区域在页面上可见,就返回 true
|
|
54
|
-
- **宽泛描述**:用户说"主页面"、"当前页面"、"页面"、"屏幕"、"整个页面"等宽泛概念时,直接返回 true,bounding_box 使用 [0, 100, 1000, 900]
|
|
55
|
-
- **禁止**因为"该区域中没有目标元素"而返回 false
|
|
56
|
-
- **禁止**因为"该区域看起来不能滑动"而返回 false
|
|
57
|
-
- 只有当页面上确实不存在用户描述的区域时,才返回 false
|
|
58
|
-
2. failure_reason: 如果 region_valid 为 false,说明失败原因
|
|
59
|
-
3. bounding_box: 可滑动内容区域的边界框 [left, top, right, bottom](0-1000整数)
|
|
60
|
-
- **必须严格基于用户描述的区域来确定 bounding_box,不要自行推测或脑补其他区域**
|
|
61
|
-
- 如果用户明确指定了区域(如"在推荐列表中"、"在月份列"、"在搜索栏下方"),bounding_box 必须精确覆盖用户描述的该区域
|
|
62
|
-
- **日期/时间选择器(date/time picker)特别注意**:
|
|
63
|
-
- picker 通常由多列滚轮组成(如年/月/日、时/分)
|
|
64
|
-
- **bounding_box 必须只包含需要调节的那一列滚轮**,绝对不能包含整个 picker
|
|
65
|
-
- **错误示例**:把整个 picker(所有列)都框进来 → 滑动时会同时影响多列,结果完全错误
|
|
66
|
-
- **正确做法**:只框选目标列的左右边界,高度可以包含整列
|
|
67
|
-
- 如果是导航栏/tab栏,选择该导航栏的区域
|
|
68
|
-
- 如果 region_valid 为 false,返回 [0, 0, 0, 0]
|
|
69
|
-
4. direction: 初始滑动方向(up/down/left/right)
|
|
70
|
-
5. user_specified_direction: 用户是否明确指定了方向(true/false)
|
|
71
|
-
6. is_numeric_adjustment: 是否是数字调节场景(true/false)
|
|
72
|
-
7. region_description: 滑动区域描述
|
|
73
|
-
8. target_description: 查找目标描述
|
|
74
|
-
9. target_number: 如果目标能解析为数字则返回数字,否则null
|
|
75
|
-
|
|
76
|
-
## 输出格式
|
|
77
|
-
只返回JSON:
|
|
78
|
-
{"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}`;
|
|
79
|
-
}
|
|
80
|
-
function judgmentPrompt(taskDesc, bbox, dir) {
|
|
81
|
-
return `## 任务
|
|
82
|
-
对比滑动前后的两张截图,仅关注滑动区域内的变化,判断滑动效果和目标查找状态。
|
|
83
|
-
|
|
84
|
-
## 查找目标
|
|
85
|
-
${taskDesc}
|
|
86
|
-
|
|
87
|
-
## 滑动区域
|
|
88
|
-
bounding_box: [${bbox.join(', ')}](0-1000整数坐标)
|
|
89
|
-
你只需要关注这个矩形区域内的内容,完全忽略区域外的一切。
|
|
90
|
-
|
|
91
|
-
## 滑动方向
|
|
92
|
-
${dir}(手指移动方向)
|
|
93
|
-
|
|
94
|
-
## 截图说明
|
|
95
|
-
- 第一张图:滑动前的屏幕
|
|
96
|
-
- 第二张图:滑动后的屏幕
|
|
97
|
-
|
|
98
|
-
## 判断要求
|
|
99
|
-
1. content_changed: 滑动后滑动区域内内容是否变化(true/false)
|
|
100
|
-
- 区域内的部分变化也算变化(如列表项滚动、标签位移、数字变化等)
|
|
101
|
-
- 如果只有区域外发生了变化而区域内没有变化,必须返回 false
|
|
102
|
-
2. target_found: 是否在第二张截图的**当前滑动区域内**已**完整看到**目标元素(true/false)
|
|
103
|
-
- **仅在上述 bounding_box 标记的滑动区域内查找目标**,区域外的元素即使与目标名称完全相同也不能算作找到
|
|
104
|
-
- **目标必须完全可见**:目标元素必须完整显示在 bounding_box 矩形范围内,不能被遮挡、裁剪或只显示一部分
|
|
105
|
-
- 不需要目标被精确选中、居中、高亮或可以直接点击,但目标本身必须完整可见
|
|
106
|
-
- 示例:在时间选择器年份列(bounding_box 范围内)查找1998,1998这个数字完整出现在滑动区域内(任何位置),就算找到了
|
|
107
|
-
- 示例:在列表中查找某张卡片,卡片必须完整显示在滑动区域内,只显示了顶部一小部分不算找到
|
|
108
|
-
- **反例**:如果 bounding_box 是小时列,即使分钟列中出现了目标数字,也必须返回 false
|
|
109
|
-
3. target_coords: 如果找到目标,返回目标坐标 [x, y](0-1000整数);未找到返回null
|
|
110
|
-
4. current_number: 数字调节场景返回当前选中数值;非数字场景返回null
|
|
111
|
-
5. blocking_popup: 是否有阻挡滑动的弹窗(true/false)
|
|
112
|
-
6. blocking_popup_close: 如果有弹窗,返回关闭按钮坐标 [x, y];无返回null
|
|
113
|
-
|
|
114
|
-
## 输出格式
|
|
115
|
-
只返回JSON:
|
|
116
|
-
{"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}`;
|
|
117
|
-
}
|
|
118
|
-
// ---- ScrollSearchAgent ----
|
|
119
|
-
class ScrollSearchAgent {
|
|
120
|
-
name = 'scroll_search';
|
|
121
|
-
description = '滑动查找目标使其进入可见区域,用于列表、导航栏、时间选择器等滚动场景。'
|
|
122
|
-
+ '一次只能查找一个元素,如需查找多个目标请分多次调用。'
|
|
123
|
-
+ '命令形式: 在<区域>滑动查找<目标描述>。'
|
|
124
|
-
+ '子agent会自动分析并探索滑动方向,遇到边界自动切换方向。'
|
|
125
|
-
+ '注意:本工具只负责将目标元素滚动到可见区域,不返回元素坐标,'
|
|
126
|
-
+ '如需点击目标元素请在调用本工具后另行执行点击操作。';
|
|
127
|
-
_llmCaller;
|
|
128
|
-
_adapter;
|
|
129
|
-
_config;
|
|
130
|
-
_reportGenerator;
|
|
131
|
-
_modelConfig;
|
|
132
|
-
_noChangeCount = 0;
|
|
133
|
-
constructor(adapter, modelConfig, config, reportGenerator) {
|
|
134
|
-
this._adapter = adapter;
|
|
135
|
-
this._modelConfig = modelConfig;
|
|
136
|
-
this._config = { ...exports.DEFAULT_SCROLL_CONFIG, ...config };
|
|
137
|
-
this._reportGenerator = reportGenerator ?? null;
|
|
138
|
-
this._llmCaller = new custom_model_1.LLMCaller();
|
|
139
|
-
}
|
|
140
|
-
async run(taskDescription, userDirection = '') {
|
|
141
|
-
logger_1.logger.info(`[ScrollSearch] Starting: task="${taskDescription.slice(0, 80)}" dir="${userDirection || '(auto)'}"`);
|
|
142
|
-
// Phase 1: Init — screenshot + LLM analysis
|
|
143
|
-
const initScreenshot = await this._takeScreenshot();
|
|
144
|
-
if (!initScreenshot) {
|
|
145
|
-
return { success: false, targetCoords: null, totalSteps: 0, message: '初始截图失败', summary: '截图失败' };
|
|
146
|
-
}
|
|
147
|
-
const initAnalysis = await this._vlmInitAnalysis(initScreenshot, taskDescription, userDirection);
|
|
148
|
-
if (!initAnalysis) {
|
|
149
|
-
return { success: false, targetCoords: null, totalSteps: 0, message: 'VLM 初始分析失败', summary: 'LLM分析失败' };
|
|
150
|
-
}
|
|
151
|
-
if (!initAnalysis.regionValid) {
|
|
152
|
-
const reason = initAnalysis.failureReason || '区域不存在';
|
|
153
|
-
return { success: false, targetCoords: null, totalSteps: 0, message: `区域验证失败: ${reason}`, summary: `区域不存在: ${reason}` };
|
|
154
|
-
}
|
|
155
|
-
logger_1.logger.info(`[ScrollSearch] Region: [${initAnalysis.boundingBox.join(', ')}] dir=${initAnalysis.direction} target="${initAnalysis.targetDescription}"`);
|
|
156
|
-
// Check if target already visible in init screenshot
|
|
157
|
-
const initJudgment = await this._vlmJudgment(initScreenshot, initScreenshot, taskDescription, initAnalysis.boundingBox, initAnalysis.direction);
|
|
158
|
-
if (initJudgment?.targetFound && initJudgment.targetCoords) {
|
|
159
|
-
logger_1.logger.info(`[ScrollSearch] Target found in initial screenshot at [${initJudgment.targetCoords.join(', ')}]`);
|
|
160
|
-
return this._success(initJudgment.targetCoords, 0, '目标在初始截图中已可见');
|
|
161
|
-
}
|
|
162
|
-
// Main loop
|
|
163
|
-
let prevScreenshot = initScreenshot;
|
|
164
|
-
let direction = initAnalysis.direction;
|
|
165
|
-
let consecutiveNoChange = 0;
|
|
166
|
-
for (let step = 1; step <= this._config.maxSteps; step++) {
|
|
167
|
-
logger_1.logger.info(`[ScrollSearch] Step ${step}/${this._config.maxSteps}`);
|
|
168
|
-
// 1. Execute swipe
|
|
169
|
-
const swipeDistance = this._calculateSwipeDistance(initAnalysis, direction, step);
|
|
170
|
-
await this._executeSwipe(direction, initAnalysis.boundingBox, swipeDistance);
|
|
171
|
-
await this._sleep(this._config.swipeWaitMs);
|
|
172
|
-
// 2. Take screenshot after swipe
|
|
173
|
-
const afterScreenshot = await this._takeScreenshot();
|
|
174
|
-
if (!afterScreenshot) {
|
|
175
|
-
logger_1.logger.warn(`[ScrollSearch] Step ${step}: 截图失败,跳过`);
|
|
176
|
-
continue;
|
|
177
|
-
}
|
|
178
|
-
// 3. VLM judgment
|
|
179
|
-
const judgment = await this._vlmJudgment(prevScreenshot, afterScreenshot, taskDescription, initAnalysis.boundingBox, direction);
|
|
180
|
-
if (!judgment) {
|
|
181
|
-
logger_1.logger.warn(`[ScrollSearch] Step ${step}: VLM 判断失败`);
|
|
182
|
-
prevScreenshot = afterScreenshot;
|
|
183
|
-
continue;
|
|
184
|
-
}
|
|
185
|
-
// 4. Handle popup
|
|
186
|
-
if (judgment.blockingPopup && judgment.blockingPopupClose) {
|
|
187
|
-
const [px, py] = this._scaleFrom1000(judgment.blockingPopupClose);
|
|
188
|
-
await this._adapter.callTool('click', { pos: [px, py] });
|
|
189
|
-
logger_1.logger.info(`[ScrollSearch] Step ${step}: 关闭弹窗 at [${px}, ${py}]`);
|
|
190
|
-
await this._sleep(500);
|
|
191
|
-
prevScreenshot = afterScreenshot;
|
|
192
|
-
continue;
|
|
193
|
-
}
|
|
194
|
-
// 5. Target found?
|
|
195
|
-
if (judgment.targetFound && judgment.targetCoords) {
|
|
196
|
-
const [tx, ty] = this._scaleFrom1000(judgment.targetCoords);
|
|
197
|
-
logger_1.logger.info(`[ScrollSearch] Target found at step ${step}! coords=[${tx}, ${ty}]`);
|
|
198
|
-
return this._success([tx, ty], step, `在第 ${step} 步找到目标`);
|
|
199
|
-
}
|
|
200
|
-
// 6. Content changed?
|
|
201
|
-
if (!judgment.contentChanged) {
|
|
202
|
-
consecutiveNoChange++;
|
|
203
|
-
logger_1.logger.info(`[ScrollSearch] Step ${step}: 内容未变化 (连续 ${consecutiveNoChange} 次)`);
|
|
204
|
-
if (consecutiveNoChange >= 1) {
|
|
205
|
-
// Switch direction
|
|
206
|
-
const newDir = opposite(direction);
|
|
207
|
-
logger_1.logger.info(`[ScrollSearch] Step ${step}: 切换方向 ${direction} → ${newDir}`);
|
|
208
|
-
direction = newDir;
|
|
209
|
-
consecutiveNoChange = 0;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
else {
|
|
213
|
-
consecutiveNoChange = 0;
|
|
214
|
-
}
|
|
215
|
-
// 7. Numeric adjustment (picker)
|
|
216
|
-
if (initAnalysis.isNumericAdjustment && judgment.currentNumber !== null && initAnalysis.targetNumber !== null) {
|
|
217
|
-
const adjusted = this._adjustNumericSwipe(judgment.currentNumber, initAnalysis.targetNumber, direction, initAnalysis.boundingBox);
|
|
218
|
-
if (adjusted) {
|
|
219
|
-
direction = adjusted.direction;
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
prevScreenshot = afterScreenshot;
|
|
223
|
-
}
|
|
224
|
-
// Max steps reached
|
|
225
|
-
return {
|
|
226
|
-
success: false,
|
|
227
|
-
targetCoords: null,
|
|
228
|
-
totalSteps: this._config.maxSteps,
|
|
229
|
-
message: `达到最大步数 ${this._config.maxSteps},未找到目标`,
|
|
230
|
-
summary: `未找到目标(${this._config.maxSteps}步)`,
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
// ---- VLM interactions ----
|
|
234
|
-
async _vlmInitAnalysis(screenshot, taskDesc, userDir) {
|
|
235
|
-
try {
|
|
236
|
-
const result = await this._llmCaller.call({
|
|
237
|
-
systemPrompt: SYSTEM_PROMPT,
|
|
238
|
-
userPrompt: initAnalysisPrompt(taskDesc, userDir),
|
|
239
|
-
images: [{ base64Data: screenshot, mimeType: 'image/jpeg' }],
|
|
240
|
-
modelConfig: this._modelConfig,
|
|
241
|
-
});
|
|
242
|
-
return this._parseInitAnalysis(result.text);
|
|
243
|
-
}
|
|
244
|
-
catch (e) {
|
|
245
|
-
logger_1.logger.error(`[ScrollSearch] VLM init analysis failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
246
|
-
return null;
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
async _vlmJudgment(before, after, taskDesc, bbox, dir) {
|
|
250
|
-
try {
|
|
251
|
-
const result = await this._llmCaller.call({
|
|
252
|
-
systemPrompt: SYSTEM_PROMPT,
|
|
253
|
-
userPrompt: judgmentPrompt(taskDesc, bbox, dir),
|
|
254
|
-
images: [
|
|
255
|
-
{ base64Data: before, mimeType: 'image/jpeg' },
|
|
256
|
-
{ base64Data: after, mimeType: 'image/jpeg' },
|
|
257
|
-
],
|
|
258
|
-
modelConfig: this._modelConfig,
|
|
259
|
-
});
|
|
260
|
-
return this._parseStepJudgment(result.text);
|
|
261
|
-
}
|
|
262
|
-
catch (e) {
|
|
263
|
-
logger_1.logger.error(`[ScrollSearch] VLM judgment failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
264
|
-
return null;
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
// ---- JSON parsing ----
|
|
268
|
-
_parseJson(text) {
|
|
269
|
-
// Strip markdown code fences if present
|
|
270
|
-
let s = text.trim();
|
|
271
|
-
s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
|
|
272
|
-
// Find first { and last }
|
|
273
|
-
const start = s.indexOf('{');
|
|
274
|
-
const end = s.lastIndexOf('}');
|
|
275
|
-
if (start < 0 || end < 0)
|
|
276
|
-
return null;
|
|
277
|
-
try {
|
|
278
|
-
return JSON.parse(s.slice(start, end + 1));
|
|
279
|
-
}
|
|
280
|
-
catch {
|
|
281
|
-
return null;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
_parseInitAnalysis(text) {
|
|
285
|
-
const j = this._parseJson(text);
|
|
286
|
-
if (!j)
|
|
287
|
-
return null;
|
|
288
|
-
const bbox = Array.isArray(j.bounding_box) ? j.bounding_box : [0, 0, 0, 0];
|
|
289
|
-
return {
|
|
290
|
-
regionValid: Boolean(j.region_valid),
|
|
291
|
-
failureReason: String(j.failure_reason ?? ''),
|
|
292
|
-
boundingBox: [bbox[0] ?? 0, bbox[1] ?? 0, bbox[2] ?? 0, bbox[3] ?? 0],
|
|
293
|
-
direction: (['up', 'down', 'left', 'right'].includes(String(j.direction)) ? String(j.direction) : 'up'),
|
|
294
|
-
userSpecifiedDirection: Boolean(j.user_specified_direction),
|
|
295
|
-
isNumericAdjustment: Boolean(j.is_numeric_adjustment),
|
|
296
|
-
regionDescription: String(j.region_description ?? ''),
|
|
297
|
-
targetDescription: String(j.target_description ?? ''),
|
|
298
|
-
targetNumber: typeof j.target_number === 'number' ? j.target_number : null,
|
|
299
|
-
};
|
|
300
|
-
}
|
|
301
|
-
_parseStepJudgment(text) {
|
|
302
|
-
const j = this._parseJson(text);
|
|
303
|
-
if (!j)
|
|
304
|
-
return null;
|
|
305
|
-
const tc = Array.isArray(j.target_coords) ? j.target_coords : null;
|
|
306
|
-
const pc = Array.isArray(j.blocking_popup_close) ? j.blocking_popup_close : null;
|
|
307
|
-
return {
|
|
308
|
-
contentChanged: Boolean(j.content_changed),
|
|
309
|
-
targetFound: Boolean(j.target_found),
|
|
310
|
-
targetCoords: tc ? [tc[0], tc[1]] : null,
|
|
311
|
-
currentNumber: typeof j.current_number === 'number' ? j.current_number : null,
|
|
312
|
-
blockingPopup: Boolean(j.blocking_popup),
|
|
313
|
-
blockingPopupClose: pc ? [pc[0], pc[1]] : null,
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
// ---- Swipe calculation ----
|
|
317
|
-
_calculateSwipeDistance(init, dir, _step) {
|
|
318
|
-
// Default distance based on config
|
|
319
|
-
let ratio = this._config.defaultDistanceRatio;
|
|
320
|
-
// For numeric adjustment, calculate based on current vs target
|
|
321
|
-
if (init.isNumericAdjustment && init.targetNumber !== null) {
|
|
322
|
-
// Use close distance for fine-tuning
|
|
323
|
-
ratio = this._config.closeDistanceRatio;
|
|
324
|
-
}
|
|
325
|
-
return Math.max(ratio, this._config.minDistanceRatio);
|
|
326
|
-
}
|
|
327
|
-
_adjustNumericSwipe(current, target, dir, _bbox) {
|
|
328
|
-
if (current === target)
|
|
329
|
-
return null;
|
|
330
|
-
// If current > target and scrolling up increases value → keep direction
|
|
331
|
-
// If current > target and scrolling up decreases value → flip direction
|
|
332
|
-
// For pickers: up usually increases, down decreases
|
|
333
|
-
const needIncrease = target > current;
|
|
334
|
-
const upIncreases = isVertical(dir) && dir === 'up';
|
|
335
|
-
if (needIncrease !== upIncreases) {
|
|
336
|
-
const newDir = opposite(dir);
|
|
337
|
-
logger_1.logger.info(`[ScrollSearch] Numeric: current=${current} target=${target}, flip ${dir}→${newDir}`);
|
|
338
|
-
return { direction: newDir };
|
|
339
|
-
}
|
|
340
|
-
return { direction: dir };
|
|
341
|
-
}
|
|
342
|
-
// ---- Swipe execution ----
|
|
343
|
-
async _executeSwipe(dir, bbox, distanceRatio) {
|
|
344
|
-
const [l, t, r, b] = bbox;
|
|
345
|
-
// Center of bounding box (0-1000 scale → 0-1 relative)
|
|
346
|
-
const cx = ((l + r) / 2) / 1000;
|
|
347
|
-
const cy = ((t + b) / 2) / 1000;
|
|
348
|
-
const regionHeight = (b - t) / 1000;
|
|
349
|
-
const regionWidth = (r - l) / 1000;
|
|
350
|
-
let sx = cx, sy = cy, ex = cx, ey = cy;
|
|
351
|
-
if (dir === 'up') {
|
|
352
|
-
// Finger moves up: start below center, end above
|
|
353
|
-
sy = cy + regionHeight * distanceRatio * 0.5;
|
|
354
|
-
ey = cy - regionHeight * distanceRatio * 0.5;
|
|
355
|
-
}
|
|
356
|
-
else if (dir === 'down') {
|
|
357
|
-
sy = cy - regionHeight * distanceRatio * 0.5;
|
|
358
|
-
ey = cy + regionHeight * distanceRatio * 0.5;
|
|
359
|
-
}
|
|
360
|
-
else if (dir === 'left') {
|
|
361
|
-
sx = cx + regionWidth * distanceRatio * 0.5;
|
|
362
|
-
ex = cx - regionWidth * distanceRatio * 0.5;
|
|
363
|
-
}
|
|
364
|
-
else {
|
|
365
|
-
sx = cx - regionWidth * distanceRatio * 0.5;
|
|
366
|
-
ex = cx + regionWidth * distanceRatio * 0.5;
|
|
367
|
-
}
|
|
368
|
-
// Clamp to 0-1
|
|
369
|
-
sx = Math.max(0, Math.min(1, sx));
|
|
370
|
-
sy = Math.max(0, Math.min(1, sy));
|
|
371
|
-
ex = Math.max(0, Math.min(1, ex));
|
|
372
|
-
ey = Math.max(0, Math.min(1, ey));
|
|
373
|
-
logger_1.logger.debug(`[ScrollSearch] Swipe ${dir}: [${sx.toFixed(3)},${sy.toFixed(3)}] → [${ex.toFixed(3)},${ey.toFixed(3)}]`);
|
|
374
|
-
await this._adapter.callTool('swipe', { start: [sx, sy], end: [ex, ey], direction: dir, log: `scroll_search ${dir}` });
|
|
375
|
-
}
|
|
376
|
-
// ---- Helpers ----
|
|
377
|
-
async _takeScreenshot() {
|
|
378
|
-
try {
|
|
379
|
-
const shot = await this._adapter.getScreenshot();
|
|
380
|
-
if (!shot.base64Data)
|
|
381
|
-
return null;
|
|
382
|
-
// Compress before returning (reduces LLM input tokens → faster response)
|
|
383
|
-
return await (0, image_helper_1.compressBase64Image)(shot.base64Data, this._config.screenshotMaxPixels, 70);
|
|
384
|
-
}
|
|
385
|
-
catch {
|
|
386
|
-
return null;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
_scaleFrom1000(coords) {
|
|
390
|
-
return [coords[0] / 1000, coords[1] / 1000];
|
|
391
|
-
}
|
|
392
|
-
_success(coords, steps, msg) {
|
|
393
|
-
return {
|
|
394
|
-
success: true,
|
|
395
|
-
targetCoords: coords,
|
|
396
|
-
totalSteps: steps,
|
|
397
|
-
message: msg,
|
|
398
|
-
summary: `找到目标: ${msg}`,
|
|
399
|
-
};
|
|
400
|
-
}
|
|
401
|
-
_sleep(ms) {
|
|
402
|
-
return new Promise(r => setTimeout(r, ms));
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
exports.ScrollSearchAgent = ScrollSearchAgent;
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Subagent infrastructure.
|
|
4
|
-
*
|
|
5
|
-
* SubagentManager allows the parent agent to delegate work to child agents
|
|
6
|
-
* via a `run_subagent` tool call. Child steps are offset from the parent's
|
|
7
|
-
* step counter for correct numbering in reports.
|
|
8
|
-
*
|
|
9
|
-
* NOTE: Full event buffering (start_buffering/drain_buffer/attach_sub_events)
|
|
10
|
-
* is deferred — this version provides the registration + invocation + step
|
|
11
|
-
* offset infrastructure.
|
|
12
|
-
*/
|
|
13
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
-
exports.SubagentManager = void 0;
|
|
15
|
-
exports.getSubagentManager = getSubagentManager;
|
|
16
|
-
const logger_1 = require("../../../common/logger");
|
|
17
|
-
class SubagentManager {
|
|
18
|
-
_subagents = new Map();
|
|
19
|
-
_parentStep = 0;
|
|
20
|
-
/** Register a sub-agent by name with a runner function. */
|
|
21
|
-
register(name, description, runner, defaultTaskDescription) {
|
|
22
|
-
this._subagents.set(name, { name, description, runner, defaultTaskDescription });
|
|
23
|
-
logger_1.logger.debug(`[SubagentManager] registered sub-agent '${name}'`);
|
|
24
|
-
}
|
|
25
|
-
/** Unregister a sub-agent. */
|
|
26
|
-
unregister(name) {
|
|
27
|
-
this._subagents.delete(name);
|
|
28
|
-
}
|
|
29
|
-
/** List registered sub-agent names + descriptions (for tool schema). */
|
|
30
|
-
listSubagents() {
|
|
31
|
-
return Array.from(this._subagents.values()).map((s) => ({ name: s.name, description: s.description }));
|
|
32
|
-
}
|
|
33
|
-
/** Set the parent's current step (for step offset calculation). */
|
|
34
|
-
setParentStep(step) {
|
|
35
|
-
this._parentStep = step;
|
|
36
|
-
}
|
|
37
|
-
/** Run a sub-agent by name. Step offset = parent step (child steps start from parent+1). */
|
|
38
|
-
async runSubagent(name, task, reportGenerator) {
|
|
39
|
-
const sub = this._subagents.get(name);
|
|
40
|
-
if (!sub) {
|
|
41
|
-
return { name, success: false, output: `Sub-agent '${name}' not found`, stepsUsed: 0 };
|
|
42
|
-
}
|
|
43
|
-
const stepOffset = this._parentStep;
|
|
44
|
-
logger_1.logger.info(`[SubagentManager] running sub-agent '${name}' (step offset=${stepOffset}): ${task.slice(0, 80)}`);
|
|
45
|
-
try {
|
|
46
|
-
const result = await sub.runner(task, { stepOffset, reportGenerator });
|
|
47
|
-
logger_1.logger.info(`[SubagentManager] sub-agent '${name}' completed: success=${result.success}, steps=${result.stepsUsed}`);
|
|
48
|
-
return result;
|
|
49
|
-
}
|
|
50
|
-
catch (e) {
|
|
51
|
-
const msg = e instanceof Error ? e.message : String(e);
|
|
52
|
-
logger_1.logger.error(`[SubagentManager] sub-agent '${name}' failed: ${msg}`);
|
|
53
|
-
return { name, success: false, output: msg, stepsUsed: 0 };
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
/** Build a tool description string for the LLM (lists available sub-agents). */
|
|
57
|
-
getToolDescription() {
|
|
58
|
-
const subs = this.listSubagents();
|
|
59
|
-
if (subs.length === 0)
|
|
60
|
-
return 'No sub-agents available.';
|
|
61
|
-
return subs.map((s) => `- ${s.name}: ${s.description}`).join('\n');
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
exports.SubagentManager = SubagentManager;
|
|
65
|
-
/** Singleton instance. */
|
|
66
|
-
let _instance = null;
|
|
67
|
-
function getSubagentManager() {
|
|
68
|
-
if (!_instance) {
|
|
69
|
-
_instance = new SubagentManager();
|
|
70
|
-
}
|
|
71
|
-
return _instance;
|
|
72
|
-
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* ToolRecorderHook — cross-cutting hook that auto-records every tool call via
|
|
4
|
-
* the global HookManager.
|
|
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;
|