// index.ts
import axios from "axios";
const DEFAULT_BASE_URL = "http://192.168.0.200:8420";
const DEFAULT_TIMEOUT_MS = 10000;
const DEFAULT_KNOWLEDGE_USER_ID = "knowledge_base";
function getBaseUrl(plugin) {
    return (plugin?.config?.baseUrl ||
        process.env.MEM0_BASE_URL ||
        DEFAULT_BASE_URL);
}
function getDefaultUserId(plugin) {
    return (plugin?.runtime?.agent?.id ||
        globalThis?.openclaw?.agent?.id ||
        plugin?.config?.userId ||
        "default");
}
function getKnowledgeUserId(plugin) {
    return (plugin?.config?.knowledgeUserId ||
        process.env.MEM0_KNOWLEDGE_USER_ID ||
        DEFAULT_KNOWLEDGE_USER_ID);
}
function http(plugin) {
    return axios.create({
        baseURL: getBaseUrl(plugin),
        timeout: DEFAULT_TIMEOUT_MS,
    });
}
export const activate = (plugin) => {
    const client = http(plugin);
    // write conversational memory
    plugin.write = async ({ text, userId }) => {
        const finalUserId = userId || getDefaultUserId(plugin);
        if (!text)
            throw new Error("Missing text for memory write");
        const res = await client.post(`/memories`, { text, userId: finalUserId });
        return res.data;
    };
    // search conversational memory
    plugin.search = async ({ query, userId }) => {
        const finalUserId = userId || getDefaultUserId(plugin);
        if (!query)
            throw new Error("Missing query for memory search");
        const res = await client.post(`/memories/search`, {
            query,
            userId: finalUserId,
        });
        return res.data;
    };
    // search knowledge base
    plugin.searchKnowledge = async ({ query, userId }) => {
        const finalUserId = userId || getKnowledgeUserId(plugin);
        if (!query)
            throw new Error("Missing query for knowledge search");
        const res = await client.post(`/knowledge/search`, {
            query,
            userId: finalUserId,
        });
        return res.data;
    };
    // write to knowledge base
    plugin.writeKnowledge = async ({ text, userId }) => {
        const finalUserId = userId || getKnowledgeUserId(plugin);
        if (!text)
            throw new Error("Missing text for knowledge write");
        const res = await client.post(`/knowledge`, { text, userId: finalUserId });
        return res.data;
    };
    // read/recall recent memories (requires /memories/recent on server)
    plugin.read = async ({ userId, limit = 5 }) => {
        const finalUserId = userId || getDefaultUserId(plugin);
        const res = await client.post(`/memories/recent`, {
            userId: finalUserId,
            limit,
        });
        return res.data.results || [];
    };
};
