"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 InvokeSubAgentHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvokeSubAgentHandler = void 0;
const common_1 = require("@nestjs/common");
const chat_service_1 = require("../../interactive-chat/chat.service");
let InvokeSubAgentHandler = InvokeSubAgentHandler_1 = class InvokeSubAgentHandler {
    constructor(chatService) {
        this.chatService = chatService;
        this.toolName = 'invoke_subagent';
        this.logger = new common_1.Logger(InvokeSubAgentHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Delegate a task to a specialized sub-agent. The sub-agent runs synchronously and returns its result directly.',
            arguments: [
                {
                    name: 'agent_name',
                    type: 'string',
                    description: 'The name of the sub-agent to invoke',
                    required: true,
                },
                {
                    name: 'prompt',
                    type: 'string',
                    description: 'The task or question to pass to the sub-agent',
                    required: true,
                },
                {
                    name: 'session_id',
                    type: 'string',
                    description: 'Optional existing session ID to reuse. If provided, the sub-agent continues in that session with its prior history.',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## invoke_subagent

Delegate a task to a specialized sub-agent. The sub-agent runs synchronously and returns its result directly.

### Behavior:
- The sub-agent runs inline — this tool call blocks until the sub-agent completes.
- The sub-agent has its own system prompt, enabled tools, and LLM loop.
- Results are returned directly as the tool response — no follow-up needed.
- **Parallel invocation:** You can invoke multiple sub-agents in the same tool call block to run them in parallel. Use this when tasks are independent of each other.
- **Follow-up:** Each invocation returns a \`[Session ID: ...]\` in the output. Pass this as the \`session_id\` parameter on a subsequent call to continue that sub-agent's session with its prior history.

### Parameters:
- **agent_name** (required): The name of the sub-agent to invoke (e.g., "explore-codebase")
- **prompt** (required): The task or question to pass to the sub-agent
- **session_id** (optional): An existing session ID to reuse. If provided, the sub-agent continues in that session with its prior history instead of creating a new one.

### Example (single invocation):
\`\`\`typescript
tool: invoke_subagent
args: {
  agent_name: "explore-codebase",
  prompt: "Find all files related to authentication in the codebase"
}
\`\`\`

### Example (parallel invocation):
\`\`\`typescript
// Invoke two independent sub-agents in the same tool call block:
tool: invoke_subagent
args: { agent_name: "explore-codebase", prompt: "Find auth files" }

tool: invoke_subagent
args: { agent_name: "explore-codebase", prompt: "Find database models" }
\`\`\`

### Example (follow-up with session_id):
\`\`\`typescript
// Continue a prior sub-agent session using the Session ID from a previous result:
tool: invoke_subagent
args: { agent_name: "explore-codebase", prompt: "Now find the tests for those files", session_id: "abc-123" }
\`\`\``;
    }
    async execute(args, context) {
        const { agent_name, prompt, session_id } = args;
        this.logger.log(`Invoking sub-agent "${agent_name}" from session ${context.session_id}${session_id ? ` (reusing session ${session_id})` : ''}`);
        try {
            const result = await this.chatService.runAgentSync(agent_name, prompt, context.session_id, session_id ? { sessionId: session_id } : undefined);
            const outputWithSessionId = `${result.content}\n\n[Session ID: ${result.childSessionId}]`;
            if (result.success) {
                return {
                    status: 'SUCCESS',
                    summary: `Sub-agent "${agent_name}" completed successfully.`,
                    persisted_args: {
                        arguments: JSON.stringify(args),
                        agentName: agent_name,
                        prompt,
                        childSessionId: result.childSessionId,
                        plain: result.content,
                        reason: `Sub-agent session: ${result.childSessionId}`,
                    },
                    execution_log: {
                        output: outputWithSessionId,
                        error_message: '',
                    },
                };
            }
            else {
                return {
                    status: 'FAILURE',
                    summary: `Sub-agent "${agent_name}" failed or could not complete.`,
                    error_message: result.content,
                    persisted_args: {
                        arguments: JSON.stringify(args),
                        agentName: agent_name,
                        prompt,
                        childSessionId: result.childSessionId,
                        plain: result.content,
                        reason: `Sub-agent session: ${result.childSessionId}`,
                    },
                    execution_log: {
                        output: outputWithSessionId,
                        error_message: result.content,
                    },
                };
            }
        }
        catch (error) {
            this.logger.error(`Sub-agent "${agent_name}" execution error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to invoke sub-agent "${agent_name}"`,
                error_message: error.message,
                execution_log: {
                    output: '',
                    error_message: error.message,
                },
            };
        }
    }
};
exports.InvokeSubAgentHandler = InvokeSubAgentHandler;
exports.InvokeSubAgentHandler = InvokeSubAgentHandler = InvokeSubAgentHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [chat_service_1.ChatService])
], InvokeSubAgentHandler);
//# sourceMappingURL=invoke-subagent.handler.js.map