"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSyncedAgentWatcher = void 0;
const EventService_1 = require("../EventService");
const messagesToRenderEvents_1 = require("../../chat/renderer/messagesToRenderEvents");
const KnowhowClient_1 = require("../KnowhowClient");
class WebSyncedAgentWatcher {
    taskId = "";
    client;
    pollInterval = null;
    lastThreadLength = 0;
    agentName = "remote-agent";
    stopped = false;
    agentEvents = new EventService_1.EventService();
    eventTypes = {
        done: "done",
        toolCall: "tool:pre_call",
        toolUsed: "tool:post_call",
        agentSay: "agent:say",
        threadUpdate: "thread_update",
    };
    constructor(client) {
        this.client = client || new KnowhowClient_1.KnowhowSimpleClient();
    }
    async startWatching(taskId) {
        this.taskId = taskId;
        this.stopped = false;
        try {
            const details = await this.client.getTaskDetails(taskId);
            const threads = details?.data?.threads || [];
            const lastThread = threads[threads.length - 1] || [];
            this.agentName = "remote-agent";
            this.lastThreadLength = lastThread.length;
        }
        catch (err) {
            console.warn(`⚠️  Could not load initial state for task ${taskId}: ${err.message}`);
        }
        this.pollInterval = setInterval(async () => {
            if (!this.stopped) {
                await this.onPoll().catch(() => { });
            }
        }, 3000);
        console.log(`🌐 Watching web-synced agent: ${taskId} (${this.agentName})`);
        console.log(`   Type /logs 20 to see recent messages, or type to send a message`);
    }
    async onPoll() {
        if (this.stopped)
            return;
        try {
            const details = await this.client.getTaskDetails(this.taskId);
            const threads = details?.data?.threads || [];
            const lastThread = threads[threads.length - 1] || [];
            const newMessages = lastThread.slice(this.lastThreadLength);
            if (newMessages.length > 0) {
                const renderEvents = (0, messagesToRenderEvents_1.messagesToRenderEvents)(newMessages, this.taskId, this.agentName);
                for (const event of renderEvents) {
                    if (event.type === "toolCall") {
                        this.agentEvents.emit(this.eventTypes.toolCall, {
                            toolCall: event.toolCall,
                        });
                    }
                    else if (event.type === "toolResult") {
                        this.agentEvents.emit(this.eventTypes.toolUsed, {
                            toolCall: event.toolCall,
                            functionResp: event.result,
                        });
                    }
                    else if (event.type === "agentMessage") {
                        this.agentEvents.emit(this.eventTypes.agentSay, {
                            message: event.message,
                        });
                    }
                }
                this.agentEvents.emit(this.eventTypes.threadUpdate, lastThread);
                this.lastThreadLength = lastThread.length;
            }
            const status = details?.data?.status;
            const result = details?.data?.result;
            if (status === "completed" || status === "killed") {
                this.stopWatching();
                if (result != null) {
                    this.agentEvents.emit(this.eventTypes.done, result);
                }
                else {
                    console.log(`\n✅ Remote agent ${this.taskId} status: ${status} (no result)`);
                }
            }
        }
        catch {
        }
    }
    async sendMessage(message) {
        await this.client.sendMessageToAgent(this.taskId, message);
    }
    async getThreads() {
        try {
            const details = await this.client.getTaskDetails(this.taskId);
            return details?.data?.threads || [];
        }
        catch {
            return [];
        }
    }
    stopWatching() {
        this.stopped = true;
        if (this.pollInterval) {
            clearInterval(this.pollInterval);
            this.pollInterval = null;
        }
        console.log(`🔌 Stopped watching web agent: ${this.taskId}`);
    }
    async pause() {
        await this.client.pauseAgent(this.taskId);
        console.log(`⏸️  Paused remote web agent: ${this.taskId}`);
    }
    async unpause() {
        await this.client.resumeAgent(this.taskId);
        console.log(`▶️  Unpaused remote web agent: ${this.taskId}`);
    }
    async kill() {
        await this.client.killAgent(this.taskId);
        console.log(`🛑 Killed remote web agent: ${this.taskId}`);
    }
}
exports.WebSyncedAgentWatcher = WebSyncedAgentWatcher;
//# sourceMappingURL=RemoteSyncer.js.map