"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentModule = void 0;
const renderer_1 = require("../renderer");
const index_1 = require("../../services/index");
const fs = __importStar(require("fs"));
const fsPromises = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const BaseChatModule_1 = require("./BaseChatModule");
const index_2 = require("../../services/index");
const index_3 = require("../../utils/index");
const TokenCompressor_1 = require("../../processors/TokenCompressor");
const ToolResponseCache_1 = require("../../processors/ToolResponseCache");
const index_4 = require("../../processors/index");
const agents_1 = require("../../agents");
const KnowhowClient_1 = require("../../services/KnowhowClient");
class AgentModule extends BaseChatModule_1.BaseChatModule {
    name = "agent";
    description = "Agent interaction functionality";
    attachedAgent;
    taskRegistry;
    sessionManager;
    processStartTime = Date.now();
    activeAgentTaskId;
    activeSyncedWatcher;
    _wireAgentEvents;
    _wireTaskId;
    _wireAgentName;
    remoteSyncModule;
    _wireEventTypes;
    constructor() {
        super();
        this.taskRegistry = new index_1.TaskRegistry();
        this.sessionManager = new index_1.SessionManager();
    }
    setRemoteSyncModule(module) {
        this.remoteSyncModule = module;
    }
    getCommands() {
        return [
            {
                name: "agent",
                description: "Start an agent by name",
                handler: this.handleAgentCommand.bind(this),
            },
            {
                name: "agents",
                description: "List available agents",
                handler: this.handleAgentsCommand.bind(this),
            },
            {
                name: "pause",
                description: "Pause the currently attached agent",
                modes: ["agent:attached"],
                handler: async (_args) => {
                    if (this.attachedAgent) {
                        await this.attachedAgent.pause();
                        console.log("Agent paused.");
                    }
                },
            },
            {
                name: "unpause",
                description: "Unpause the currently attached agent",
                modes: ["agent:attached"],
                handler: async (_args) => {
                    if (this.attachedAgent) {
                        await this.attachedAgent.unpause();
                        console.log("Agent unpaused.");
                    }
                },
            },
            {
                name: "kill",
                description: "Kill the currently attached agent",
                modes: ["agent:attached"],
                handler: async (_args) => {
                    if (this.attachedAgent) {
                        await this.attachedAgent.kill();
                        console.log("Agent terminated.");
                        this.detachFromAgent();
                    }
                },
            },
            {
                name: "detach",
                description: "Detach from the currently attached agent",
                modes: ["agent:attached"],
                handler: async (_args) => {
                    console.log("Detached from agent");
                    this.detachFromAgent();
                },
            },
            {
                name: "done",
                description: "Exit the current agent interaction",
                modes: ["agent:attached"],
                handler: async (_args) => {
                    this.detachFromAgent();
                },
            },
        ];
    }
    detachFromAgent() {
        this.attachedAgent = undefined;
        this.unwireAgentRendering();
        if (this.chatService) {
            this.chatService.setMode("default");
        }
        if (this.activeSyncedWatcher) {
            this.activeSyncedWatcher.stopWatching();
            this.activeSyncedWatcher = undefined;
        }
        const context = this.chatService?.getContext();
        if (context)
            context.activeAgentTaskId = undefined;
    }
    getModes() {
        return [
            {
                name: "agent",
                description: "Agent interaction mode",
                active: true,
                promptText: () => {
                    const ctx = this.chatService?.getContext();
                    return ctx?.currentAgent
                        ? `\nAsk knowhow ${ctx.currentAgent}: `
                        : `\nAsk knowhow: `;
                },
            },
            {
                name: "agent:attached",
                description: "Attached to a running agent",
                active: false,
                promptText: () => this.attachedAgent
                    ? `Enter command or message for ${this.attachedAgent.name}: `
                    : `Enter command or message for agent: `,
            },
        ];
    }
    get renderer() {
        return (this.chatService?.getContext()?.renderer ??
            new renderer_1.ConsoleRenderer());
    }
    async initialize(service) {
        await super.initialize(service);
        const Events = (0, index_2.services)().Events;
        Events.setListener({ key: "agentModule:pluginLog", event: Events.eventTypes.pluginLog }, (logEvent) => {
            const activeTasks = this.taskRegistry.getAll();
            this.renderer.render({
                type: "log",
                taskId: this.activeAgentTaskId,
                agentName: logEvent.source,
                message: logEvent.message,
                level: logEvent.level || "info",
                timestamp: logEvent.timestamp || new Date().toISOString(),
            });
        });
        await this.handleAgentCommand(["Patcher"]);
    }
    async handleAgentCommand(args) {
        const context = this.chatService?.getContext();
        if (args.length === 0) {
            if (context?.agentMode) {
                if (context) {
                    context.agentMode = false;
                    context.selectedAgent = undefined;
                    context.currentAgent = undefined;
                    this.chatService.disableMode("agent");
                }
                console.log("Agent mode disabled. Switched to chat mode.");
                return;
            }
            else {
                console.log("Agent mode is currently disabled. Use /agent <agent_name> to enable it, or /agents to list available agents.");
                return;
            }
        }
        const agentName = args[0];
        try {
            if (agents_1.agentConstructors[agentName]) {
                if (context) {
                    const agentContext = (0, index_2.services)().Agents.getAgentContext();
                    const tempAgent = (0, agents_1.createAgent)(agentName, agentContext);
                    context.selectedAgent = tempAgent;
                    context.agentMode = true;
                    context.currentAgent = agentName;
                    const clientInfo = await tempAgent.clientService.getClient(undefined, tempAgent.getModel());
                    context.currentModel = clientInfo.model;
                    context.currentProvider = clientInfo.provider;
                    this.chatService.setMode("agent");
                }
                console.log(`Agent mode enabled. Selected agent: ${agentName}. Type your task to get started.`);
            }
            else {
                console.log(`Agent "${agentName}" not found. Use /agents to list available agents.`);
            }
        }
        catch (error) {
            console.error(`Error selecting agent ${agentName}:`, error);
        }
    }
    getTaskRegistry() {
        return this.taskRegistry;
    }
    getSessionManager() {
        return this.sessionManager;
    }
    getRenderer() {
        return this.renderer;
    }
    getActiveSyncedWatcher() {
        return this.activeSyncedWatcher;
    }
    setActiveSyncedWatcher(w) {
        this.activeSyncedWatcher = w;
    }
    getActiveAgentTaskId() {
        return this.activeAgentTaskId;
    }
    setActiveAgentTaskId(id) {
        this.activeAgentTaskId = id;
    }
    wireAgentRendering(taskId, agentEvents, eventTypes, agentName) {
        if (eventTypes.toolCall) {
            agentEvents.setListener({ key: "agentModule:render:toolCall", event: eventTypes.toolCall }, (data) => this.renderer.render({
                type: "toolCall",
                taskId,
                agentName,
                toolCall: data.toolCall,
            }));
        }
        if (eventTypes.toolUsed) {
            agentEvents.setListener({ key: "agentModule:render:toolUsed", event: eventTypes.toolUsed }, (data) => this.renderer.render({
                type: "toolResult",
                taskId,
                agentName,
                toolCall: data.toolCall,
                result: data.functionResp,
            }));
        }
        if (eventTypes.agentSay) {
            agentEvents.setListener({ key: "agentModule:render:agentSay", event: eventTypes.agentSay }, (data) => this.renderer.render({
                type: "agentMessage",
                taskId,
                agentName,
                message: data.message,
                role: "assistant",
            }));
        }
        this.activeAgentTaskId = taskId;
        this.renderer.setActiveTaskId(taskId);
        this._wireAgentEvents = agentEvents;
        this._wireAgentName = agentName;
        this._wireEventTypes = eventTypes;
        this._wireTaskId = taskId;
    }
    unwireAgentRendering() {
        if (this._wireAgentEvents) {
            this._wireAgentEvents.removeManagedListenersByPrefix("agentModule:render:");
            this._wireAgentEvents = undefined;
        }
        this.activeAgentTaskId = undefined;
        this.renderer.setActiveTaskId(undefined);
    }
    rewireAgentRendering() {
        if (!this._wireAgentEvents ||
            !this._wireTaskId ||
            !this._wireEventTypes ||
            !this._wireAgentName)
            return;
        this.wireAgentRendering(this._wireTaskId, this._wireAgentEvents, this._wireEventTypes, this._wireAgentName);
    }
    async handleAgentsCommand(args) {
        try {
            const agentNames = Object.keys(agents_1.agentConstructors);
            if (agentNames.length > 0) {
                console.log("\nAvailable agents:");
                agentNames.forEach((name) => {
                    console.log(`  - ${name}`);
                });
                console.log("─".repeat(80), "\n");
                const selectedAgent = await this.chatService?.getInput("Select an agent to start: ", agentNames);
                if (selectedAgent &&
                    selectedAgent.trim() &&
                    agentNames.includes(selectedAgent.trim())) {
                    await this.handleAgentCommand([selectedAgent.trim()]);
                }
                else if (selectedAgent && selectedAgent.trim()) {
                    console.log(`Agent "${selectedAgent.trim()}" not found.`);
                }
            }
        }
        catch (error) {
            console.error("Error listing agents:", error);
            console.log("Could not load agents list.");
        }
    }
    getProcessStartTime() {
        return this.processStartTime;
    }
    async resumeSession(sessionId, resumeReason) {
        try {
            const session = this.sessionManager.loadSession(sessionId);
            if (!session) {
                console.error(`Session ${sessionId} not found.`);
                return;
            }
            console.log(`\n🔄 Resuming session: ${sessionId}`);
            console.log(`Agent: ${session.agentName}`);
            console.log(`Original task: ${session.initialInput}`);
            console.log(`Status: ${session.status}`);
            const resumePrompt = [
                "You are resuming a previously started task.",
                session.initialInput ? `ORIGINAL REQUEST: ${session.initialInput}` : "",
                "Please continue from where you left off and complete the original request.",
                resumeReason ? `Reason for resuming: ${resumeReason}` : "",
            ]
                .filter(Boolean)
                .join("\n");
            const threads = session.threads || [];
            const normalizedThreads = threads.length > 0 && !Array.isArray(threads[0])
                ? [threads]
                : threads;
            const lastThread = normalizedThreads.length > 0 ? normalizedThreads[normalizedThreads.length - 1] : [];
            const resumeMessages = [...lastThread];
            const reversedIndex = [...lastThread]
                .reverse()
                .findIndex((e) => e.role === "user" && typeof e.content === "string");
            if (reversedIndex === -1) {
                resumeMessages.push({ role: "user", content: resumePrompt });
            }
            else {
                const actualIndex = lastThread.length - 1 - reversedIndex;
                resumeMessages[actualIndex] = {
                    ...resumeMessages[actualIndex],
                    content: resumeMessages[actualIndex].content + `\n\n<Workflow>[RESUME CONTEXT]: ${resumePrompt}</Workflow>`,
                };
            }
            console.log("🚀 Session resuming...");
            const context = this.chatService?.getContext();
            const agentName = session.agentName || context.currentAgent;
            const previousAgentMode = context?.agentMode;
            if (!agentName || !agents_1.agentConstructors[agentName]) {
                console.error(`Agent ${agentName} not found.`);
                return;
            }
            const { agent, taskId } = await this.setupAgent({
                agentName,
                input: resumePrompt,
                messageId: session.knowhowMessageId,
                existingKnowhowTaskId: session.knowhowTaskId,
                chatHistory: [],
                run: false,
            });
            agent.agentEvents.once(agent.eventTypes.done, () => {
                const ctx = this.chatService?.getContext();
                if (ctx && !previousAgentMode) {
                    ctx.agentMode = false;
                    ctx.selectedAgent = undefined;
                    ctx.currentAgent = undefined;
                    this.chatService?.disableMode("agent");
                }
            });
            await this.attachedAgentChatLoop(taskId, agent, resumePrompt, resumeMessages);
        }
        catch (error) {
            console.error(`Failed to resume session ${sessionId}:`, error.message);
        }
    }
    async handleInput(input, context) {
        if (context.agentMode && context.selectedAgent) {
            if (this.attachedAgent) {
                this.attachedAgent.addPendingUserMessage({
                    role: "user",
                    content: input,
                });
                return true;
            }
            context.chatHistory = context.chatHistory || [];
            const { taskId } = await this.startAgent(context.selectedAgent, input, context.chatHistory);
            context.chatHistory.push({
                input,
                output: "",
                taskId,
            });
            return true;
        }
        return false;
    }
    async setupAgent(options) {
        if (!agents_1.agentConstructors[options.agentName]) {
            throw new Error(`Agent "${options.agentName}" not found. Available agents: ${Object.keys(agents_1.agentConstructors).join(", ")}`);
        }
        const { input, chatHistory = [], agentName } = options;
        const agentContext = (0, index_2.services)().Agents.getAgentContext();
        const agent = (0, agents_1.createAgent)(options.agentName, agentContext);
        let done = false;
        let output = "Done";
        const taskId = options.taskId || this.sessionManager.generateTaskId(input);
        let knowhowTaskId;
        try {
            const context = this.chatService?.getContext();
            const plugins = context?.plugins || [];
            const formattedPrompt = await this.chatService.formatChatInput(input, plugins, chatHistory);
            let taskInfo = {
                taskId,
                knowhowMessageId: options.messageId,
                knowhowTaskId: options.existingKnowhowTaskId,
                agentName,
                agent,
                initialInput: input,
                formattedPrompt,
                status: "running",
                startTime: Date.now(),
                totalCost: 0,
            };
            this.taskRegistry.register(taskId, taskInfo);
            this.saveSession(taskId, taskInfo, []);
            const syncer = new index_1.SyncerService();
            const syncTaskId = await syncer.createTask({
                taskId,
                prompt: input,
                messageId: options.messageId,
                syncFs: options.syncFs,
                existingKnowhowTaskId: options.existingKnowhowTaskId,
                agentName,
            });
            const webTaskId = syncer.getCreatedWebTaskId();
            knowhowTaskId = webTaskId;
            taskInfo.knowhowTaskId = webTaskId || syncTaskId;
            this.taskRegistry.register(taskId, taskInfo);
            await syncer.setupAgentSync(agent, syncTaskId);
            const threadUpdateHandler = async (threadState) => {
                this.updateSession(taskId, agent.getThreads());
                taskInfo.totalCost = agent.getTotalCostUsd();
            };
            agent.agentEvents.on(agent.eventTypes.threadUpdate, threadUpdateHandler);
            console.log(index_3.Marked.parse(`**Starting ${agent.name} with task ID: ${taskId}...**`));
            console.log(index_3.Marked.parse(`**Task:** ${input}`));
            await agent.newTask(taskId);
            if (options.model) {
                console.log("Setting model:", options.model);
                agent.setModel(options.model);
                agent.setModelPreferences([
                    { model: options.model, provider: options.provider },
                ]);
            }
            agent.tools.registerOverride("askHuman", async (originalArgs, originalTool) => {
                const question = originalArgs[0];
                const chatService = this.chatService;
                if (!chatService) {
                    throw new Error("ChatService not available in tools context");
                }
                console.log("AI has asked: ");
                console.log(index_3.Marked.parse(question), "\n");
                return await chatService.getInput("response: ");
            }, 10);
            const caching = [
                new ToolResponseCache_1.ToolResponseCache(agent.tools).createProcessor(),
                new TokenCompressor_1.TokenCompressor(agent.tools).createProcessor((msg) => Boolean(msg.role === "tool" && msg.tool_call_id)),
            ];
            agent.messageProcessor.setProcessors("pre_call", [
                new index_4.Base64ImageProcessor(agent.tools).createProcessor(),
                ...caching,
                new index_4.CustomVariables(agent.tools).createProcessor(),
            ]);
            agent.messageProcessor.setProcessors("post_call", [
                new index_4.XmlToolCallProcessor().createProcessor(),
                new index_4.HarmonyToolProcessor().createProcessor(),
            ]);
            agent.messageProcessor.setProcessors("post_tools", [
                new index_4.Base64ImageProcessor(agent.tools).createProcessor(),
                ...caching,
            ]);
            const agentLogHandler = (logData) => {
                this.renderer.render({
                    type: "log",
                    taskId,
                    agentName: logData.agentName,
                    message: logData.message,
                    level: logData.level,
                    timestamp: logData.timestamp,
                });
            };
            const agentStatusHandler = (statusData) => {
                this.renderer.render({
                    type: "agentStatus",
                    taskId,
                    agentName: statusData.agentName,
                    statusMessage: statusData.statusMessage,
                    details: statusData.details,
                    timestamp: statusData.timestamp,
                });
            };
            agent.agentEvents.on(agent.eventTypes.agentLog, agentLogHandler);
            agent.agentEvents.on(agent.eventTypes.agentStatus, agentStatusHandler);
            const taskCompleted = new Promise((resolve) => {
                agent.agentEvents.once(agent.eventTypes.done, async (doneMsg) => {
                    console.log("🎯 [AgentModule] Task Completed");
                    done = true;
                    output = doneMsg || "No response from the AI";
                    agent.agentEvents.removeListener(agent.eventTypes.threadUpdate, threadUpdateHandler);
                    agent.agentEvents.removeListener(agent.eventTypes.agentLog, agentLogHandler);
                    agent.agentEvents.removeListener(agent.eventTypes.agentStatus, agentStatusHandler);
                    taskInfo = this.taskRegistry.get(taskId);
                    await syncer.waitForFinalization();
                    if (taskInfo) {
                        taskInfo.status = "completed";
                        taskInfo.totalCost = agent.getTotalCostUsd();
                        this.updateSession(taskId, agent.getThreads());
                        taskInfo.endTime = Date.now();
                    }
                    console.log(index_3.Marked.parse(output));
                    console.log("🎯 [AgentModule] Task Complete");
                    resolve(doneMsg);
                });
            });
            if (options.maxTimeLimit) {
                agent.setMaxRunTime(options.maxTimeLimit * 60 * 1000);
            }
            console.log(`🤖 Starting agent: ${options.agentName}`);
            console.log(`📝 Task: ${options.input}`);
            if (options.maxTimeLimit) {
                console.log(`⏱️  Time limit: ${options.maxTimeLimit} minutes`);
            }
            if (options.maxSpendLimit) {
                console.log(`💰 Spend limit: $${options.maxSpendLimit}`);
            }
            console.log("─".repeat(50));
            if (options.run) {
                agent.call(formattedPrompt);
            }
            return {
                agent,
                taskId,
                formattedPrompt,
                initialInput: input,
                taskCompleted,
            };
        }
        catch (error) {
            console.error("Agent setup failed:", error);
            this.taskRegistry.delete(taskId);
        }
    }
    async loadThreadsForTask(taskId, messageId) {
        const resumeTaskId = taskId;
        const localMetadataPath = path.join(".knowhow", "processes", "agents", resumeTaskId, "metadata.json");
        let threads = [];
        if (!messageId && fs.existsSync(localMetadataPath)) {
            try {
                const raw = await fsPromises.readFile(localMetadataPath, "utf-8");
                const metadata = JSON.parse(raw);
                threads = metadata.threads || [];
                console.log(`📁 Loaded threads from local FS: ${localMetadataPath}`);
            }
            catch (e) {
                console.warn(`⚠️ Failed to parse local metadata: ${e.message}`);
            }
        }
        else {
            try {
                const client = new KnowhowClient_1.KnowhowSimpleClient();
                threads = await client.getTaskThreads(resumeTaskId);
                console.log(`🌐 Loaded threads from remote for task: ${resumeTaskId}`);
            }
            catch (e) {
                console.warn(`⚠️ Could not load threads from remote: ${e.message}`);
            }
        }
        return threads;
    }
    async resumeFromMessages(options) {
        const { agentName, input, threads, messageId, taskId } = options;
        let originalRequest = "";
        if (threads && threads.length > 0) {
            const firstThread = threads[0];
            if (Array.isArray(firstThread)) {
                const firstUserMsg = firstThread.find((m) => m.role === "user" && m.content);
                if (firstUserMsg) {
                    originalRequest =
                        typeof firstUserMsg.content === "string"
                            ? firstUserMsg.content
                            : JSON.stringify(firstUserMsg.content);
                }
            }
        }
        const resumePrompt = [
            "You are resuming a previously started task.",
            originalRequest ? `ORIGINAL REQUEST: ${originalRequest}` : "",
            "Please continue from where you left off.",
            input ? input : "",
        ]
            .filter(Boolean)
            .join("\n");
        const lastThread = threads && threads.length > 0 ? threads[threads.length - 1] : [];
        const resumeMessages = [...lastThread];
        const resumeIndex = lastThread
            .reverse()
            .findIndex((e) => e.role === "user" && typeof e.content === "string");
        if (resumeIndex === -1) {
            resumeMessages.push({
                role: "user",
                content: resumePrompt,
            });
        }
        else {
            const actualIndex = lastThread.length - 1 - resumeIndex;
            const lastUserMessage = resumeMessages[actualIndex];
            lastUserMessage.content += `\n\n<Workflow>[RESUME CONTEXT]: ${resumePrompt}</Workflow>`;
        }
        const result = await this.setupAgent({
            agentName,
            input: resumePrompt,
            messageId,
            existingKnowhowTaskId: taskId,
            run: false,
        });
        result.agent.call(resumePrompt, resumeMessages);
        return { taskCompleted: result.taskCompleted };
    }
    getActiveTasks() {
        return Array.from(this.taskRegistry.getEntries()).map(([taskId, taskInfo]) => ({
            taskId,
            agent: taskInfo,
        }));
    }
    attachToTask(taskId) {
        if (this.taskRegistry.has(taskId)) {
            console.log(index_3.Marked.parse(`**Attached to agent task: ${taskId}**`));
            return true;
        }
        console.log(index_3.Marked.parse(`**Task ${taskId} not found or already completed.**`));
        return false;
    }
    saveSession(taskId, taskInfo, threads) {
        this.sessionManager.saveSession(taskId, taskInfo, threads);
    }
    updateSession(taskId, threads) {
        const taskInfo = this.taskRegistry.get(taskId);
        this.sessionManager.updateSession(taskId, taskInfo, threads);
    }
    async startAgent(selectedAgent, initialInput, chatHistory = []) {
        try {
            const { agent, taskId, formattedPrompt } = await this.setupAgent({
                agentName: selectedAgent.name,
                input: initialInput,
                chatHistory,
                model: selectedAgent.getModel(),
                provider: selectedAgent.getProvider(),
                run: false,
            });
            if (this.remoteSyncModule?.isAutoSyncEnabled()) {
                await this.remoteSyncModule.syncTask(taskId);
            }
            await this.attachedAgentChatLoop(taskId, agent, formattedPrompt);
            return { taskId };
        }
        catch (error) {
            console.error("Error starting agent:", error);
        }
    }
    async attachedAgentChatLoop(taskId, agent, initialInput, initialMessages) {
        try {
            let agentFinalOutput;
            if (this.chatService) {
                this.chatService.setMode("agent:attached");
            }
            this.wireAgentRendering(taskId, agent.agentEvents, agent.eventTypes, agent.name);
            const context = this.chatService?.getContext();
            if (context)
                context.activeAgentTaskId = taskId;
            this.attachedAgent = agent;
            const donePromise = new Promise((resolve) => {
                agent.agentEvents.once(agent.eventTypes.done, (doneMsg) => {
                    agentFinalOutput = doneMsg || "No response from the AI";
                    console.log("Finished", taskId, `$${agent.getTotalCostUsd()}`);
                    const finalTaskInfo = this.taskRegistry.get(taskId);
                    if (finalTaskInfo) {
                        if (finalTaskInfo.status === "running") {
                            finalTaskInfo.status = "completed";
                            finalTaskInfo.totalCost = agent.getTotalCostUsd();
                            finalTaskInfo.endTime = Date.now();
                        }
                    }
                    if (context.chatHistory) {
                        const found = context.chatHistory.find((h) => h.taskId === taskId);
                        if (found)
                            found.output = agentFinalOutput;
                    }
                    resolve("done");
                    this.detachFromAgent();
                });
            });
            if (initialInput) {
                const taskInfo = this.taskRegistry.get(taskId);
                agent.call(taskInfo?.formattedPrompt || taskInfo?.initialInput || initialInput, initialMessages);
            }
        }
        catch (error) {
            console.error("Agent execution failed:", error);
        }
    }
}
exports.AgentModule = AgentModule;
//# sourceMappingURL=AgentModule.js.map