utils.ts 2.54 KB
/**
 * 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',
    });
}