/**
 * Agent Remove Tool
 *
 * One-command removal of a worker agent: kills process, deletes workspace,
 * removes from registry. Replaces the 8-step manual cleanup process.
 */
import { log } from '../utils/logger.js';
import { AgentRegistryManager } from '../core/agent-registry.js';
import { existsSync, rmSync } from 'fs';
export const agentRemoveTool = {
    name: 'agent_remove',
    label: 'Remove Agent',
    description: 'Fully remove a worker agent: kill process, delete workspace, remove from registry',
    parameters: {
        type: 'object',
        properties: {
            name: {
                type: 'string',
                description: 'Name of the agent to remove',
            },
            force: {
                type: 'boolean',
                description: 'Force removal even if the agent appears to be running',
                default: false,
            },
        },
        required: ['name'],
    },
    async execute(_toolCallId, params) {
        const name = params.name;
        const force = params.force || false;
        try {
            const registry = new AgentRegistryManager();
            const agent = registry.getAgentByName(name);
            if (!agent) {
                return {
                    content: [{ type: 'text', text: `Agent "${name}" not found in registry.` }],
                    details: { error: 'not_found' },
                    isError: true,
                };
            }
            // Don't remove self (master) unless forced
            if (agent.type === 'self' && !force) {
                return {
                    content: [{ type: 'text', text: `Cannot remove the active master "${name}". Use --force to override.` }],
                    details: { error: 'is_master' },
                    isError: true,
                };
            }
            const steps = [];
            // 1. Kill process if running
            if (agent.pid) {
                try {
                    process.kill(agent.pid, 0); // Check if alive
                    if (!force && agent.status !== 'offline') {
                        return {
                            content: [{ type: 'text', text: `Agent "${name}" (PID ${agent.pid}) is still running. Use --force to kill and remove.` }],
                            details: { error: 'still_running', pid: agent.pid },
                            isError: true,
                        };
                    }
                    process.kill(agent.pid, 'SIGTERM');
                    // Give it a moment to die
                    await new Promise(r => setTimeout(r, 500));
                    try {
                        process.kill(agent.pid, 'SIGKILL');
                    }
                    catch { }
                    steps.push(`Killed process (PID ${agent.pid})`);
                }
                catch {
                    steps.push(`Process not running (PID ${agent.pid} already dead)`);
                }
            }
            // 2. Remove workspace directory
            const workspace = agent.workspace || registry.getAgentWorkspace(agent.id);
            if (workspace && existsSync(workspace)) {
                try {
                    rmSync(workspace, { recursive: true, force: true });
                    steps.push(`Deleted workspace: ${workspace}`);
                }
                catch (err) {
                    steps.push(`Failed to delete workspace: ${err instanceof Error ? err.message : String(err)}`);
                }
            }
            else {
                steps.push('No workspace directory found');
            }
            // 3. Remove tasks associated with this agent
            const tasks = registry.getAgentTasks(agent.id);
            for (const task of tasks) {
                registry.removeTask(task.id);
            }
            if (tasks.length > 0) {
                steps.push(`Removed ${tasks.length} task(s)`);
            }
            // 4. Remove from registry
            registry.removeAgent(agent.id);
            registry.save();
            steps.push('Removed from registry');
            return {
                content: [{
                        type: 'text',
                        text: `Removed agent "${name}" (${agent.id}):\n${steps.map(s => `  - ${s}`).join('\n')}`,
                    }],
                details: {
                    agent_id: agent.id,
                    agent_name: name,
                    steps,
                },
            };
        }
        catch (error) {
            log.error('Failed to remove agent:', error);
            return {
                content: [{ type: 'text', text: `Failed to remove agent: ${error instanceof Error ? error.message : String(error)}` }],
                details: { error: error instanceof Error ? error.message : String(error) },
                isError: true,
            };
        }
    },
};
//# sourceMappingURL=agentRemove.js.map