mem0ai
Version:
The Memory Layer For Your AI Apps
989 lines (980 loc) • 32 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/client/index.ts
var index_exports = {};
__export(index_exports, {
AuthenticationError: () => AuthenticationError,
ConfigurationError: () => ConfigurationError,
Feedback: () => Feedback,
MemoryClient: () => MemoryClient,
MemoryError: () => MemoryError,
MemoryNotFoundError: () => MemoryNotFoundError,
MemoryQuotaExceededError: () => MemoryQuotaExceededError,
NetworkError: () => NetworkError,
RateLimitError: () => RateLimitError,
ValidationError: () => ValidationError,
WebhookEvent: () => WebhookEvent,
createExceptionFromResponse: () => createExceptionFromResponse,
default: () => index_default
});
module.exports = __toCommonJS(index_exports);
// src/client/mem0.ts
var import_axios = __toESM(require("axios"));
// src/client/telemetry.ts
var version = true ? "3.0.3" : "dev";
var MEM0_TELEMETRY = true;
var _a;
try {
MEM0_TELEMETRY = ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) === "false" ? false : true;
} catch (error) {
}
var POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
var POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
function generateHash(input) {
const randomStr = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
return randomStr;
}
var UnifiedTelemetry = class {
constructor(projectApiKey, host) {
this.apiKey = projectApiKey;
this.host = host;
}
async captureEvent(distinctId, eventName, properties = {}) {
if (!MEM0_TELEMETRY) return false;
const eventProperties = {
client_version: version,
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
...properties,
$process_person_profile: false,
$lib: "posthog-node"
};
const payload = {
api_key: this.apiKey,
distinct_id: distinctId,
event: eventName,
properties: eventProperties
};
try {
const response = await fetch(this.host, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
if (!response.ok) {
console.error("Telemetry event capture failed:", await response.text());
return false;
}
return true;
} catch (error) {
console.error("Telemetry event capture failed:", error);
return false;
}
}
async captureIdentify(anonId, email) {
if (!MEM0_TELEMETRY) return false;
if (!anonId || !email || anonId === email) return false;
const payload = {
api_key: this.apiKey,
distinct_id: email,
event: "$identify",
properties: {
$anon_distinct_id: anonId,
client_source: "typescript",
$lib: "posthog-node"
}
};
try {
const response = await fetch(this.host, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
if (!response.ok) {
console.error(
"Telemetry identify capture failed:",
await response.text()
);
return false;
}
return true;
} catch (error) {
console.error("Telemetry identify capture failed:", error);
return false;
}
}
async shutdown() {
}
};
function isTelemetryEnabled() {
return MEM0_TELEMETRY;
}
var telemetry = new UnifiedTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);
async function captureClientEvent(eventName, instance, additionalData = {}) {
if (!instance.telemetryId) {
console.warn("No telemetry ID found for instance");
return;
}
const eventData = {
function: `${instance.constructor.name}`,
method: eventName,
api_host: instance.host,
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
client_version: version,
keys: (additionalData == null ? void 0 : additionalData.keys) || [],
...additionalData
};
await telemetry.captureEvent(
instance.telemetryId,
`client.${eventName}`,
eventData
);
}
// src/client/config.ts
async function getNodeFs() {
var _a2, _b, _c, _d, _e;
if (typeof process === "undefined" || !((_a2 = process.versions) == null ? void 0 : _a2.node)) return null;
try {
const [fs, path, os, crypto] = await Promise.all([
import("fs"),
import("path"),
import("os"),
import("crypto")
]);
const fsMod = (_b = fs.default) != null ? _b : fs;
const pathMod = (_c = path.default) != null ? _c : path;
const osMod = (_d = os.default) != null ? _d : os;
const cryptoMod = (_e = crypto.default) != null ? _e : crypto;
const dir = process.env.MEM0_DIR || pathMod.join(osMod.homedir(), ".mem0");
return {
fs: fsMod,
path: pathMod,
crypto: cryptoMod,
configPath: pathMod.join(dir, "config.json")
};
} catch (e) {
return null;
}
}
function loadConfig(node) {
try {
if (!node.fs.existsSync(node.configPath)) return null;
const parsed = JSON.parse(node.fs.readFileSync(node.configPath, "utf8"));
return parsed && typeof parsed === "object" ? parsed : null;
} catch (e) {
return null;
}
}
function writeConfig(node, config) {
node.fs.mkdirSync(node.path.dirname(node.configPath), { recursive: true });
node.fs.writeFileSync(node.configPath, JSON.stringify(config, null, 4));
}
function aliasPairMarker(node, anonId, email) {
return node.crypto.createHash("sha256").update(`${anonId}\0${email}`, "utf8").digest("hex");
}
function randomUserId(node) {
if (typeof node.crypto.randomUUID === "function") {
return node.crypto.randomUUID();
}
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
async function getOrCreateMem0UserId() {
var _a2;
const node = await getNodeFs();
if (!node) return null;
try {
const config = (_a2 = loadConfig(node)) != null ? _a2 : {};
if (typeof config.user_id === "string" && config.user_id) {
return config.user_id;
}
const userId = randomUserId(node);
config.user_id = userId;
writeConfig(node, config);
return userId;
} catch (e) {
return null;
}
}
async function readMem0AnonIds() {
const node = await getNodeFs();
if (!node) return null;
const config = loadConfig(node);
if (!config) return null;
const telemetry2 = config.telemetry && typeof config.telemetry === "object" ? config.telemetry : {};
return {
oss: typeof config.user_id === "string" ? config.user_id : void 0,
cli: typeof telemetry2.anonymous_id === "string" ? telemetry2.anonymous_id : void 0,
aliasedPairs: Array.isArray(telemetry2.aliased_pairs) ? telemetry2.aliased_pairs.filter(
(item) => typeof item === "string"
) : []
};
}
async function isMem0Aliased(anonId, email) {
if (!anonId || !email) return false;
const node = await getNodeFs();
if (!node) return false;
const config = loadConfig(node);
if (!config) return false;
const telemetry2 = config.telemetry && typeof config.telemetry === "object" ? config.telemetry : {};
const aliasedPairs = Array.isArray(telemetry2.aliased_pairs) ? telemetry2.aliased_pairs : [];
return aliasedPairs.includes(aliasPairMarker(node, anonId, email));
}
async function markMem0Aliased(anonId, email) {
var _a2;
const node = await getNodeFs();
if (!node) return;
try {
const config = (_a2 = loadConfig(node)) != null ? _a2 : {};
const telemetry2 = config.telemetry && typeof config.telemetry === "object" ? config.telemetry : {};
const aliasedPairs = Array.isArray(telemetry2.aliased_pairs) ? telemetry2.aliased_pairs : [];
const marker = aliasPairMarker(node, anonId, email);
if (!aliasedPairs.includes(marker)) {
aliasedPairs.push(marker);
}
telemetry2.aliased_pairs = aliasedPairs;
config.telemetry = telemetry2;
writeConfig(node, config);
} catch (e) {
}
}
// src/client/utils.ts
function camelToSnake(str) {
if (str === str.toUpperCase()) return str;
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
}
function snakeToCamel(str) {
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}
function camelToSnakeKeys(obj) {
if (obj === null || obj === void 0 || typeof obj !== "object") return obj;
if (Array.isArray(obj)) return obj.map(camelToSnakeKeys);
if (obj instanceof Date) return obj;
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
camelToSnake(key),
camelToSnakeKeys(value)
])
);
}
function snakeToCamelKeys(obj) {
if (obj === null || obj === void 0 || typeof obj !== "object") return obj;
if (Array.isArray(obj)) return obj.map(snakeToCamelKeys);
if (obj instanceof Date) return obj;
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
snakeToCamel(key),
snakeToCamelKeys(value)
])
);
}
// src/common/exceptions.ts
var MemoryError = class extends Error {
constructor(message, errorCode, options = {}) {
var _a2, _b;
super(message);
this.name = "MemoryError";
this.errorCode = errorCode;
this.details = (_a2 = options.details) != null ? _a2 : {};
this.suggestion = options.suggestion;
this.debugInfo = (_b = options.debugInfo) != null ? _b : {};
Object.setPrototypeOf(this, new.target.prototype);
}
};
var AuthenticationError = class extends MemoryError {
constructor(message, errorCode, options) {
super(message, errorCode, options);
this.name = "AuthenticationError";
}
};
var RateLimitError = class extends MemoryError {
constructor(message, errorCode, options) {
super(message, errorCode, options);
this.name = "RateLimitError";
}
};
var ValidationError = class extends MemoryError {
constructor(message, errorCode, options) {
super(message, errorCode, options);
this.name = "ValidationError";
}
};
var MemoryNotFoundError = class extends MemoryError {
constructor(message, errorCode, options) {
super(message, errorCode, options);
this.name = "MemoryNotFoundError";
}
};
var NetworkError = class extends MemoryError {
constructor(message, errorCode, options) {
super(message, errorCode, options);
this.name = "NetworkError";
}
};
var ConfigurationError = class extends MemoryError {
constructor(message, errorCode, options) {
super(message, errorCode, options);
this.name = "ConfigurationError";
}
};
var MemoryQuotaExceededError = class extends MemoryError {
constructor(message, errorCode, options) {
super(message, errorCode, options);
this.name = "MemoryQuotaExceededError";
}
};
var HTTP_STATUS_TO_EXCEPTION = {
400: ValidationError,
401: AuthenticationError,
403: AuthenticationError,
404: MemoryNotFoundError,
408: NetworkError,
409: ValidationError,
413: MemoryQuotaExceededError,
422: ValidationError,
429: RateLimitError,
500: MemoryError,
502: NetworkError,
503: NetworkError,
504: NetworkError
};
var HTTP_SUGGESTIONS = {
400: "Please check your request parameters and try again",
401: "Please check your API key and authentication credentials",
403: "You don't have permission to perform this operation",
404: "The requested resource was not found",
408: "Request timed out. Please try again",
409: "Resource conflict. Please check your request",
413: "Request too large. Please reduce the size of your request",
422: "Invalid request data. Please check your input",
429: "Rate limit exceeded. Please wait before making more requests",
500: "Internal server error. Please try again later",
502: "Service temporarily unavailable. Please try again later",
503: "Service unavailable. Please try again later",
504: "Gateway timeout. Please try again later"
};
function createExceptionFromResponse(statusCode, responseText, options = {}) {
var _a2, _b;
const ExceptionClass = (_a2 = HTTP_STATUS_TO_EXCEPTION[statusCode]) != null ? _a2 : MemoryError;
const errorCode = `HTTP_${statusCode}`;
const suggestion = (_b = HTTP_SUGGESTIONS[statusCode]) != null ? _b : "Please try again later";
return new ExceptionClass(
responseText || `HTTP ${statusCode} error`,
errorCode,
{ ...options, suggestion }
);
}
// src/client/mem0.ts
var ENTITY_PARAMS = [
"user_id",
"agent_id",
"app_id",
"run_id",
"userId",
"agentId",
"appId",
"runId"
];
function rejectTopLevelEntityParams(options, methodName) {
const invalidKeys = Object.keys(options != null ? options : {}).filter(
(k) => ENTITY_PARAMS.includes(k)
);
if (invalidKeys.length > 0) {
throw new Error(
`Top-level entity parameters [${invalidKeys.join(", ")}] are not supported in ${methodName}(). Use filters: { user_id: "..." } instead.`
);
}
}
var APIError = class extends Error {
constructor(message) {
super(message);
this.name = "APIError";
}
};
var MemoryClient = class {
_validateApiKey() {
if (!this.apiKey) {
throw new Error("Mem0 API key is required");
}
if (typeof this.apiKey !== "string") {
throw new Error("Mem0 API key must be a string");
}
if (this.apiKey.trim() === "") {
throw new Error("Mem0 API key cannot be empty");
}
}
constructor(options) {
this.apiKey = options.apiKey;
this.host = options.host || "https://api.mem0.ai";
this.organizationId = null;
this.projectId = null;
this.headers = {
Authorization: `Token ${this.apiKey}`,
"Content-Type": "application/json"
};
this.client = import_axios.default.create({
baseURL: this.host,
headers: { Authorization: `Token ${this.apiKey}` },
timeout: 6e4
});
this._validateApiKey();
this.telemetryId = "";
this._initializeClient();
}
async _initializeClient() {
try {
await this.ping();
if (!this.telemetryId) {
this.telemetryId = generateHash(this.apiKey);
}
await this._maybeAliasAnonToEmail();
captureClientEvent("init", this, {
client_type: "MemoryClient"
}).catch((error) => {
console.error("Failed to capture event:", error);
});
} catch (error) {
console.error("Failed to initialize client:", error);
await captureClientEvent("init_error", this, {
error: (error == null ? void 0 : error.message) || "Unknown error",
stack: (error == null ? void 0 : error.stack) || "No stack trace"
});
}
}
async _maybeAliasAnonToEmail() {
if (!isTelemetryEnabled()) return;
try {
const email = this.telemetryId;
if (!email || !email.includes("@")) return;
const sharedAnonId = await getOrCreateMem0UserId();
const anonIds = await readMem0AnonIds();
if (!anonIds && !sharedAnonId) return;
const candidates = [(anonIds == null ? void 0 : anonIds.oss) || sharedAnonId, anonIds == null ? void 0 : anonIds.cli].filter(
(id) => !!id && id !== email
);
const seen = /* @__PURE__ */ new Set();
for (const anonId of candidates) {
if (seen.has(anonId) || await isMem0Aliased(anonId, email)) continue;
seen.add(anonId);
if (await telemetry.captureIdentify(anonId, email)) {
await markMem0Aliased(anonId, email);
}
}
} catch (error) {
console.error("Failed to alias telemetry identity:", error);
}
}
_captureEvent(methodName, args) {
captureClientEvent(methodName, this, {
success: true,
args_count: args.length,
keys: args.length > 0 ? args[0] : []
}).catch((error) => {
console.error("Failed to capture event:", error);
});
}
async _fetchWithErrorHandling(url, options) {
const response = await fetch(url, {
...options,
headers: {
...options.headers,
Authorization: `Token ${this.apiKey}`,
"Mem0-User-ID": this.telemetryId
}
});
if (!response.ok) {
const errorData = await response.text();
throw createExceptionFromResponse(response.status, errorData);
}
const jsonResponse = await response.json();
return snakeToCamelKeys(jsonResponse);
}
_preparePayload(messages, options) {
const payload = {};
payload.messages = messages;
return camelToSnakeKeys({ ...payload, ...options });
}
_prepareParams(options) {
return Object.fromEntries(
Object.entries(options).filter(([_, v]) => v != null)
);
}
async ping() {
try {
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/ping/`,
{
method: "GET",
headers: {
Authorization: `Token ${this.apiKey}`
}
}
);
if (!response || typeof response !== "object") {
throw new APIError("Invalid response format from ping endpoint");
}
if (response.status !== "ok") {
throw new APIError(response.message || "API Key is invalid");
}
const { orgId, projectId, userEmail } = response;
if (orgId) this.organizationId = orgId;
if (projectId) this.projectId = projectId;
if (userEmail) this.telemetryId = userEmail;
} catch (error) {
if (error instanceof MemoryError || error instanceof APIError) {
throw error;
} else {
throw new APIError(
`Failed to ping server: ${error.message || "Unknown error"}`
);
}
}
}
async add(messages, options = {}) {
if (this.telemetryId === "") await this.ping();
const payload = this._preparePayload(messages, options);
const payloadKeys = Object.keys(payload);
this._captureEvent("add", [payloadKeys]);
const response = await this._fetchWithErrorHandling(
`${this.host}/v3/memories/add/`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify(payload)
}
);
return response;
}
async update(memoryId, {
text,
metadata,
timestamp
}) {
if (text === void 0 && metadata === void 0 && timestamp === void 0) {
throw new Error(
"At least one of text, metadata, or timestamp must be provided for update."
);
}
if (this.telemetryId === "") await this.ping();
const payload = {};
if (text !== void 0) payload.text = text;
if (metadata !== void 0) payload.metadata = metadata;
if (timestamp !== void 0) payload.timestamp = timestamp;
const payloadKeys = Object.keys(payload);
this._captureEvent("update", [payloadKeys]);
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/memories/${memoryId}/`,
{
method: "PUT",
headers: this.headers,
body: JSON.stringify(payload)
}
);
return response;
}
async get(memoryId) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("get", []);
return this._fetchWithErrorHandling(
`${this.host}/v1/memories/${memoryId}/`,
{
headers: this.headers
}
);
}
async getAll(options) {
rejectTopLevelEntityParams(options, "getAll");
if (this.telemetryId === "") await this.ping();
const payloadKeys = Object.keys(options || {});
this._captureEvent("get_all", [payloadKeys]);
const { page, pageSize, filters, ...rest } = options != null ? options : {};
const body = {
...camelToSnakeKeys(rest),
...filters && { filters }
};
let url = `${this.host}/v3/memories/`;
if (page && pageSize) {
url += `?page=${page}&page_size=${pageSize}`;
}
const response = await this._fetchWithErrorHandling(url, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body)
});
return response;
}
async search(query, options) {
rejectTopLevelEntityParams(options, "search");
if (this.telemetryId === "") await this.ping();
const payloadKeys = Object.keys(options || {});
this._captureEvent("search", [payloadKeys]);
const { filters, ...rest } = options != null ? options : {};
const payload = {
query,
output_format: "v1.1",
...camelToSnakeKeys(rest),
...filters && { filters }
};
const response = await this._fetchWithErrorHandling(
`${this.host}/v3/memories/search/`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify(payload)
}
);
return response;
}
async delete(memoryId) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("delete", []);
return this._fetchWithErrorHandling(
`${this.host}/v1/memories/${memoryId}/`,
{
method: "DELETE",
headers: this.headers
}
);
}
async deleteAll(options = {}) {
if (this.telemetryId === "") await this.ping();
const payloadKeys = Object.keys(options || {});
this._captureEvent("delete_all", [payloadKeys]);
const snakeOptions = camelToSnakeKeys(this._prepareParams(options));
const params = new URLSearchParams(snakeOptions);
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/memories/?${params}`,
{
method: "DELETE",
headers: this.headers
}
);
return response;
}
async history(memoryId) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("history", []);
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/memories/${memoryId}/history/`,
{
headers: this.headers
}
);
return response;
}
async users(options) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("users", []);
let url = `${this.host}/v1/entities/`;
const params = [];
if (options == null ? void 0 : options.page) params.push(`page=${options.page}`);
if (options == null ? void 0 : options.pageSize) params.push(`page_size=${options.pageSize}`);
if (params.length) url += `?${params.join("&")}`;
const response = await this._fetchWithErrorHandling(url, {
headers: this.headers
});
return response;
}
/**
* @deprecated The method should not be used, use `deleteUsers` instead. This will be removed in version 2.2.0.
*/
async deleteUser(data) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("delete_user", []);
if (!data.entity_type) {
data.entity_type = "user";
}
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/entities/${data.entity_type}/${data.entity_id}/`,
{
method: "DELETE",
headers: this.headers
}
);
return response;
}
async deleteUsers(params = {}) {
if (this.telemetryId === "") await this.ping();
let to_delete = [];
const { userId, agentId, appId, runId } = params;
if (userId) {
to_delete = [{ type: "user", name: userId }];
} else if (agentId) {
to_delete = [{ type: "agent", name: agentId }];
} else if (appId) {
to_delete = [{ type: "app", name: appId }];
} else if (runId) {
to_delete = [{ type: "run", name: runId }];
} else {
const entities = await this.users();
to_delete = entities.results.map((entity) => ({
type: entity.type,
name: entity.name
}));
}
if (to_delete.length === 0) {
throw new Error("No entities to delete");
}
for (const entity of to_delete) {
try {
await this.client.delete(`/v2/entities/${entity.type}/${entity.name}/`);
} catch (error) {
throw new APIError(
`Failed to delete ${entity.type} ${entity.name}: ${error.message}`
);
}
}
this._captureEvent("delete_users", [
{ userId, agentId, appId, runId, sync_type: "sync" }
]);
return {
message: userId || agentId || appId || runId ? "Entity deleted successfully." : "All users, agents, apps and runs deleted."
};
}
async batchUpdate(memories) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("batch_update", []);
const memoriesBody = memories.map((memory) => ({
memory_id: memory.memoryId,
text: memory.text
}));
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/batch/`,
{
method: "PUT",
headers: this.headers,
body: JSON.stringify({ memories: memoriesBody })
}
);
return response;
}
async batchDelete(memories) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("batch_delete", []);
const memoriesBody = memories.map((memory) => ({
memory_id: memory
}));
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/batch/`,
{
method: "DELETE",
headers: this.headers,
body: JSON.stringify({ memories: memoriesBody })
}
);
return response;
}
async getProject(options) {
if (this.telemetryId === "") await this.ping();
const payloadKeys = Object.keys(options || {});
this._captureEvent("get_project", [payloadKeys]);
const { fields } = options;
if (!(this.organizationId && this.projectId)) {
throw new Error(
"organizationId and projectId must be set to access instructions or categories"
);
}
const params = new URLSearchParams();
fields == null ? void 0 : fields.forEach((field) => params.append("fields", camelToSnake(field)));
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/?${params.toString()}`,
{
headers: this.headers
}
);
return response;
}
async updateProject(prompts) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("update_project", []);
if (!(this.organizationId && this.projectId)) {
throw new Error(
"organizationId and projectId must be set to update instructions or categories"
);
}
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/`,
{
method: "PATCH",
headers: this.headers,
body: JSON.stringify(camelToSnakeKeys(prompts))
}
);
return response;
}
// WebHooks
async getWebhooks(data) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("get_webhooks", []);
const project_id = (data == null ? void 0 : data.projectId) || this.projectId;
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/webhooks/projects/${project_id}/`,
{
headers: this.headers
}
);
return response;
}
async createWebhook(webhook) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("create_webhook", []);
const body = {
name: webhook.name,
url: webhook.url,
event_types: webhook.eventTypes
};
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/webhooks/projects/${this.projectId}/`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify(body)
}
);
return response;
}
async updateWebhook(webhook) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("update_webhook", []);
const body = {};
if (webhook.name != null) body.name = webhook.name;
if (webhook.url != null) body.url = webhook.url;
if (webhook.eventTypes != null) body.event_types = webhook.eventTypes;
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/webhooks/${webhook.webhookId}/`,
{
method: "PUT",
headers: this.headers,
body: JSON.stringify(body)
}
);
return response;
}
async deleteWebhook(data) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("delete_webhook", []);
const webhook_id = data.webhookId || data;
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/webhooks/${webhook_id}/`,
{
method: "DELETE",
headers: this.headers
}
);
return response;
}
async feedback(data) {
if (this.telemetryId === "") await this.ping();
const payloadKeys = Object.keys(data || {});
this._captureEvent("feedback", [payloadKeys]);
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/feedback/`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify(camelToSnakeKeys(data))
}
);
return response;
}
async createMemoryExport(data) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("create_memory_export", []);
if (!data.filters || !data.schema) {
throw new Error("Missing filters or schema");
}
const { filters, ...rest } = data;
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/exports/`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify({
...camelToSnakeKeys(rest),
filters
})
}
);
return response;
}
async getMemoryExport(data) {
if (this.telemetryId === "") await this.ping();
this._captureEvent("get_memory_export", []);
if (!data.memoryExportId && !data.filters) {
throw new Error("Missing memoryExportId or filters");
}
const { filters, ...rest } = data;
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/exports/get/`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify({
...camelToSnakeKeys(rest),
...filters && { filters }
})
}
);
return response;
}
};
// src/client/mem0.types.ts
var Feedback = /* @__PURE__ */ ((Feedback2) => {
Feedback2["POSITIVE"] = "POSITIVE";
Feedback2["NEGATIVE"] = "NEGATIVE";
Feedback2["VERY_NEGATIVE"] = "VERY_NEGATIVE";
return Feedback2;
})(Feedback || {});
var WebhookEvent = /* @__PURE__ */ ((WebhookEvent2) => {
WebhookEvent2["MEMORY_ADDED"] = "memory_add";
WebhookEvent2["MEMORY_UPDATED"] = "memory_update";
WebhookEvent2["MEMORY_DELETED"] = "memory_delete";
WebhookEvent2["MEMORY_CATEGORIZED"] = "memory_categorize";
return WebhookEvent2;
})(WebhookEvent || {});
// src/client/index.ts
var index_default = MemoryClient;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AuthenticationError,
ConfigurationError,
Feedback,
MemoryClient,
MemoryError,
MemoryNotFoundError,
MemoryQuotaExceededError,
NetworkError,
RateLimitError,
ValidationError,
WebhookEvent,
createExceptionFromResponse
});
//# sourceMappingURL=index.js.map