"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.jqToolResponseDefinition = void 0;
exports.executeJqQuery = executeJqQuery;
const jq = __importStar(require("node-jq"));
function tryParseJson(content) {
    try {
        return JSON.parse(content);
    }
    catch {
        return null;
    }
}
function parseNestedJsonStrings(obj) {
    if (typeof obj === "string") {
        const parsed = tryParseJson(obj);
        if (parsed) {
            return parseNestedJsonStrings(parsed);
        }
        return obj;
    }
    if (Array.isArray(obj)) {
        return obj.map((item) => parseNestedJsonStrings(item));
    }
    if (obj && typeof obj === "object") {
        const result = {};
        for (const [key, value] of Object.entries(obj)) {
            result[key] = parseNestedJsonStrings(value);
        }
        return result;
    }
    return obj;
}
async function executeJqQuery(data, toolCallId, jqQuery, availableIds, toolNameMap) {
    if (!data) {
        const idList = availableIds
            .map((id) => {
            const name = toolNameMap?.[id];
            return name ? `${id} (${name})` : id;
        })
            .join("\n  - ");
        return `Error: No tool response found for toolCallId "${toolCallId}". Call listStoredToolResponses to see all available responses with their tool names.\n\nAvailable toolCallIds:\n  - ${idList || "(none)"}`;
    }
    try {
        const jsonData = tryParseJson(data);
        if (!jsonData) {
            return `Error: Tool response data is not valid JSON for toolCallId "${toolCallId}"`;
        }
        const parsedData = parseNestedJsonStrings(jsonData);
        const result = await jq.run(jqQuery, parsedData, { input: "json" });
        if (typeof result === "string") {
            return result;
        }
        else if (typeof result === "number" || typeof result === "boolean") {
            return String(result);
        }
        else if (result === null) {
            return "null";
        }
        else {
            return JSON.stringify(result);
        }
    }
    catch (error) {
        let errorMessage = `JQ Query Error: ${error.message}`;
        const jsonObj = tryParseJson(data);
        if (!jsonObj) {
            errorMessage += `\nNote: The tool response data is not valid JSON. Raw data preview:\n${data.substring(0, 300)}...`;
        }
        else {
            errorMessage += `\nData structure preview:\n${JSON.stringify(jsonObj, null, 2).substring(0, 500)}...`;
        }
        return errorMessage;
    }
}
exports.jqToolResponseDefinition = {
    type: "function",
    function: {
        name: "jqToolResponse",
        description: "Execute a JQ query on a stored tool response to extract specific data. Use this when you need to extract specific information from any tool response that has been stored. This is the preferred way to search or filter compressed JSON tool responses — it parses the data automatically without requiring repeated expandTokens calls. IMPORTANT: You do NOT know the toolCallId at the time you call a tool — you must call listStoredToolResponses first to discover the correct toolCallId. The listStoredToolResponses output shows each response's tool name so you can identify which response belongs to which call. How to determine the correct JQ query: (1) For mcp_* tool responses (external MCP tools like mcp_1_*): the response is stored as a raw JSON object — use '.' to access the root directly, e.g. '.children | map(.name)' or '.state'. Do NOT use .content[0].text | fromjson for these. (2) For compressed MCP tool responses (._mcp_format === true): use '._data' e.g. '._data.children | map(.name)'. (3) For standard built-in tool responses: data may be nested under '.content[0].text | fromjson'. Use jqToolResponse instead of expandTokens whenever the stored data is JSON.",
        parameters: {
            type: "object",
            positional: true,
            properties: {
                toolCallId: {
                    type: "string",
                    description: "The toolCallId of the stored tool response",
                },
                jqQuery: {
                    type: "string",
                    description: "The JQ query to execute on the tool response data. For mcp_* tool responses (raw JSON object): '.children | map({id: .id, name: .name})' (extract fields from children array), '.children | map(select(.state == \"PENDING\")) | length' (count pending children), '.name' (get a top-level field). For compressed responses (._mcp_format true): '._data.children | map(.name)' or '._data | map(select(.state == \"PENDING\")) | length'. For standard built-in tool responses: '.content[0].text | fromjson | map(.title)' (extract titles from standard MCP array), '.content[0].text | fromjson | map(select(.createdAt > \"2025-01-01\"))' (filter by date).",
                },
            },
            required: ["toolCallId", "jqQuery"],
        },
    },
};
//# sourceMappingURL=jqToolResponse.js.map