"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var ManageSubAgentsHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageSubAgentsHandler = void 0;
const common_1 = require("@nestjs/common");
const sub_agents_service_1 = require("../../sub-agents/sub-agents.service");
let ManageSubAgentsHandler = ManageSubAgentsHandler_1 = class ManageSubAgentsHandler {
    constructor(subAgentsService) {
        this.subAgentsService = subAgentsService;
        this.toolName = 'manage_sub_agents';
        this.logger = new common_1.Logger(ManageSubAgentsHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg sub-agents — specialized agent configurations with their own system prompt, context templates, and enabled tools.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|get|create|update|delete|duplicate',
                    required: true,
                },
                {
                    name: 'id',
                    type: 'string',
                    description: 'UUID of the sub-agent (required for get/update/delete/duplicate)',
                    required: false,
                },
                {
                    name: 'data',
                    type: 'object',
                    description: 'Fields for create/update. Keys: name (required), description, system_prompt_id, context_template_id, followup_context_template_id, enabled_tools (array|null|"all"), enabled_mcp_tools (array|"all"|null), is_active, model_id.',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_sub_agents

Manage RepoBurg sub-agents — specialized agent configurations with their own system prompt, context templates, and enabled tools. Sub-agents are used by the invoke_subagent tool to delegate specialized tasks.

### Actions:

- **list** — List all sub-agents (returns id, name, description, is_active, model_id, is_builtin)
- **get** — Get full details of a sub-agent by ID
- **create** — Create a new sub-agent. Provide \`data\` with: name (required), description, system_prompt_id, context_template_id, followup_context_template_id, enabled_tools (array of tool names, null for all), enabled_mcp_tools (array of serverName__toolName, "all", or null), is_active (default true), model_id
- **update** — Update a sub-agent. Provide \`id\` and \`data\` with fields to change. Built-in sub-agents can only change is_active and model_id.
- **delete** — Delete a sub-agent by ID
- **duplicate** — Duplicate a sub-agent by ID (works for built-in too). Returns the new copy.

### Parameters:
- **action** (required): Operation to perform
- **id** (optional): UUID of the sub-agent
- **data** (optional): Object with sub-agent fields

### Examples:

List all sub-agents:
\`\`\`typescript
tool: manage_sub_agents
args: { action: "list" }
\`\`\`

Create a sub-agent:
\`\`\`typescript
tool: manage_sub_agents
args: { action: "create", data: { name: "Bug Fixer", description: "Specialized in fixing bugs", enabled_tools: ["create_file", "overwrite_file", "delete_file", "request_context", "run_command"], model_id: "ollama/glm-5.1:cloud" } }
\`\`\`

Update a sub-agent's active status:
\`\`\`typescript
tool: manage_sub_agents
args: { action: "update", id: "uuid-here", data: { is_active: false } }
\`\`\``;
    }
    async execute(args, _context) {
        const { action } = args;
        try {
            let result;
            switch (action) {
                case 'list':
                    result = await this.handleList();
                    break;
                case 'get':
                    result = await this.handleGet(args.id);
                    break;
                case 'create':
                    result = await this.handleCreate(args.data);
                    break;
                case 'update':
                    result = await this.handleUpdate(args.id, args.data);
                    break;
                case 'delete':
                    result = await this.handleDelete(args.id);
                    break;
                case 'duplicate':
                    result = await this.handleDuplicate(args.id);
                    break;
                default:
                    result = {
                        status: 'FAILURE',
                        summary: `Unknown action "${action}". Valid actions: list, get, create, update, delete, duplicate`,
                        error_message: `Unknown action: ${action}`,
                        execution_log: {
                            output: '',
                            error_message: `Unknown action: ${action}`,
                        },
                    };
            }
            if (!result.persisted_args)
                result.persisted_args = {};
            if (!result.persisted_args.command_string)
                result.persisted_args.command_string = `${action}`;
            if (!result.persisted_args.reason)
                result.persisted_args.reason = result.summary || '';
            return result;
        }
        catch (error) {
            this.logger.error(`manage_sub_agents error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} sub-agent: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList() {
        const subAgents = await this.subAgentsService.findAll();
        const summary = subAgents.map((a) => ({
            id: a.id,
            name: a.name,
            description: a.description,
            is_active: a.is_active,
            model_id: a.model_id,
            is_builtin: a.is_builtin,
            builtin_key: a.builtin_key,
            system_prompt_id: a.system_prompt_id,
            context_template_id: a.context_template_id,
            followup_context_template_id: a.followup_context_template_id,
            enabled_tools: a.enabled_tools,
            enabled_mcp_tools: a.enabled_mcp_tools,
        }));
        return {
            status: 'SUCCESS',
            summary: `Found ${subAgents.length} sub-agent(s).`,
            execution_log: {
                output: JSON.stringify(summary, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleGet(id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for get action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const subAgent = await this.subAgentsService.findOne(id);
        return {
            status: 'SUCCESS',
            summary: `Sub-agent "${subAgent.name}"`,
            execution_log: {
                output: JSON.stringify(subAgent, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreate(data) {
        if (!data || !data.name) {
            return {
                status: 'FAILURE',
                summary: 'data.name is required for create',
                error_message: 'Missing required field: name',
                execution_log: {
                    output: '',
                    error_message: 'Missing required field: name',
                },
            };
        }
        const createDto = {
            name: data.name,
            description: data.description ?? null,
            system_prompt_id: data.system_prompt_id ?? null,
            context_template_id: data.context_template_id ?? null,
            followup_context_template_id: data.followup_context_template_id ?? null,
            enabled_tools: data.enabled_tools ?? null,
            enabled_mcp_tools: data.enabled_mcp_tools ?? null,
            is_active: data.is_active ?? true,
            model_id: data.model_id ?? null,
        };
        const subAgent = await this.subAgentsService.create(createDto);
        const result = {
            id: subAgent.id,
            name: subAgent.name,
            is_active: subAgent.is_active,
        };
        return {
            status: 'SUCCESS',
            summary: `Sub-agent "${subAgent.name}" created with ID ${subAgent.id}`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleUpdate(id, data) {
        if (!id || !data) {
            return {
                status: 'FAILURE',
                summary: 'id and data are required for update action',
                error_message: 'Missing parameters',
                execution_log: { output: '', error_message: 'Missing parameters' },
            };
        }
        const updateDto = {};
        const allowedFields = [
            'name',
            'description',
            'system_prompt_id',
            'context_template_id',
            'followup_context_template_id',
            'enabled_tools',
            'enabled_mcp_tools',
            'is_active',
            'model_id',
        ];
        for (const key of allowedFields) {
            if (data[key] !== undefined) {
                updateDto[key] = data[key];
            }
        }
        const subAgent = await this.subAgentsService.update(id, updateDto);
        return {
            status: 'SUCCESS',
            summary: `Sub-agent "${subAgent.name}" updated`,
            execution_log: {
                output: JSON.stringify({
                    id: subAgent.id,
                    name: subAgent.name,
                    is_active: subAgent.is_active,
                }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleDelete(id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for delete action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        await this.subAgentsService.remove(id);
        return {
            status: 'SUCCESS',
            summary: `Sub-agent ${id} deleted`,
            execution_log: {
                output: JSON.stringify({ deleted: true, id }),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleDuplicate(id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for duplicate action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const subAgent = await this.subAgentsService.duplicate(id);
        return {
            status: 'SUCCESS',
            summary: `Sub-agent duplicated as "${subAgent.name}"`,
            execution_log: {
                output: JSON.stringify({ id: subAgent.id, name: subAgent.name }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
};
exports.ManageSubAgentsHandler = ManageSubAgentsHandler;
exports.ManageSubAgentsHandler = ManageSubAgentsHandler = ManageSubAgentsHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [sub_agents_service_1.SubAgentsService])
], ManageSubAgentsHandler);
//# sourceMappingURL=manage-sub-agents.handler.js.map