"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listStoredToolResponsesDefinition = exports.tailToolResponseDefinition = exports.grepToolResponseDefinition = exports.jqToolResponseDefinition = exports.ToolResponseCache = void 0;
const JsonCompressor_1 = require("./JsonCompressor");
const tools_1 = require("./tools");
Object.defineProperty(exports, "jqToolResponseDefinition", { enumerable: true, get: function () { return tools_1.jqToolResponseDefinition; } });
Object.defineProperty(exports, "grepToolResponseDefinition", { enumerable: true, get: function () { return tools_1.grepToolResponseDefinition; } });
Object.defineProperty(exports, "tailToolResponseDefinition", { enumerable: true, get: function () { return tools_1.tailToolResponseDefinition; } });
Object.defineProperty(exports, "listStoredToolResponsesDefinition", { enumerable: true, get: function () { return tools_1.listStoredToolResponsesDefinition; } });
class ToolResponseCache {
    storage = {};
    metadataStorage = {};
    toolNameMap = {};
    jsonCompressor;
    constructor(toolsService, jsonCompressor) {
        this.jsonCompressor = jsonCompressor || this.createMinimalJsonCompressor();
        this.registerTool(toolsService);
    }
    createMinimalJsonCompressor() {
        const minimalStorage = {
            storeString: (key, value) => {
            },
            generateKey: () => {
                return `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            },
            estimateTokens: (text) => {
                return Math.ceil(text.length / 4);
            },
        };
        return new JsonCompressor_1.JsonCompressor(minimalStorage, 4000, 8000, "expandTokens");
    }
    parseNestedJsonStrings(obj) {
        if (typeof obj === "string") {
            const parsed = this.jsonCompressor.tryParseJson(obj);
            if (parsed) {
                return this.parseNestedJsonStrings(parsed);
            }
            return obj;
        }
        if (Array.isArray(obj)) {
            return obj.map((item) => this.parseNestedJsonStrings(item));
        }
        if (obj && typeof obj === "object") {
            const result = {};
            for (const [key, value] of Object.entries(obj)) {
                result[key] = this.parseNestedJsonStrings(value);
            }
            return result;
        }
        return obj;
    }
    storeToolResponse(content, toolCallId, toolName) {
        if (this.storage[toolCallId]) {
            return;
        }
        const parsed = this.jsonCompressor.tryParseJson(content);
        if (parsed && typeof parsed === 'object' && parsed._mcp_format === true && parsed._data) {
            this.storage[toolCallId] = JSON.stringify({
                _mcp_format: true,
                _raw_structure: parsed._raw_structure,
                _data: parsed._data
            });
        }
        else if (parsed !== null) {
            try {
                const outerParse = JSON.parse(content);
                if (typeof outerParse === 'string') {
                    if (typeof parsed === 'object') {
                        this.storage[toolCallId] = JSON.stringify(parsed);
                    }
                    else if (typeof parsed === 'string') {
                        this.storage[toolCallId] = parsed;
                    }
                    else {
                        this.storage[toolCallId] = content;
                    }
                }
                else {
                    this.storage[toolCallId] = content;
                }
            }
            catch {
                this.storage[toolCallId] = content;
            }
        }
        else {
            this.storage[toolCallId] = content;
        }
        this.metadataStorage[toolCallId] = {
            toolCallId,
            originalLength: content.length,
            storedAt: Date.now(),
        };
        if (toolName) {
            this.toolNameMap[toolCallId] = toolName;
        }
    }
    async processMessage(message) {
        if (message.role !== "tool" ||
            !message.tool_call_id ||
            typeof message.content !== "string") {
            return;
        }
        this.storeToolResponse(message.content, message.tool_call_id, message.name);
    }
    createProcessor(filterFn) {
        return async (originalMessages, modifiedMessages) => {
            for (const message of originalMessages) {
                if (filterFn && !filterFn(message)) {
                    continue;
                }
                await this.processMessage(message);
            }
        };
    }
    async queryToolResponse(toolCallId, jqQuery) {
        const data = this.storage[toolCallId];
        const availableIds = Object.keys(this.storage);
        return (0, tools_1.executeJqQuery)(data, toolCallId, jqQuery, availableIds, this.toolNameMap);
    }
    async grepToolResponse(toolCallId, pattern, options) {
        const data = this.storage[toolCallId];
        const availableIds = Object.keys(this.storage);
        return (0, tools_1.executeGrep)(data, toolCallId, pattern, availableIds, options, this.toolNameMap);
    }
    async tailToolResponse(toolCallId, options) {
        const data = this.storage[toolCallId];
        const availableIds = Object.keys(this.storage);
        return (0, tools_1.executeTail)(data, toolCallId, availableIds, options, this.toolNameMap);
    }
    async listStoredToolResponses() {
        return (0, tools_1.executeListStoredToolResponses)(this.storage, this.metadataStorage, this.toolNameMap);
    }
    retrieveRawResponse(toolCallId) {
        return this.storage[toolCallId] || null;
    }
    clearStorage() {
        this.storage = {};
        this.metadataStorage = {};
    }
    getStorageKeys() {
        return Object.keys(this.storage);
    }
    getStorageSize() {
        return Object.keys(this.storage).length;
    }
    registerTool(toolsService) {
        toolsService.addTools([
            tools_1.jqToolResponseDefinition,
            tools_1.grepToolResponseDefinition,
            tools_1.tailToolResponseDefinition,
            tools_1.listStoredToolResponsesDefinition,
        ]);
        toolsService.addFunctions({
            [tools_1.jqToolResponseDefinition.function.name]: async (toolCallId, jqQuery) => {
                return await this.queryToolResponse(toolCallId, jqQuery);
            },
            [tools_1.grepToolResponseDefinition.function.name]: async (toolCallId, pattern, options) => {
                return await this.grepToolResponse(toolCallId, pattern, options);
            },
            [tools_1.tailToolResponseDefinition.function.name]: async (toolCallId, options) => {
                return await this.tailToolResponse(toolCallId, options);
            },
            [tools_1.listStoredToolResponsesDefinition.function.name]: async () => {
                return await this.listStoredToolResponses();
            },
        });
    }
}
exports.ToolResponseCache = ToolResponseCache;
//# sourceMappingURL=ToolResponseCache.js.map