// tools/orchestrate-runtime.ts — Handler for orchestrate_runtime MCP tool (SPEC-079 AC-10)
import { startOrchestration } from '../engine/orchestrator/index.js';
/**
 * Handle the orchestrate_runtime tool invocation.
 * Launches and coordinates agents with configurable topologies.
 */
export async function handleOrchestrateRuntime(input) {
    const config = {
        topology: input.topology,
        tasks: input.tasks,
        agents: input.agents,
        options: {
            maxRetries: input.maxRetries ?? 2,
            timeoutMs: input.timeoutMs ?? 600000,
            failFast: input.failFast ?? false,
            spawnMethod: input.spawnMethod ?? 'cli-subprocess',
            conflictStrategy: input.conflictStrategy ?? 'merge-auto',
            dryRun: input.dryRun ?? false,
        },
    };
    if (config.tasks.length === 0) {
        return {
            content: [{ type: 'text', text: 'Error: At least one task is required.' }],
            isError: true,
        };
    }
    const result = await startOrchestration(config);
    const summary = buildResultSummary(result, config.options.dryRun);
    return {
        content: [{ type: 'text', text: summary }],
    };
}
/**
 * Build a human-readable summary of the orchestration result.
 */
function buildResultSummary(result, isDryRun) {
    const lines = [
        isDryRun ? '## Orchestration Plan (Dry Run)' : '## Orchestration Result',
        '',
        `**Session**: ${result.sessionId}`,
        `**Duration**: ${String(result.duration)}ms`,
        `**Agents**: ${String(result.agents.length)}`,
        `**Tasks**: ${String(result.tasks.length)}`,
        '',
    ];
    // Task summary
    const completed = result.tasks.filter((t) => t.status === 'completed').length;
    const failed = result.tasks.filter((t) => t.status === 'failed').length;
    lines.push(`### Tasks: ${String(completed)} completed, ${String(failed)} failed`);
    lines.push('');
    for (const task of result.tasks) {
        lines.push(`- **${task.taskId}** (${task.agentId}): ${task.status} (${String(task.duration)}ms)`);
    }
    lines.push('');
    // Conflicts
    if (result.conflicts.length > 0) {
        lines.push(`### Conflicts: ${String(result.conflicts.length)}`);
        for (const conflict of result.conflicts) {
            const status = conflict.resolved ? 'resolved' : 'unresolved';
            lines.push(`- **${conflict.file}**: ${status} (${conflict.strategy})`);
        }
        lines.push('');
    }
    // Cost
    if (result.totalCost.tokens > 0) {
        lines.push('### Cost');
        lines.push(`- Tokens: ${String(result.totalCost.tokens)}`);
        lines.push(`- USD: $${result.totalCost.usd.toFixed(4)}`);
    }
    return lines.join('\n');
}
//# sourceMappingURL=orchestrate-runtime.js.map