utils.ts
2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Utility functions for Launch Agent.
*/
import type { LaunchAgentResult } from './types';
import { logger } from '../../utils/logger';
/**
* Extract launch result from agent response.
* @param response - Agent response text (with TaskCompletion tags already stripped by evoltagent)
* @returns Parsed LaunchAgentResult object
*/
export function parseLaunchResult(response: string): Promise<LaunchAgentResult> {
// Check for empty response
if (!response || response.trim().length === 0) {
logger.printInfoLog('启动智能体返回空响应');
return Promise.resolve({
success: false,
error: 'Agent returned empty response',
});
}
// The evoltagent library strips <TaskCompletion> tags before calling postProcessor.
// Be tolerant: the model may emit ```json, ```JSON, a bare ``` fence, or even a
// bare {…} object. We try several extraction strategies before giving up so a
// minor formatting variance (or a trailing comma) does not abort the whole run.
const candidates: string[] = [];
const jsonFence = response.match(/```json\s*\n?([\s\S]*?)```/i);
if (jsonFence) candidates.push(jsonFence[1]);
const anyFence = response.match(/```\s*\n?([\s\S]*?)```/);
if (anyFence) candidates.push(anyFence[1]);
const braceMatch = response.match(/\{[\s\S]*\}/);
if (braceMatch) candidates.push(braceMatch[0]);
for (const raw of candidates) {
const jsonStr = (raw ?? '').trim();
if (!jsonStr) continue;
// Tolerate trailing commas before parsing
const normalized = jsonStr.replace(/,(\s*[}\]])/g, '$1');
try {
const parsed = JSON.parse(normalized) as LaunchAgentResult;
if (!parsed || typeof parsed !== 'object') continue;
// A usable result must signal success explicitly OR carry the server fields.
const hasServerFields = !!(parsed.serverKey && parsed.url && parsed.port);
if (parsed.success === true && !hasServerFields) {
continue; // incomplete success payload, try next candidate
}
if (parsed.success === undefined && !hasServerFields) {
continue; // not a real launch result, try next candidate
}
return Promise.resolve(parsed);
} catch {
// Try next candidate
}
}
logger.printInfoLog('启动智能体响应缺少 JSON 块');
return Promise.resolve({
success: false,
error: 'No JSON code block found in agent response',
});
}