/**
 * Agent List Tool
 *
 * List registered agents.
 */
import { AgentRegistryManager } from '../core/agent-registry.js';
import { checkAgentHealth } from '../utils/agent-utils.js';
export const agentListTool = {
    name: 'agent_list',
    label: 'List Agents',
    description: 'List all registered agents',
    parameters: {
        type: 'object',
        properties: {
            show_tasks: {
                type: 'boolean',
                description: 'Show recent tasks for each agent',
                default: false,
            },
            max_tasks: {
                type: 'number',
                description: 'Maximum tasks to show per agent',
                default: 5,
            },
            include_offline: {
                type: 'boolean',
                description: 'Include offline historical workers in the listing',
                default: false,
            },
            max_agents: {
                type: 'number',
                description: 'Maximum agents to show',
                default: 20,
            },
            check_health: {
                type: 'boolean',
                description: 'Check agent health status',
                default: true,
            },
        },
        required: [],
    },
    async execute(toolCallId, params, signal, onUpdate, context) {
        const showTasks = params.show_tasks || false;
        const maxTasks = params.max_tasks || 5;
        const includeOffline = params.include_offline === true;
        const maxAgents = typeof params.max_agents === 'number' && params.max_agents > 0 ? params.max_agents : 20;
        try {
            const registry = new AgentRegistryManager();
            const allAgents = registry.getAgents();
            if (allAgents.length === 0) {
                return {
                    content: [{
                            type: 'text',
                            text: 'No agents registered.\n\nUse agent_serve to make this instance a networked agent.\nUse agent_spawn_local to spawn worker agents.',
                        }],
                    details: { agent_count: 0 },
                };
            }
            for (const agent of allAgents) {
                if (params.check_health !== false && agent.endpoint) {
                    const healthy = await checkAgentHealth(agent.endpoint, 2000);
                    if (!healthy && agent.status !== 'offline') {
                        agent.status = 'offline';
                        agent.lastHeartbeat = Date.now();
                        registry.upsertAgent(agent);
                    }
                }
            }
            const reconciledAgents = registry.getAgents();
            const sortedAgents = reconciledAgents
                .filter(agent => includeOffline || agent.status !== 'offline')
                .sort((a, b) => {
                const statusRank = (a.status === 'offline' ? 1 : 0) - (b.status === 'offline' ? 1 : 0);
                if (statusRank !== 0)
                    return statusRank;
                const heartbeatA = a.lastHeartbeat || a.created || 0;
                const heartbeatB = b.lastHeartbeat || b.created || 0;
                return heartbeatB - heartbeatA;
            });
            const agents = sortedAgents.slice(0, maxAgents);
            let output = `## Registered Agents (${agents.length}${agents.length !== reconciledAgents.length ? ` of ${reconciledAgents.length}` : ''})\n\n`;
            for (const agent of agents) {
                const effectiveStatus = agent.status;
                output += `### ${agent.name} (${agent.type})\n`;
                output += `- **ID**: ${agent.id}\n`;
                output += `- **Status**: ${effectiveStatus}\n`;
                if (agent.endpoint) {
                    output += `- **Endpoint**: ${agent.endpoint}\n`;
                }
                output += `- **Workspace**: ${agent.workspace}\n`;
                output += `- **Auto-start**: ${agent.autoStart === false ? 'disabled' : 'enabled'}\n`;
                output += `- **Created**: ${new Date(agent.created).toLocaleString()}\n`;
                if (agent.lastHeartbeat) {
                    const age = Date.now() - agent.lastHeartbeat;
                    output += `- **Last heartbeat**: ${Math.floor(age / 1000)}s ago\n`;
                }
                if (agent.capabilities.length > 0) {
                    output += `- **Capabilities**: ${agent.capabilities.join(', ')}\n`;
                }
                else {
                    output += `- **Capabilities**: all\n`;
                }
                if (agent.platform) {
                    output += `- **Platform**: ${agent.platform}\n`;
                }
                if (agent.platformCapabilities?.search) {
                    const search = agent.platformCapabilities.search;
                    output += `- **Search**: ${search.recommendedTool} (grep: ${search.hasGrep ? '✓' : '✗'}, rg: ${search.hasRipgrep ? '✓' : '✗'})\n`;
                }
                if (agent.persona?.loaded) {
                    output += `- **Persona**: ${agent.persona.name} (${agent.persona.role})\n`;
                }
                if (showTasks) {
                    const tasks = registry.getAgentTasks(agent.id);
                    const recentTasks = tasks
                        .sort((a, b) => b.created - a.created)
                        .slice(0, maxTasks);
                    if (recentTasks.length > 0) {
                        output += `- **Recent tasks**:\n`;
                        for (const task of recentTasks) {
                            const age = Date.now() - task.created;
                            output += `  • ${task.id.substring(0, 8)}: ${task.payload.tool} (${task.status}, ${Math.floor(age / 1000)}s ago)\n`;
                        }
                    }
                }
                output += '\n';
            }
            registry.markOfflineAgents();
            registry.cleanupOldTasks();
            registry.save();
            // Add registry info
            const tasks = registry.getTasks();
            const pending = tasks.filter(t => t.status === 'pending' || t.status === 'running').length;
            const completed = tasks.filter(t => t.status === 'completed').length;
            const failed = tasks.filter(t => t.status === 'failed' || t.status === 'cancelled').length;
            output += `## Registry Summary\n`;
            output += `- **Shown agents**: ${agents.length}\n`;
            output += `- **Total agents**: ${reconciledAgents.length}\n`;
            output += `- **Total tasks**: ${tasks.length}\n`;
            output += `- **Pending/running**: ${pending}\n`;
            output += `- **Completed**: ${completed}\n`;
            output += `- **Failed/cancelled**: ${failed}\n`;
            output += `- **Registry path**: ${registry.getRegistryPath()}\n`;
            return {
                content: [{ type: 'text', text: output }],
                details: {
                    agent_count: agents.length,
                    task_count: tasks.length,
                    agents: agents.map(a => ({
                        id: a.id,
                        name: a.name,
                        type: a.type,
                        status: a.status,
                        endpoint: a.endpoint,
                    })),
                },
            };
        }
        catch (error) {
            return {
                content: [{
                        type: 'text',
                        text: `❌ Failed to list agents: ${error instanceof Error ? error.message : String(error)}`,
                    }],
                details: { error: error instanceof Error ? error.message : String(error) },
                isError: true,
            };
        }
    },
};
//# sourceMappingURL=agentList.js.map