@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,150 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
// get_step_screenshot tool definition.
|
|
3
|
-
//
|
|
4
|
-
// Screenshot data is returned directly to the LLM via images + a text description.
|
|
5
|
-
// The tool function appends the step number to context.screenshotCalls (for guardrail checks).
|
|
6
|
-
// Return value contains operation info (tool_name(arguments) as-is), the view reason (desc),
|
|
7
|
-
// and a comparison note.
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.parseStepNumbers = parseStepNumbers;
|
|
10
|
-
exports.getStepScreenshot = getStepScreenshot;
|
|
11
|
-
exports.getStepScreenshotErrorFunction = getStepScreenshotErrorFunction;
|
|
12
|
-
const image_helper_1 = require("../../../common/image_helper");
|
|
13
|
-
const logger_1 = require("../../../common/logger");
|
|
14
|
-
// data URI prefix returned by compressImageToBase64
|
|
15
|
-
const DATA_URI_PREFIX = 'data:image/jpeg;base64,';
|
|
16
|
-
// Compress a screenshot path to pure base64 (strip the data URI prefix).
|
|
17
|
-
async function compressToPureBase64(filePath, maxPixels) {
|
|
18
|
-
const dataUri = await (0, image_helper_1.compressImageToBase64)(filePath, maxPixels);
|
|
19
|
-
if (!dataUri) {
|
|
20
|
-
logger_1.logger.warn(`Screenshot compression failed or file does not exist: ${filePath}`);
|
|
21
|
-
return '';
|
|
22
|
-
}
|
|
23
|
-
if (dataUri.startsWith(DATA_URI_PREFIX)) {
|
|
24
|
-
return dataUri.slice(DATA_URI_PREFIX.length);
|
|
25
|
-
}
|
|
26
|
-
return dataUri;
|
|
27
|
-
}
|
|
28
|
-
// View label mapping
|
|
29
|
-
const VIEW_LABELS = {
|
|
30
|
-
observed: 'Agent observation (seen at decision time)',
|
|
31
|
-
before_action: 'Before action (prior to execution)',
|
|
32
|
-
};
|
|
33
|
-
/**
|
|
34
|
-
* Parse a step-number argument that may be a number, a numeric string, or a
|
|
35
|
-
* comma-separated list ("1,2,3"). Returns de-duplicated numbers preserving
|
|
36
|
-
* first-seen order. Aligned with python screenshot_tool._parse_step_numbers.
|
|
37
|
-
*/
|
|
38
|
-
function parseStepNumbers(value) {
|
|
39
|
-
const raw = String(value ?? '').trim();
|
|
40
|
-
if (!raw)
|
|
41
|
-
return [];
|
|
42
|
-
const seen = new Set();
|
|
43
|
-
const out = [];
|
|
44
|
-
for (const part of raw.split(/[,\s]+/)) {
|
|
45
|
-
const n = parseInt(part, 10);
|
|
46
|
-
if (!Number.isNaN(n) && !seen.has(n)) {
|
|
47
|
-
seen.add(n);
|
|
48
|
-
out.push(n);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return out;
|
|
52
|
-
}
|
|
53
|
-
// Load screenshot data for one or more steps (stepNumber may be "1,2,3").
|
|
54
|
-
// desc explains why the screenshots are being viewed.
|
|
55
|
-
async function getStepScreenshot(ctx, stepNumber, desc = '') {
|
|
56
|
-
const reportData = ctx.reportData;
|
|
57
|
-
if (!reportData) {
|
|
58
|
-
return { images: [], text: 'Report data not loaded', loaded: false };
|
|
59
|
-
}
|
|
60
|
-
const stepNums = parseStepNumbers(stepNumber);
|
|
61
|
-
if (stepNums.length === 0) {
|
|
62
|
-
return { images: [], text: `Invalid step number: ${stepNumber}`, loaded: false };
|
|
63
|
-
}
|
|
64
|
-
// Compression hardcode (aligned with Python screenshot_tool.py: _COMPRESS_MAX_PIXELS = 1500)
|
|
65
|
-
const maxPixels = 1500;
|
|
66
|
-
const contentBlocks = [];
|
|
67
|
-
const flatImages = [];
|
|
68
|
-
const loadedStepKeys = [];
|
|
69
|
-
for (const sn of stepNums) {
|
|
70
|
-
// Find the target StepData
|
|
71
|
-
let targetStep = null;
|
|
72
|
-
for (const s of reportData.steps) {
|
|
73
|
-
if (s.stepNumber === sn) {
|
|
74
|
-
targetStep = s;
|
|
75
|
-
break;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
if (!targetStep) {
|
|
79
|
-
const total = reportData.steps.length;
|
|
80
|
-
contentBlocks.push({ type: 'text', text: `\n[Step ${sn} does not exist (total ${total} steps)]\n` });
|
|
81
|
-
continue;
|
|
82
|
-
}
|
|
83
|
-
const screenshots = targetStep.screenshots ?? [];
|
|
84
|
-
// Step header text (interleaved before the images)
|
|
85
|
-
const headerParts = [`\n=== Step ${sn} ===`];
|
|
86
|
-
if (desc)
|
|
87
|
-
headerParts.push(` (reason: ${desc})`);
|
|
88
|
-
// Operation info
|
|
89
|
-
const tc = targetStep.toolCall ?? {};
|
|
90
|
-
const toolName = tc['tool_name'] ?? '';
|
|
91
|
-
const arguments_ = tc['arguments'] ?? {};
|
|
92
|
-
if (toolName)
|
|
93
|
-
headerParts.push(`\nOperation: ${toolName}(${JSON.stringify(arguments_)})`);
|
|
94
|
-
contentBlocks.push({ type: 'text', text: headerParts.join('') });
|
|
95
|
-
const views = screenshots.length >= 2
|
|
96
|
-
? [{ idx: 0, key: 'observed' }, { idx: 1, key: 'before_action' }]
|
|
97
|
-
: screenshots.length === 1
|
|
98
|
-
? [{ idx: 0, key: 'observed' }]
|
|
99
|
-
: [];
|
|
100
|
-
let loadedForStep = 0;
|
|
101
|
-
for (const { idx, key } of views) {
|
|
102
|
-
const b64 = await compressToPureBase64(screenshots[idx], maxPixels);
|
|
103
|
-
if (b64) {
|
|
104
|
-
// View label text interleaved before each image
|
|
105
|
-
contentBlocks.push({ type: 'text', text: `\n[${sn} ${key}] ${VIEW_LABELS[key]}\n` });
|
|
106
|
-
contentBlocks.push({ type: 'image', base64Data: b64, mimeType: 'image/jpeg' });
|
|
107
|
-
flatImages.push({ base64Data: b64, mimeType: 'image/jpeg' });
|
|
108
|
-
loadedStepKeys.push(`${sn}:${key}`);
|
|
109
|
-
loadedForStep++;
|
|
110
|
-
logger_1.logger.debug(`getStepScreenshot: step ${sn} ${key} screenshot (idx=${idx})`);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
if (loadedForStep === 0) {
|
|
114
|
-
contentBlocks.push({ type: 'text', text: `\n[Step ${sn} has no screenshot data]\n` });
|
|
115
|
-
}
|
|
116
|
-
// Record the viewed step number (for guardrail process checks)
|
|
117
|
-
ctx.screenshotCalls.push(sn);
|
|
118
|
-
}
|
|
119
|
-
if (flatImages.length === 0) {
|
|
120
|
-
return { images: [], text: `Step(s) ${stepNums.join(',')} have no screenshot data`, loaded: false };
|
|
121
|
-
}
|
|
122
|
-
// Build a human-readable description text
|
|
123
|
-
const parts = [`Screenshots loaded: step(s) ${stepNums.join(',')}`];
|
|
124
|
-
if (desc)
|
|
125
|
-
parts.push(`, reason: ${desc}`);
|
|
126
|
-
parts.push(`. Views: ${loadedStepKeys.join(', ')}.`);
|
|
127
|
-
if (stepNums.length > 1) {
|
|
128
|
-
parts.push(' Multiple steps provided in a single call; compare across steps where relevant.');
|
|
129
|
-
}
|
|
130
|
-
const text = parts.join('');
|
|
131
|
-
// Stash interleaved text/image blocks into pendingImages (consumed before the next LLM call)
|
|
132
|
-
if (contentBlocks.length > 0) {
|
|
133
|
-
ctx.pendingImages.push({
|
|
134
|
-
role: 'user',
|
|
135
|
-
content: contentBlocks.map((b) => b.type === 'text'
|
|
136
|
-
? { type: 'text', text: b.text }
|
|
137
|
-
: { type: 'input_image', image_url: `${DATA_URI_PREFIX}${b.base64Data}` }),
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
return { images: flatImages, text, loaded: true };
|
|
141
|
-
}
|
|
142
|
-
// Friendly error handler for get_step_screenshot (used when tool args are malformed).
|
|
143
|
-
function getStepScreenshotErrorFunction(error) {
|
|
144
|
-
const errorMsg = String(error?.message ?? error);
|
|
145
|
-
if (errorMsg.includes('expected a JSON object')) {
|
|
146
|
-
return ('Tool parameter format error: please pass parameters as a JSON object, not an array. ' +
|
|
147
|
-
'Correct format example: {"step_number": 1}');
|
|
148
|
-
}
|
|
149
|
-
return `Tool call error, please retry. Error: ${errorMsg.slice(0, 200)}`;
|
|
150
|
-
}
|
|
@@ -1,274 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
// Type definitions for the ReportAnalyzerAgent.
|
|
3
|
-
// Mirrors the Python types.py with TypeScript classes/interfaces.
|
|
4
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.AnalyzerOutput = exports.RootCauseClassification = exports.VALID_CATEGORY_LABELS = exports.ACCURACY_CN_TO_EN = exports.VALID_ACCURACY_VALUES = exports.ROOT_CAUSE_SUB_CATEGORIES = exports.AccuracyVerdict = exports.ROOT_CAUSE_CATEGORY_LABELS = exports.RootCauseCategory = exports.EVIDENCE_NONE = exports.EVIDENCE_MISSING = exports.EVIDENCE_PARTIAL = exports.EVIDENCE_COMPLETE = exports.CONSISTENCY_SEVERITY_ERROR = exports.CONSISTENCY_SEVERITY_WARNING = exports.CONSISTENCY_SEVERITY_INFO = exports.ANALYSIS_SUBDIR = void 0;
|
|
6
|
-
exports.resolveSubCategory = resolveSubCategory;
|
|
7
|
-
exports.createAnalyzerContext = createAnalyzerContext;
|
|
8
|
-
exports.createRootCauseResult = createRootCauseResult;
|
|
9
|
-
// Analysis result subdirectory name (single source of truth to avoid DRY violations)
|
|
10
|
-
exports.ANALYSIS_SUBDIR = 'analysis';
|
|
11
|
-
exports.CONSISTENCY_SEVERITY_INFO = 'info';
|
|
12
|
-
exports.CONSISTENCY_SEVERITY_WARNING = 'warning';
|
|
13
|
-
exports.CONSISTENCY_SEVERITY_ERROR = 'error';
|
|
14
|
-
exports.EVIDENCE_COMPLETE = 'complete';
|
|
15
|
-
exports.EVIDENCE_PARTIAL = 'partial';
|
|
16
|
-
exports.EVIDENCE_MISSING = 'missing';
|
|
17
|
-
exports.EVIDENCE_NONE = 'none';
|
|
18
|
-
// 5 top-level root cause categories (对齐 python 5 值:应用问题/Agent问题/用例问题/环境问题/无问题).
|
|
19
|
-
// Values are English labels used as identifiers throughout the pipeline.
|
|
20
|
-
var RootCauseCategory;
|
|
21
|
-
(function (RootCauseCategory) {
|
|
22
|
-
RootCauseCategory["APP_ISSUE"] = "Application Issue";
|
|
23
|
-
RootCauseCategory["AGENT_ISSUE"] = "Agent Issue";
|
|
24
|
-
RootCauseCategory["CASE_ISSUE"] = "Test Case Issue";
|
|
25
|
-
RootCauseCategory["ENV_ISSUE"] = "Environment Issue";
|
|
26
|
-
RootCauseCategory["NO_ISSUE"] = "No Issue";
|
|
27
|
-
})(RootCauseCategory || (exports.RootCauseCategory = RootCauseCategory = {}));
|
|
28
|
-
// 5 top-level category label map (value is the RootCauseCategory enum value)
|
|
29
|
-
exports.ROOT_CAUSE_CATEGORY_LABELS = {
|
|
30
|
-
'Application Issue': 'Application Issue',
|
|
31
|
-
'Agent Issue': 'Agent Issue',
|
|
32
|
-
'Test Case Issue': 'Test Case Issue',
|
|
33
|
-
'Environment Issue': 'Environment Issue',
|
|
34
|
-
'No Issue': 'No Issue',
|
|
35
|
-
};
|
|
36
|
-
// Accuracy verdict (4-way).
|
|
37
|
-
var AccuracyVerdict;
|
|
38
|
-
(function (AccuracyVerdict) {
|
|
39
|
-
AccuracyVerdict["CORRECT"] = "Correct";
|
|
40
|
-
AccuracyVerdict["MISJUDGED_PASS"] = "Misjudged Pass";
|
|
41
|
-
AccuracyVerdict["MISJUDGED_FAIL"] = "Misjudged Fail";
|
|
42
|
-
AccuracyVerdict["INCONCLUSIVE"] = "Inconclusive";
|
|
43
|
-
})(AccuracyVerdict || (exports.AccuracyVerdict = AccuracyVerdict = {}));
|
|
44
|
-
// Second-level root cause names keyed by top-level category label.
|
|
45
|
-
// APP 5, AGENT 6, CASE 7, ENV 6.
|
|
46
|
-
exports.ROOT_CAUSE_SUB_CATEGORIES = {
|
|
47
|
-
'Application Issue': {
|
|
48
|
-
'Functional Exception': 'Functional Exception',
|
|
49
|
-
'UI Display Bug': 'UI Display Bug',
|
|
50
|
-
'Data Inconsistency': 'Data Inconsistency',
|
|
51
|
-
'Interaction Logic Bug': 'Interaction Logic Bug',
|
|
52
|
-
'Compatibility/Stability Bug': 'Compatibility/Stability Bug',
|
|
53
|
-
},
|
|
54
|
-
'Agent Issue': {
|
|
55
|
-
'Operation Error': 'Operation Error',
|
|
56
|
-
'Omitted Operation': 'Omitted Operation',
|
|
57
|
-
'Understanding Error': 'Understanding Error',
|
|
58
|
-
'Cognition Error': 'Understanding Error',
|
|
59
|
-
'Reasoning Error': 'Understanding Error',
|
|
60
|
-
'Cognition Reasoning Error': 'Understanding Error',
|
|
61
|
-
'Operation Lag': 'Operation Lag',
|
|
62
|
-
'Repeated Operation': 'Repeated Operation',
|
|
63
|
-
'Tool Exception': 'Tool Exception',
|
|
64
|
-
},
|
|
65
|
-
'Test Case Issue': {
|
|
66
|
-
'Ambiguous Step': 'Ambiguous Step',
|
|
67
|
-
'Ambiguous Expectation': 'Ambiguous Expectation',
|
|
68
|
-
'Unexecutable': 'Unexecutable',
|
|
69
|
-
'Missing Prerequisite': 'Missing Prerequisite',
|
|
70
|
-
'Missing Step': 'Missing Step',
|
|
71
|
-
'Unreasonable Expectation': 'Unreasonable Expectation',
|
|
72
|
-
'External Dependency': 'External Dependency',
|
|
73
|
-
},
|
|
74
|
-
'Environment Issue': {
|
|
75
|
-
'Data Preparation': 'Data Preparation',
|
|
76
|
-
'Data Not Prepared': 'Data Preparation',
|
|
77
|
-
'Account/Permission': 'Account/Permission',
|
|
78
|
-
'Network Exception': 'Network Exception',
|
|
79
|
-
'Device Exception': 'Device Exception',
|
|
80
|
-
'Configuration Error': 'Configuration Error',
|
|
81
|
-
'Business Limitation': 'Business Limitation',
|
|
82
|
-
},
|
|
83
|
-
'No Issue': {
|
|
84
|
-
'None': 'None',
|
|
85
|
-
},
|
|
86
|
-
};
|
|
87
|
-
// Valid accuracy values (used by guardrails) — includes Chinese aliases for cross-runtime compatibility
|
|
88
|
-
exports.VALID_ACCURACY_VALUES = new Set([
|
|
89
|
-
'Correct', '正确',
|
|
90
|
-
'Misjudged Pass', '误判通过',
|
|
91
|
-
'Misjudged Fail', '误判失败',
|
|
92
|
-
'Inconclusive', '无法判定',
|
|
93
|
-
]);
|
|
94
|
-
// Chinese → English accuracy mapping
|
|
95
|
-
exports.ACCURACY_CN_TO_EN = {
|
|
96
|
-
'正确': 'Correct',
|
|
97
|
-
'误判通过': 'Misjudged Pass',
|
|
98
|
-
'误判失败': 'Misjudged Fail',
|
|
99
|
-
'无法判定': 'Inconclusive',
|
|
100
|
-
};
|
|
101
|
-
// Valid top-level category labels (used by guardrails)
|
|
102
|
-
exports.VALID_CATEGORY_LABELS = new Set([
|
|
103
|
-
'Application Issue',
|
|
104
|
-
'Agent Issue',
|
|
105
|
-
'Test Case Issue',
|
|
106
|
-
'Environment Issue',
|
|
107
|
-
'No Issue',
|
|
108
|
-
]);
|
|
109
|
-
// All second-level root cause names (for cross-category lookups)
|
|
110
|
-
const _ALL_SUB_CATEGORY_NAMES = new Set();
|
|
111
|
-
for (const subs of Object.values(exports.ROOT_CAUSE_SUB_CATEGORIES)) {
|
|
112
|
-
for (const subName of Object.values(subs)) {
|
|
113
|
-
_ALL_SUB_CATEGORY_NAMES.add(subName);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
// Compound name lookup index ("Application Issue-Functional Exception" -> "Functional Exception")
|
|
117
|
-
const _COMPOUND_NAME_INDEX = {};
|
|
118
|
-
for (const [catLabel, subs] of Object.entries(exports.ROOT_CAUSE_SUB_CATEGORIES)) {
|
|
119
|
-
for (const subName of Object.keys(subs)) {
|
|
120
|
-
_COMPOUND_NAME_INDEX[`${catLabel}-${subName}`] = subName;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
// Resolve a sub-category text to a canonical name.
|
|
124
|
-
// Supports: direct name lookup, compound name, cross-category name, fuzzy match.
|
|
125
|
-
function resolveSubCategory(subText, catLabel) {
|
|
126
|
-
if (!subText)
|
|
127
|
-
return '';
|
|
128
|
-
const trimmed = subText.trim();
|
|
129
|
-
if (!trimmed)
|
|
130
|
-
return '';
|
|
131
|
-
const subs = exports.ROOT_CAUSE_SUB_CATEGORIES[catLabel] ?? {};
|
|
132
|
-
// 1. Direct name lookup
|
|
133
|
-
if (trimmed in subs) {
|
|
134
|
-
return subs[trimmed];
|
|
135
|
-
}
|
|
136
|
-
// 2. Compound name lookup
|
|
137
|
-
if (trimmed in _COMPOUND_NAME_INDEX) {
|
|
138
|
-
return _COMPOUND_NAME_INDEX[trimmed];
|
|
139
|
-
}
|
|
140
|
-
// 3. Cross-category name lookup
|
|
141
|
-
if (_ALL_SUB_CATEGORY_NAMES.has(trimmed)) {
|
|
142
|
-
return trimmed;
|
|
143
|
-
}
|
|
144
|
-
// 4. Fuzzy match: text contains a sub-category name
|
|
145
|
-
for (const subName of Object.keys(subs)) {
|
|
146
|
-
if (trimmed.includes(subName)) {
|
|
147
|
-
return subName;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
// 5. Fallback: unrecognised, return original text
|
|
151
|
-
return trimmed;
|
|
152
|
-
}
|
|
153
|
-
function createAnalyzerContext(reportData, config) {
|
|
154
|
-
return {
|
|
155
|
-
reportData,
|
|
156
|
-
screenshotCalls: [],
|
|
157
|
-
config: config ?? null,
|
|
158
|
-
pendingImages: [],
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
function createRootCauseResult(overrides = {}) {
|
|
162
|
-
return {
|
|
163
|
-
rootCauseCategory: '',
|
|
164
|
-
rootCauseSubCategory: '',
|
|
165
|
-
rootCauseReason: '',
|
|
166
|
-
confidence: 0.0,
|
|
167
|
-
accuracy: '',
|
|
168
|
-
evidence: [],
|
|
169
|
-
checkpoints: [],
|
|
170
|
-
summary: '',
|
|
171
|
-
taskIntent: '',
|
|
172
|
-
improvementSuggestions: [],
|
|
173
|
-
reverseVerification: '',
|
|
174
|
-
problems: [],
|
|
175
|
-
...overrides,
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
// === Legacy-compatible types (kept for AnalyzerOutput external interface) ===
|
|
179
|
-
// Root cause classification block inside AnalyzerOutput.
|
|
180
|
-
class RootCauseClassification {
|
|
181
|
-
category;
|
|
182
|
-
subCategory;
|
|
183
|
-
reason;
|
|
184
|
-
confidence;
|
|
185
|
-
evidence;
|
|
186
|
-
accuracy;
|
|
187
|
-
constructor(opts) {
|
|
188
|
-
this.category = opts.category;
|
|
189
|
-
this.subCategory = opts.subCategory;
|
|
190
|
-
this.reason = opts.reason;
|
|
191
|
-
this.confidence = opts.confidence;
|
|
192
|
-
this.evidence = opts.evidence ?? [];
|
|
193
|
-
this.accuracy = opts.accuracy ?? '';
|
|
194
|
-
}
|
|
195
|
-
toDict() {
|
|
196
|
-
const catLabel = this.category; // enum value is the English label
|
|
197
|
-
const subName = resolveSubCategory(this.subCategory, catLabel);
|
|
198
|
-
return {
|
|
199
|
-
category: catLabel,
|
|
200
|
-
sub_category: subName,
|
|
201
|
-
reason: this.reason,
|
|
202
|
-
confidence: this.confidence,
|
|
203
|
-
evidence: this.evidence,
|
|
204
|
-
accuracy: this.accuracy,
|
|
205
|
-
};
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
exports.RootCauseClassification = RootCauseClassification;
|
|
209
|
-
// External-facing analysis output. Consumed by ReportWriter.
|
|
210
|
-
class AnalyzerOutput {
|
|
211
|
-
taskDescription;
|
|
212
|
-
taskIntent;
|
|
213
|
-
taskResultStatus;
|
|
214
|
-
rootCause;
|
|
215
|
-
summary;
|
|
216
|
-
improvementSuggestions;
|
|
217
|
-
reverseVerification;
|
|
218
|
-
analysisTime;
|
|
219
|
-
modelUsed;
|
|
220
|
-
analysisDurationSeconds;
|
|
221
|
-
// Field name kept as totalLlmCalls for external interface compatibility,
|
|
222
|
-
// but actually records retry attempts rather than per-turn LLM call count.
|
|
223
|
-
totalLlmCalls;
|
|
224
|
-
accuracy;
|
|
225
|
-
checkpoints;
|
|
226
|
-
problems;
|
|
227
|
-
evidenceCompleteness;
|
|
228
|
-
consistencyNotes;
|
|
229
|
-
trace;
|
|
230
|
-
// Screenshot comparison data (for HTML rendering, not written to JSON)
|
|
231
|
-
screenshotData;
|
|
232
|
-
constructor(opts) {
|
|
233
|
-
this.taskDescription = opts.taskDescription;
|
|
234
|
-
this.taskIntent = opts.taskIntent;
|
|
235
|
-
this.taskResultStatus = opts.taskResultStatus;
|
|
236
|
-
this.rootCause = opts.rootCause ?? null;
|
|
237
|
-
this.summary = opts.summary ?? '';
|
|
238
|
-
this.improvementSuggestions = opts.improvementSuggestions ?? [];
|
|
239
|
-
this.reverseVerification = opts.reverseVerification ?? '';
|
|
240
|
-
this.analysisTime = opts.analysisTime ?? '';
|
|
241
|
-
this.modelUsed = opts.modelUsed ?? '';
|
|
242
|
-
this.analysisDurationSeconds = opts.analysisDurationSeconds ?? 0.0;
|
|
243
|
-
this.totalLlmCalls = opts.totalLlmCalls ?? 0;
|
|
244
|
-
this.accuracy = opts.accuracy ?? '';
|
|
245
|
-
this.checkpoints = opts.checkpoints ?? [];
|
|
246
|
-
this.problems = opts.problems ?? [];
|
|
247
|
-
this.evidenceCompleteness = opts.evidenceCompleteness ?? {};
|
|
248
|
-
this.consistencyNotes = opts.consistencyNotes ?? [];
|
|
249
|
-
this.trace = opts.trace ?? [];
|
|
250
|
-
this.screenshotData = opts.screenshotData ?? [];
|
|
251
|
-
}
|
|
252
|
-
toDict() {
|
|
253
|
-
return {
|
|
254
|
-
task_description: this.taskDescription,
|
|
255
|
-
task_intent: this.taskIntent,
|
|
256
|
-
task_result_status: this.taskResultStatus,
|
|
257
|
-
root_cause: this.rootCause ? this.rootCause.toDict() : null,
|
|
258
|
-
summary: this.summary,
|
|
259
|
-
improvement_suggestions: this.improvementSuggestions,
|
|
260
|
-
reverse_verification: this.reverseVerification,
|
|
261
|
-
analysis_time: this.analysisTime,
|
|
262
|
-
model_used: this.modelUsed,
|
|
263
|
-
analysis_duration_seconds: this.analysisDurationSeconds,
|
|
264
|
-
total_llm_calls: this.totalLlmCalls,
|
|
265
|
-
accuracy: this.accuracy,
|
|
266
|
-
checkpoints: this.checkpoints,
|
|
267
|
-
problems: this.problems,
|
|
268
|
-
evidence_completeness: this.evidenceCompleteness,
|
|
269
|
-
consistency_notes: this.consistencyNotes,
|
|
270
|
-
trace: this.trace,
|
|
271
|
-
};
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
exports.AnalyzerOutput = AnalyzerOutput;
|
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* RewriteAgent — 测试用例改写 Agent — 移植自 python rewrite_agent/agent.py
|
|
4
|
-
*
|
|
5
|
-
* 二元门决策 + LLM 自决子动作:
|
|
6
|
-
* 1. decideAction 做二元门判定(NO_REWRITE / REWRITE)
|
|
7
|
-
* 2. NO_REWRITE 直接返回(不调 LLM)——保守终止安全门
|
|
8
|
-
* 3. REWRITE → runAgentWithRetry(max 3):LLMCaller.call → parseRewriteResult →
|
|
9
|
-
* validateRewriteOutput;guardrail 触发带原因重跑;重试超限降级 NO_REWRITE
|
|
10
|
-
*
|
|
11
|
-
* 仿 Node.js ReportAnalyzerAgent 的 LLM 调用模式(LLMCaller.call,无 tools 纯文本输出)。
|
|
12
|
-
*/
|
|
13
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
14
|
-
if (k2 === undefined) k2 = k;
|
|
15
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
16
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
17
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
18
|
-
}
|
|
19
|
-
Object.defineProperty(o, k2, desc);
|
|
20
|
-
}) : (function(o, m, k, k2) {
|
|
21
|
-
if (k2 === undefined) k2 = k;
|
|
22
|
-
o[k2] = m[k];
|
|
23
|
-
}));
|
|
24
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
25
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
26
|
-
}) : function(o, v) {
|
|
27
|
-
o["default"] = v;
|
|
28
|
-
});
|
|
29
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
30
|
-
var ownKeys = function(o) {
|
|
31
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
32
|
-
var ar = [];
|
|
33
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
34
|
-
return ar;
|
|
35
|
-
};
|
|
36
|
-
return ownKeys(o);
|
|
37
|
-
};
|
|
38
|
-
return function (mod) {
|
|
39
|
-
if (mod && mod.__esModule) return mod;
|
|
40
|
-
var result = {};
|
|
41
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
42
|
-
__setModuleDefault(result, mod);
|
|
43
|
-
return result;
|
|
44
|
-
};
|
|
45
|
-
})();
|
|
46
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
47
|
-
exports.RewriteAgent = void 0;
|
|
48
|
-
exports.summarizeAnalyzerOutput = summarizeAnalyzerOutput;
|
|
49
|
-
const path = __importStar(require("path"));
|
|
50
|
-
const fs = __importStar(require("fs"));
|
|
51
|
-
const model_1 = require("../../../common/model");
|
|
52
|
-
const logger_1 = require("../../../common/logger");
|
|
53
|
-
const mapping_1 = require("./mapping");
|
|
54
|
-
const parse_1 = require("./parse");
|
|
55
|
-
const guardrails_1 = require("./guardrails");
|
|
56
|
-
const types_1 = require("./types");
|
|
57
|
-
const MAX_RETRIES = 3;
|
|
58
|
-
const REWRITER_PROMPT_PATH = path.join(__dirname, 'prompts', 'rewriter_v1.0.md');
|
|
59
|
-
/** 裁剪 AnalyzerOutput 为 summary dict(移植自 python _summarize_analyzer_output)。
|
|
60
|
-
* 只含关键字段,喂给 rewriter 与写入 loop_result.json。不喂 trace/screenshot 等。
|
|
61
|
-
* 字段集与 python 对齐(snake_case),category 为 Node.js 分析器的英文标签。 */
|
|
62
|
-
function summarizeAnalyzerOutput(output) {
|
|
63
|
-
const rc = output.rootCause;
|
|
64
|
-
return {
|
|
65
|
-
task_result_status: (output.taskResultStatus ?? '').toUpperCase(),
|
|
66
|
-
root_cause: rc
|
|
67
|
-
? {
|
|
68
|
-
category: rc.category ?? '',
|
|
69
|
-
sub_category: rc.subCategory ?? '',
|
|
70
|
-
reason: (rc.reason ?? '').slice(0, 500),
|
|
71
|
-
evidence: (rc.evidence ?? []).slice(0, 5),
|
|
72
|
-
}
|
|
73
|
-
: null,
|
|
74
|
-
analysis_summary: (output.summary ?? '').slice(0, 500),
|
|
75
|
-
improvement_suggestions: (output.improvementSuggestions ?? []).slice(0, 8),
|
|
76
|
-
reverse_verification: (output.reverseVerification ?? '').slice(0, 500),
|
|
77
|
-
problems: (output.problems ?? []).slice(0, 5),
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
class RewriteAgent {
|
|
81
|
-
config;
|
|
82
|
-
constructor(config) {
|
|
83
|
-
this.config = config;
|
|
84
|
-
}
|
|
85
|
-
async run(input) {
|
|
86
|
-
logger_1.logger.info(`[RewriteAgent] 开始改写: iteration=${input.iteration}, ` +
|
|
87
|
-
`original_task='${input.originalTask.slice(0, 50)}...'`);
|
|
88
|
-
const summary = input.analyzerOutputSummary ?? {};
|
|
89
|
-
const rootCause = summary['root_cause'] ?? null;
|
|
90
|
-
const rootCauseCategory = rootCause ? rootCause['category'] : null;
|
|
91
|
-
const subCategory = rootCause ? rootCause['sub_category'] : null;
|
|
92
|
-
const decision = (0, mapping_1.decideAction)(rootCauseCategory, subCategory);
|
|
93
|
-
logger_1.logger.info(`[RewriteAgent] decideAction: category=${rootCauseCategory}, sub=${subCategory} → decision=${decision}`);
|
|
94
|
-
if (decision === types_1.RewriteDecision.NO_REWRITE) {
|
|
95
|
-
logger_1.logger.info('[RewriteAgent] NO_REWRITE(二元门),跳过 LLM 调用');
|
|
96
|
-
return {
|
|
97
|
-
action: types_1.RewriteAction.NO_REWRITE,
|
|
98
|
-
rewrittenTask: null,
|
|
99
|
-
knowledgeText: '',
|
|
100
|
-
rewriteReason: `根因 ${rootCauseCategory} 无需改写(二元门)`,
|
|
101
|
-
confidence: 1.0,
|
|
102
|
-
rawLlmOutput: '',
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
return this.runAgentWithRetry(input, MAX_RETRIES);
|
|
106
|
-
}
|
|
107
|
-
async runAgentWithRetry(input, maxRetries) {
|
|
108
|
-
const llmCaller = new model_1.LLMCaller();
|
|
109
|
-
// 加载 rewriter prompt
|
|
110
|
-
let basePrompt;
|
|
111
|
-
try {
|
|
112
|
-
basePrompt = fs.readFileSync(REWRITER_PROMPT_PATH, 'utf-8');
|
|
113
|
-
}
|
|
114
|
-
catch {
|
|
115
|
-
logger_1.logger.warn(`Rewriter prompt 文件不存在: ${REWRITER_PROMPT_PATH}`);
|
|
116
|
-
basePrompt = '请根据归因结果改写测试用例。';
|
|
117
|
-
}
|
|
118
|
-
const retryReasons = [];
|
|
119
|
-
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
120
|
-
logger_1.logger.info(`[RewriteAgent] 尝试 ${attempt + 1}/${maxRetries}`);
|
|
121
|
-
const systemPrompt = this.buildPrompt(input, basePrompt, retryReasons);
|
|
122
|
-
const userPrompt = '请根据归因结果,按最小改动原则产出改写内容(改写后的任务和/或知识库文本,不适用填 N/A)。';
|
|
123
|
-
try {
|
|
124
|
-
const llmResult = await llmCaller.call({
|
|
125
|
-
systemPrompt,
|
|
126
|
-
userPrompt,
|
|
127
|
-
modelConfig: this.config,
|
|
128
|
-
});
|
|
129
|
-
const finalText = llmResult.text ?? '';
|
|
130
|
-
if (!finalText.trim()) {
|
|
131
|
-
retryReasons.push('LLM 输出为空或非文本');
|
|
132
|
-
logger_1.logger.warn('[RewriteAgent] LLM 输出为空,重试');
|
|
133
|
-
continue;
|
|
134
|
-
}
|
|
135
|
-
const parsed = (0, parse_1.parseRewriteResult)(finalText);
|
|
136
|
-
if (parsed === null) {
|
|
137
|
-
retryReasons.push(`解析失败(Markdown 格式无效,LLM 输出前200字: ${finalText.slice(0, 200)})`);
|
|
138
|
-
logger_1.logger.warn('[RewriteAgent] 解析失败(Markdown),重试');
|
|
139
|
-
continue;
|
|
140
|
-
}
|
|
141
|
-
logger_1.logger.info(`[RewriteAgent] 解析成功: action=${parsed.action}, ` +
|
|
142
|
-
`rewritten_task=${parsed.rewrittenTask ? 'yes' : 'no'}, ` +
|
|
143
|
-
`knowledge_text_len=${parsed.knowledgeText?.length ?? 0}`);
|
|
144
|
-
const guard = (0, guardrails_1.validateRewriteOutput)(parsed, input.originalTask);
|
|
145
|
-
if (guard.tripwireTriggered) {
|
|
146
|
-
const reason = guard.outputInfo.reason ?? 'guardrail 触发';
|
|
147
|
-
retryReasons.push(reason);
|
|
148
|
-
logger_1.logger.warn(`[RewriteAgent] guardrail tripwire: ${reason}`);
|
|
149
|
-
continue;
|
|
150
|
-
}
|
|
151
|
-
logger_1.logger.info(`[RewriteAgent] 改写成功: attempt=${attempt + 1}`);
|
|
152
|
-
return parsed;
|
|
153
|
-
}
|
|
154
|
-
catch (e) {
|
|
155
|
-
const errMsg = e instanceof Error ? e.message : String(e);
|
|
156
|
-
retryReasons.push(`异常: ${errMsg.slice(0, 200)}`);
|
|
157
|
-
logger_1.logger.warn(`[RewriteAgent] Exception: ${errMsg.slice(0, 200)}`);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
const allReasons = retryReasons.join('; ');
|
|
161
|
-
logger_1.logger.error(`[RewriteAgent] ${maxRetries}次重试均失败: ${allReasons}`);
|
|
162
|
-
return {
|
|
163
|
-
action: types_1.RewriteAction.NO_REWRITE,
|
|
164
|
-
rewrittenTask: null,
|
|
165
|
-
knowledgeText: '',
|
|
166
|
-
rewriteReason: `error: ${maxRetries} 次重试均失败: ${allReasons}`,
|
|
167
|
-
confidence: 0.0,
|
|
168
|
-
rawLlmOutput: '',
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
/** 构建 Agent instructions(填充占位符 + 重试 hint)。移植自 python _build_prompt。 */
|
|
172
|
-
buildPrompt(input, basePrompt, retryReasons) {
|
|
173
|
-
const summary = input.analyzerOutputSummary ?? {};
|
|
174
|
-
const rootCause = summary['root_cause'] ?? null;
|
|
175
|
-
const taskResultStatus = String(summary['task_result_status'] ?? '');
|
|
176
|
-
const category = rootCause ? String(rootCause['category'] ?? '') : '';
|
|
177
|
-
const subCategory = rootCause ? String(rootCause['sub_category'] ?? '') : '';
|
|
178
|
-
const reason = rootCause ? String(rootCause['reason'] ?? '') : '';
|
|
179
|
-
const evidence = (rootCause ? rootCause['evidence'] : []) ?? [];
|
|
180
|
-
const improvementSuggestions = summary['improvement_suggestions'] ?? [];
|
|
181
|
-
const reverseVerification = String(summary['reverse_verification'] ?? '');
|
|
182
|
-
const analysisSummary = String(summary['analysis_summary'] ?? '');
|
|
183
|
-
const problems = summary['problems'] ?? [];
|
|
184
|
-
const evidenceText = evidence.length
|
|
185
|
-
? evidence.map((e) => `- ${e}`).join('\n')
|
|
186
|
-
: '(无)';
|
|
187
|
-
const suggestionsText = improvementSuggestions.length
|
|
188
|
-
? improvementSuggestions.map((s, i) => `${i + 1}. ${s}`).join('\n')
|
|
189
|
-
: '(无)';
|
|
190
|
-
const problemsText = problems.length ? problems.map((p) => `- ${p}`).join('\n') : '(无)';
|
|
191
|
-
let prompt = basePrompt;
|
|
192
|
-
prompt = prompt.replace('{original_task}', input.originalTask);
|
|
193
|
-
prompt = prompt.replace('{iteration}', String(input.iteration));
|
|
194
|
-
prompt = prompt.replace('{task_result_status}', taskResultStatus);
|
|
195
|
-
prompt = prompt.replace('{root_cause_category}', category);
|
|
196
|
-
prompt = prompt.replace('{root_cause_sub_category}', subCategory);
|
|
197
|
-
prompt = prompt.replace('{root_cause_reason}', reason);
|
|
198
|
-
prompt = prompt.replace('{root_cause_evidence}', evidenceText);
|
|
199
|
-
prompt = prompt.replace('{improvement_suggestions}', suggestionsText);
|
|
200
|
-
prompt = prompt.replace('{reverse_verification}', reverseVerification);
|
|
201
|
-
prompt = prompt.replace('{analysis_summary}', analysisSummary);
|
|
202
|
-
prompt = prompt.replace('{problems}', problemsText);
|
|
203
|
-
if (retryReasons.length > 0) {
|
|
204
|
-
prompt += `\n\n**上次改写被拒绝**:${retryReasons.join('; ')},请修正。`;
|
|
205
|
-
}
|
|
206
|
-
return prompt;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
exports.RewriteAgent = RewriteAgent;
|