mem0ai 3.0.0-beta.0 → 3.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +41 -9
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +41 -9
- package/dist/index.mjs.map +1 -1
- package/dist/oss/index.d.mts +71 -97
- package/dist/oss/index.d.ts +71 -97
- package/dist/oss/index.js +2603 -1327
- package/dist/oss/index.js.map +1 -1
- package/dist/oss/index.mjs +2607 -1324
- package/dist/oss/index.mjs.map +1 -1
- package/package.json +4 -3
package/dist/index.d.mts
CHANGED
|
@@ -198,7 +198,9 @@ declare class MemoryClient {
|
|
|
198
198
|
}): Promise<Array<Memory>>;
|
|
199
199
|
get(memoryId: string): Promise<Memory>;
|
|
200
200
|
getAll(options?: GetAllMemoryOptions): Promise<Array<Memory>>;
|
|
201
|
-
search(query: string, options?: SearchMemoryOptions): Promise<
|
|
201
|
+
search(query: string, options?: SearchMemoryOptions): Promise<{
|
|
202
|
+
results: Array<Memory>;
|
|
203
|
+
}>;
|
|
202
204
|
delete(memoryId: string): Promise<{
|
|
203
205
|
message: string;
|
|
204
206
|
}>;
|
|
@@ -333,4 +335,4 @@ declare class MemoryQuotaExceededError extends MemoryError {
|
|
|
333
335
|
*/
|
|
334
336
|
declare function createExceptionFromResponse(statusCode: number, responseText: string, options?: Omit<MemoryErrorOptions, "suggestion">): MemoryError;
|
|
335
337
|
|
|
336
|
-
export { type AddMemoryOptions, type AllUsers, AuthenticationError, ConfigurationError, type CreateMemoryExportPayload, type DeleteAllMemoryOptions,
|
|
338
|
+
export { type AddMemoryOptions, type AllUsers, AuthenticationError, ConfigurationError, type CreateMemoryExportPayload, type DeleteAllMemoryOptions, Feedback, type FeedbackPayload, type GetAllMemoryOptions, type GetMemoryExportPayload, type Memory, MemoryClient, MemoryError, type MemoryErrorOptions, type MemoryHistory, MemoryNotFoundError, MemoryQuotaExceededError, type MemoryUpdateBody, type Message, type Messages, NetworkError, type ProjectOptions, type ProjectResponse, type PromptUpdatePayload, RateLimitError, type SearchMemoryOptions, type User, ValidationError, type Webhook, type WebhookCreatePayload, WebhookEvent, type WebhookUpdatePayload, createExceptionFromResponse, MemoryClient as default };
|
package/dist/index.d.ts
CHANGED
|
@@ -198,7 +198,9 @@ declare class MemoryClient {
|
|
|
198
198
|
}): Promise<Array<Memory>>;
|
|
199
199
|
get(memoryId: string): Promise<Memory>;
|
|
200
200
|
getAll(options?: GetAllMemoryOptions): Promise<Array<Memory>>;
|
|
201
|
-
search(query: string, options?: SearchMemoryOptions): Promise<
|
|
201
|
+
search(query: string, options?: SearchMemoryOptions): Promise<{
|
|
202
|
+
results: Array<Memory>;
|
|
203
|
+
}>;
|
|
202
204
|
delete(memoryId: string): Promise<{
|
|
203
205
|
message: string;
|
|
204
206
|
}>;
|
|
@@ -333,4 +335,4 @@ declare class MemoryQuotaExceededError extends MemoryError {
|
|
|
333
335
|
*/
|
|
334
336
|
declare function createExceptionFromResponse(statusCode: number, responseText: string, options?: Omit<MemoryErrorOptions, "suggestion">): MemoryError;
|
|
335
337
|
|
|
336
|
-
export { type AddMemoryOptions, type AllUsers, AuthenticationError, ConfigurationError, type CreateMemoryExportPayload, type DeleteAllMemoryOptions,
|
|
338
|
+
export { type AddMemoryOptions, type AllUsers, AuthenticationError, ConfigurationError, type CreateMemoryExportPayload, type DeleteAllMemoryOptions, Feedback, type FeedbackPayload, type GetAllMemoryOptions, type GetMemoryExportPayload, type Memory, MemoryClient, MemoryError, type MemoryErrorOptions, type MemoryHistory, MemoryNotFoundError, MemoryQuotaExceededError, type MemoryUpdateBody, type Message, type Messages, NetworkError, type ProjectOptions, type ProjectResponse, type PromptUpdatePayload, RateLimitError, type SearchMemoryOptions, type User, ValidationError, type Webhook, type WebhookCreatePayload, WebhookEvent, type WebhookUpdatePayload, createExceptionFromResponse, MemoryClient as default };
|
package/dist/index.js
CHANGED
|
@@ -252,6 +252,26 @@ function createExceptionFromResponse(statusCode, responseText, options = {}) {
|
|
|
252
252
|
}
|
|
253
253
|
|
|
254
254
|
// src/client/mem0.ts
|
|
255
|
+
var ENTITY_PARAMS = [
|
|
256
|
+
"user_id",
|
|
257
|
+
"agent_id",
|
|
258
|
+
"app_id",
|
|
259
|
+
"run_id",
|
|
260
|
+
"userId",
|
|
261
|
+
"agentId",
|
|
262
|
+
"appId",
|
|
263
|
+
"runId"
|
|
264
|
+
];
|
|
265
|
+
function rejectTopLevelEntityParams(options, methodName) {
|
|
266
|
+
const invalidKeys = Object.keys(options != null ? options : {}).filter(
|
|
267
|
+
(k) => ENTITY_PARAMS.includes(k)
|
|
268
|
+
);
|
|
269
|
+
if (invalidKeys.length > 0) {
|
|
270
|
+
throw new Error(
|
|
271
|
+
`Top-level entity parameters [${invalidKeys.join(", ")}] are not supported in ${methodName}(). Use filters: { user_id: "..." } instead.`
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
255
275
|
var APIError = class extends Error {
|
|
256
276
|
constructor(message) {
|
|
257
277
|
super(message);
|
|
@@ -379,7 +399,7 @@ var MemoryClient = class {
|
|
|
379
399
|
const payloadKeys = Object.keys(payload);
|
|
380
400
|
this._captureEvent("add", [payloadKeys]);
|
|
381
401
|
const response = await this._fetchWithErrorHandling(
|
|
382
|
-
`${this.host}/
|
|
402
|
+
`${this.host}/v3/memories/`,
|
|
383
403
|
{
|
|
384
404
|
method: "POST",
|
|
385
405
|
headers: this.headers,
|
|
@@ -427,13 +447,15 @@ var MemoryClient = class {
|
|
|
427
447
|
}
|
|
428
448
|
async getAll(options) {
|
|
429
449
|
var _a2;
|
|
450
|
+
rejectTopLevelEntityParams(options, "getAll");
|
|
430
451
|
if (this.telemetryId === "") await this.ping();
|
|
431
452
|
const payloadKeys = Object.keys(options || {});
|
|
432
453
|
this._captureEvent("get_all", [payloadKeys]);
|
|
433
|
-
const { page, pageSize, ...rest } = options != null ? options : {};
|
|
454
|
+
const { page, pageSize, filters, ...rest } = options != null ? options : {};
|
|
434
455
|
const body = {
|
|
435
456
|
output_format: "v1.1",
|
|
436
|
-
...camelToSnakeKeys(rest)
|
|
457
|
+
...camelToSnakeKeys(rest),
|
|
458
|
+
...filters && { filters }
|
|
437
459
|
};
|
|
438
460
|
let url = `${this.host}/v2/memories/`;
|
|
439
461
|
if (page && pageSize) {
|
|
@@ -447,24 +469,26 @@ var MemoryClient = class {
|
|
|
447
469
|
return Array.isArray(response) ? response : (_a2 = response == null ? void 0 : response.results) != null ? _a2 : response;
|
|
448
470
|
}
|
|
449
471
|
async search(query, options) {
|
|
450
|
-
|
|
472
|
+
rejectTopLevelEntityParams(options, "search");
|
|
451
473
|
if (this.telemetryId === "") await this.ping();
|
|
452
474
|
const payloadKeys = Object.keys(options || {});
|
|
453
475
|
this._captureEvent("search", [payloadKeys]);
|
|
476
|
+
const { filters, ...rest } = options != null ? options : {};
|
|
454
477
|
const payload = {
|
|
455
478
|
query,
|
|
456
479
|
output_format: "v1.1",
|
|
457
|
-
...camelToSnakeKeys(
|
|
480
|
+
...camelToSnakeKeys(rest),
|
|
481
|
+
...filters && { filters }
|
|
458
482
|
};
|
|
459
483
|
const response = await this._fetchWithErrorHandling(
|
|
460
|
-
`${this.host}/
|
|
484
|
+
`${this.host}/v3/memories/search/`,
|
|
461
485
|
{
|
|
462
486
|
method: "POST",
|
|
463
487
|
headers: this.headers,
|
|
464
488
|
body: JSON.stringify(payload)
|
|
465
489
|
}
|
|
466
490
|
);
|
|
467
|
-
return
|
|
491
|
+
return response;
|
|
468
492
|
}
|
|
469
493
|
async delete(memoryId) {
|
|
470
494
|
if (this.telemetryId === "") await this.ping();
|
|
@@ -724,12 +748,16 @@ var MemoryClient = class {
|
|
|
724
748
|
if (!data.filters || !data.schema) {
|
|
725
749
|
throw new Error("Missing filters or schema");
|
|
726
750
|
}
|
|
751
|
+
const { filters, ...rest } = data;
|
|
727
752
|
const response = await this._fetchWithErrorHandling(
|
|
728
753
|
`${this.host}/v1/exports/`,
|
|
729
754
|
{
|
|
730
755
|
method: "POST",
|
|
731
756
|
headers: this.headers,
|
|
732
|
-
body: JSON.stringify(
|
|
757
|
+
body: JSON.stringify({
|
|
758
|
+
...camelToSnakeKeys(rest),
|
|
759
|
+
filters
|
|
760
|
+
})
|
|
733
761
|
}
|
|
734
762
|
);
|
|
735
763
|
return response;
|
|
@@ -740,12 +768,16 @@ var MemoryClient = class {
|
|
|
740
768
|
if (!data.memoryExportId && !data.filters) {
|
|
741
769
|
throw new Error("Missing memoryExportId or filters");
|
|
742
770
|
}
|
|
771
|
+
const { filters, ...rest } = data;
|
|
743
772
|
const response = await this._fetchWithErrorHandling(
|
|
744
773
|
`${this.host}/v1/exports/get/`,
|
|
745
774
|
{
|
|
746
775
|
method: "POST",
|
|
747
776
|
headers: this.headers,
|
|
748
|
-
body: JSON.stringify(
|
|
777
|
+
body: JSON.stringify({
|
|
778
|
+
...camelToSnakeKeys(rest),
|
|
779
|
+
...filters && { filters }
|
|
780
|
+
})
|
|
749
781
|
}
|
|
750
782
|
);
|
|
751
783
|
return response;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/index.ts","../src/client/mem0.ts","../src/client/telemetry.ts","../src/client/utils.ts","../src/common/exceptions.ts","../src/client/mem0.types.ts"],"sourcesContent":["import { MemoryClient } from \"./mem0\";\nimport type * as MemoryTypes from \"./mem0.types\";\n\n// Re-export all types from mem0.types\nexport type {\n EntityOptions,\n AddMemoryOptions,\n SearchMemoryOptions,\n GetAllMemoryOptions,\n DeleteAllMemoryOptions,\n ProjectOptions,\n Memory,\n MemoryHistory,\n MemoryUpdateBody,\n ProjectResponse,\n PromptUpdatePayload,\n Webhook,\n WebhookCreatePayload,\n WebhookUpdatePayload,\n Messages,\n Message,\n AllUsers,\n User,\n FeedbackPayload,\n CreateMemoryExportPayload,\n GetMemoryExportPayload,\n} from \"./mem0.types\";\n\n// Re-export enums as values (not type-only)\nexport { Feedback, WebhookEvent } from \"./mem0.types\";\n\n// Export the main client\nexport { MemoryClient };\nexport default MemoryClient;\n\n// Export structured exceptions\nexport {\n MemoryError,\n AuthenticationError,\n RateLimitError,\n ValidationError,\n MemoryNotFoundError,\n NetworkError,\n ConfigurationError,\n MemoryQuotaExceededError,\n createExceptionFromResponse,\n} from \"../common/exceptions\";\n\nexport type { MemoryErrorOptions } from \"../common/exceptions\";\n","import axios from \"axios\";\nimport {\n AllUsers,\n ProjectOptions,\n Memory,\n MemoryHistory,\n AddMemoryOptions,\n SearchMemoryOptions,\n GetAllMemoryOptions,\n DeleteAllMemoryOptions,\n MemoryUpdateBody,\n ProjectResponse,\n PromptUpdatePayload,\n Webhook,\n WebhookCreatePayload,\n WebhookUpdatePayload,\n Message,\n FeedbackPayload,\n CreateMemoryExportPayload,\n GetMemoryExportPayload,\n} from \"./mem0.types\";\nimport { captureClientEvent, generateHash } from \"./telemetry\";\nimport { camelToSnake, camelToSnakeKeys, snakeToCamelKeys } from \"./utils\";\nimport { createExceptionFromResponse, MemoryError } from \"../common/exceptions\";\n\nclass APIError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"APIError\";\n }\n}\n\ninterface ClientOptions {\n apiKey: string;\n host?: string;\n}\n\nexport default class MemoryClient {\n apiKey: string;\n host: string;\n private organizationId: string | number | null;\n private projectId: string | number | null;\n headers: Record<string, string>;\n client: any;\n telemetryId: string;\n\n _validateApiKey(): any {\n if (!this.apiKey) {\n throw new Error(\"Mem0 API key is required\");\n }\n if (typeof this.apiKey !== \"string\") {\n throw new Error(\"Mem0 API key must be a string\");\n }\n if (this.apiKey.trim() === \"\") {\n throw new Error(\"Mem0 API key cannot be empty\");\n }\n }\n\n constructor(options: ClientOptions) {\n this.apiKey = options.apiKey;\n this.host = options.host || \"https://api.mem0.ai\";\n this.organizationId = null;\n this.projectId = null;\n\n this.headers = {\n Authorization: `Token ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n this.client = axios.create({\n baseURL: this.host,\n headers: { Authorization: `Token ${this.apiKey}` },\n timeout: 60000,\n });\n\n this._validateApiKey();\n this.telemetryId = \"\";\n this._initializeClient();\n }\n\n private async _initializeClient() {\n try {\n await this.ping();\n\n if (!this.telemetryId) {\n this.telemetryId = generateHash(this.apiKey);\n }\n\n captureClientEvent(\"init\", this, {\n client_type: \"MemoryClient\",\n }).catch((error: any) => {\n console.error(\"Failed to capture event:\", error);\n });\n } catch (error: any) {\n console.error(\"Failed to initialize client:\", error);\n await captureClientEvent(\"init_error\", this, {\n error: error?.message || \"Unknown error\",\n stack: error?.stack || \"No stack trace\",\n });\n }\n }\n\n private _captureEvent(methodName: string, args: any[]) {\n captureClientEvent(methodName, this, {\n success: true,\n args_count: args.length,\n keys: args.length > 0 ? args[0] : [],\n }).catch((error: any) => {\n console.error(\"Failed to capture event:\", error);\n });\n }\n\n async _fetchWithErrorHandling(url: string, options: any): Promise<any> {\n const response = await fetch(url, {\n ...options,\n headers: {\n ...options.headers,\n Authorization: `Token ${this.apiKey}`,\n \"Mem0-User-ID\": this.telemetryId,\n },\n });\n if (!response.ok) {\n const errorData = await response.text();\n throw createExceptionFromResponse(response.status, errorData);\n }\n const jsonResponse = await response.json();\n return snakeToCamelKeys(jsonResponse);\n }\n\n _preparePayload(\n messages: Array<Message>,\n options: Record<string, any>,\n ): object {\n const payload: any = {};\n payload.messages = messages;\n return camelToSnakeKeys({ ...payload, ...options });\n }\n\n _prepareParams(options: Record<string, any>): object {\n return Object.fromEntries(\n Object.entries(options).filter(([_, v]) => v != null),\n );\n }\n\n async ping(): Promise<void> {\n try {\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/ping/`,\n {\n method: \"GET\",\n headers: {\n Authorization: `Token ${this.apiKey}`,\n },\n },\n );\n\n if (!response || typeof response !== \"object\") {\n throw new APIError(\"Invalid response format from ping endpoint\");\n }\n\n if (response.status !== \"ok\") {\n throw new APIError(response.message || \"API Key is invalid\");\n }\n\n const { orgId, projectId, userEmail } = response;\n\n if (orgId) this.organizationId = orgId;\n if (projectId) this.projectId = projectId;\n if (userEmail) this.telemetryId = userEmail;\n } catch (error: any) {\n // Pass through structured exceptions and APIError\n if (error instanceof MemoryError || error instanceof APIError) {\n throw error;\n } else {\n throw new APIError(\n `Failed to ping server: ${error.message || \"Unknown error\"}`,\n );\n }\n }\n }\n\n async add(\n messages: Array<Message>,\n options: AddMemoryOptions & Record<string, any> = {},\n ): Promise<Array<Memory>> {\n if (this.telemetryId === \"\") await this.ping();\n\n const payload = this._preparePayload(messages, options);\n const payloadKeys = Object.keys(payload);\n this._captureEvent(\"add\", [payloadKeys]);\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/memories/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(payload),\n },\n );\n return response;\n }\n\n async update(\n memoryId: string,\n {\n text,\n metadata,\n timestamp,\n }: {\n text?: string;\n metadata?: Record<string, any>;\n timestamp?: number | string;\n },\n ): Promise<Array<Memory>> {\n if (\n text === undefined &&\n metadata === undefined &&\n timestamp === undefined\n ) {\n throw new Error(\n \"At least one of text, metadata, or timestamp must be provided for update.\",\n );\n }\n\n if (this.telemetryId === \"\") await this.ping();\n const payload: Record<string, any> = {};\n if (text !== undefined) payload.text = text;\n if (metadata !== undefined) payload.metadata = metadata;\n if (timestamp !== undefined) payload.timestamp = timestamp;\n\n const payloadKeys = Object.keys(payload);\n this._captureEvent(\"update\", [payloadKeys]);\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/memories/${memoryId}/`,\n {\n method: \"PUT\",\n headers: this.headers,\n body: JSON.stringify(payload),\n },\n );\n return response;\n }\n\n async get(memoryId: string): Promise<Memory> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"get\", []);\n return this._fetchWithErrorHandling(\n `${this.host}/v1/memories/${memoryId}/`,\n {\n headers: this.headers,\n },\n );\n }\n\n async getAll(options?: GetAllMemoryOptions): Promise<Array<Memory>> {\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(options || {});\n this._captureEvent(\"get_all\", [payloadKeys]);\n const { page, pageSize, ...rest } = options ?? {};\n const body: Record<string, any> = {\n output_format: \"v1.1\",\n ...camelToSnakeKeys(rest),\n };\n\n let url = `${this.host}/v2/memories/`;\n if (page && pageSize) {\n url += `?page=${page}&page_size=${pageSize}`;\n }\n\n const response = await this._fetchWithErrorHandling(url, {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(body),\n });\n // Unwrap v1.1 format: { results: [...] } → [...]\n return Array.isArray(response) ? response : (response?.results ?? response);\n }\n\n async search(\n query: string,\n options?: SearchMemoryOptions,\n ): Promise<Array<Memory>> {\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(options || {});\n this._captureEvent(\"search\", [payloadKeys]);\n const payload: Record<string, any> = {\n query,\n output_format: \"v1.1\",\n ...camelToSnakeKeys(options ?? {}),\n };\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v2/memories/search/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(payload),\n },\n );\n // Unwrap v1.1 format: { results: [...] } → [...]\n return Array.isArray(response) ? response : (response?.results ?? response);\n }\n\n async delete(memoryId: string): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"delete\", []);\n return this._fetchWithErrorHandling(\n `${this.host}/v1/memories/${memoryId}/`,\n {\n method: \"DELETE\",\n headers: this.headers,\n },\n );\n }\n\n async deleteAll(\n options: DeleteAllMemoryOptions = {},\n ): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(options || {});\n this._captureEvent(\"delete_all\", [payloadKeys]);\n const snakeOptions = camelToSnakeKeys(this._prepareParams(options));\n // @ts-ignore\n const params = new URLSearchParams(snakeOptions);\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/memories/?${params}`,\n {\n method: \"DELETE\",\n headers: this.headers,\n },\n );\n return response;\n }\n\n async history(memoryId: string): Promise<Array<MemoryHistory>> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"history\", []);\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/memories/${memoryId}/history/`,\n {\n headers: this.headers,\n },\n );\n return response;\n }\n\n async users(options?: {\n page?: number;\n pageSize?: number;\n }): Promise<AllUsers> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"users\", []);\n let url = `${this.host}/v1/entities/`;\n const params: string[] = [];\n if (options?.page) params.push(`page=${options.page}`);\n if (options?.pageSize) params.push(`page_size=${options.pageSize}`);\n if (params.length) url += `?${params.join(\"&\")}`;\n const response = await this._fetchWithErrorHandling(url, {\n headers: this.headers,\n });\n return response;\n }\n\n /**\n * @deprecated The method should not be used, use `deleteUsers` instead. This will be removed in version 2.2.0.\n */\n async deleteUser(data: {\n entity_id: number;\n entity_type: string;\n }): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"delete_user\", []);\n if (!data.entity_type) {\n data.entity_type = \"user\";\n }\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/entities/${data.entity_type}/${data.entity_id}/`,\n {\n method: \"DELETE\",\n headers: this.headers,\n },\n );\n return response;\n }\n\n async deleteUsers(\n params: {\n userId?: string;\n agentId?: string;\n appId?: string;\n runId?: string;\n } = {},\n ): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n\n let to_delete: Array<{ type: string; name: string }> = [];\n const { userId, agentId, appId, runId } = params;\n\n if (userId) {\n to_delete = [{ type: \"user\", name: userId }];\n } else if (agentId) {\n to_delete = [{ type: \"agent\", name: agentId }];\n } else if (appId) {\n to_delete = [{ type: \"app\", name: appId }];\n } else if (runId) {\n to_delete = [{ type: \"run\", name: runId }];\n } else {\n const entities = await this.users();\n to_delete = entities.results.map((entity) => ({\n type: entity.type,\n name: entity.name,\n }));\n }\n\n if (to_delete.length === 0) {\n throw new Error(\"No entities to delete\");\n }\n\n for (const entity of to_delete) {\n try {\n await this.client.delete(`/v2/entities/${entity.type}/${entity.name}/`);\n } catch (error: any) {\n throw new APIError(\n `Failed to delete ${entity.type} ${entity.name}: ${error.message}`,\n );\n }\n }\n\n this._captureEvent(\"delete_users\", [\n { userId, agentId, appId, runId, sync_type: \"sync\" },\n ]);\n\n return {\n message:\n userId || agentId || appId || runId\n ? \"Entity deleted successfully.\"\n : \"All users, agents, apps and runs deleted.\",\n };\n }\n\n async batchUpdate(memories: Array<MemoryUpdateBody>): Promise<string> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"batch_update\", []);\n const memoriesBody = memories.map((memory) => ({\n memory_id: memory.memoryId,\n text: memory.text,\n }));\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/batch/`,\n {\n method: \"PUT\",\n headers: this.headers,\n body: JSON.stringify({ memories: memoriesBody }),\n },\n );\n return response;\n }\n\n async batchDelete(memories: Array<string>): Promise<string> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"batch_delete\", []);\n const memoriesBody = memories.map((memory) => ({\n memory_id: memory,\n }));\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/batch/`,\n {\n method: \"DELETE\",\n headers: this.headers,\n body: JSON.stringify({ memories: memoriesBody }),\n },\n );\n return response;\n }\n\n async getProject(options: ProjectOptions): Promise<ProjectResponse> {\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(options || {});\n this._captureEvent(\"get_project\", [payloadKeys]);\n const { fields } = options;\n\n if (!(this.organizationId && this.projectId)) {\n throw new Error(\n \"organizationId and projectId must be set to access instructions or categories\",\n );\n }\n\n const params = new URLSearchParams();\n fields?.forEach((field) => params.append(\"fields\", camelToSnake(field)));\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/?${params.toString()}`,\n {\n headers: this.headers,\n },\n );\n return response;\n }\n\n async updateProject(\n prompts: PromptUpdatePayload,\n ): Promise<Record<string, any>> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"update_project\", []);\n if (!(this.organizationId && this.projectId)) {\n throw new Error(\n \"organizationId and projectId must be set to update instructions or categories\",\n );\n }\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/`,\n {\n method: \"PATCH\",\n headers: this.headers,\n body: JSON.stringify(camelToSnakeKeys(prompts)),\n },\n );\n return response;\n }\n\n // WebHooks\n async getWebhooks(data?: { projectId?: string }): Promise<Array<Webhook>> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"get_webhooks\", []);\n const project_id = data?.projectId || this.projectId;\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/webhooks/projects/${project_id}/`,\n {\n headers: this.headers,\n },\n );\n return response;\n }\n\n async createWebhook(webhook: WebhookCreatePayload): Promise<Webhook> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"create_webhook\", []);\n const body = {\n name: webhook.name,\n url: webhook.url,\n event_types: webhook.eventTypes,\n };\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/webhooks/projects/${this.projectId}/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(body),\n },\n );\n return response;\n }\n\n async updateWebhook(\n webhook: WebhookUpdatePayload,\n ): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"update_webhook\", []);\n const body: Record<string, any> = {};\n if (webhook.name != null) body.name = webhook.name;\n if (webhook.url != null) body.url = webhook.url;\n if (webhook.eventTypes != null) body.event_types = webhook.eventTypes;\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/webhooks/${webhook.webhookId}/`,\n {\n method: \"PUT\",\n headers: this.headers,\n body: JSON.stringify(body),\n },\n );\n return response;\n }\n\n async deleteWebhook(data: {\n webhookId: string;\n }): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"delete_webhook\", []);\n const webhook_id = data.webhookId || data;\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/webhooks/${webhook_id}/`,\n {\n method: \"DELETE\",\n headers: this.headers,\n },\n );\n return response;\n }\n\n async feedback(data: FeedbackPayload): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(data || {});\n this._captureEvent(\"feedback\", [payloadKeys]);\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/feedback/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(camelToSnakeKeys(data)),\n },\n );\n return response;\n }\n\n async createMemoryExport(\n data: CreateMemoryExportPayload,\n ): Promise<{ message: string; id: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"create_memory_export\", []);\n\n if (!data.filters || !data.schema) {\n throw new Error(\"Missing filters or schema\");\n }\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/exports/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(camelToSnakeKeys(data)),\n },\n );\n\n return response;\n }\n\n async getMemoryExport(\n data: GetMemoryExportPayload,\n ): Promise<{ message: string; id: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"get_memory_export\", []);\n\n if (!data.memoryExportId && !data.filters) {\n throw new Error(\"Missing memoryExportId or filters\");\n }\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/exports/get/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(camelToSnakeKeys(data)),\n },\n );\n return response;\n }\n}\n\nexport { MemoryClient };\n","// @ts-nocheck\nimport type { TelemetryClient, TelemetryOptions } from \"./telemetry.types\";\n\nlet version = \"2.1.36\";\n\n// Safely check for process.env in different environments\nlet MEM0_TELEMETRY = true;\ntry {\n MEM0_TELEMETRY = process?.env?.MEM0_TELEMETRY === \"false\" ? false : true;\n} catch (error) {}\nconst POSTHOG_API_KEY = \"phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX\";\nconst POSTHOG_HOST = \"https://us.i.posthog.com/i/v0/e/\";\n\n// Simple hash function using random strings\nfunction generateHash(input: string): string {\n const randomStr =\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15);\n return randomStr;\n}\n\nclass UnifiedTelemetry implements TelemetryClient {\n private apiKey: string;\n private host: string;\n\n constructor(projectApiKey: string, host: string) {\n this.apiKey = projectApiKey;\n this.host = host;\n }\n\n async captureEvent(distinctId: string, eventName: string, properties = {}) {\n if (!MEM0_TELEMETRY) return;\n\n const eventProperties = {\n client_version: version,\n timestamp: new Date().toISOString(),\n ...properties,\n $process_person_profile: false,\n $lib: \"posthog-node\",\n };\n\n const payload = {\n api_key: this.apiKey,\n distinct_id: distinctId,\n event: eventName,\n properties: eventProperties,\n };\n\n try {\n const response = await fetch(this.host, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n console.error(\"Telemetry event capture failed:\", await response.text());\n }\n } catch (error) {\n console.error(\"Telemetry event capture failed:\", error);\n }\n }\n\n async shutdown() {\n // No shutdown needed for direct API calls\n }\n}\n\nconst telemetry = new UnifiedTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);\n\nasync function captureClientEvent(\n eventName: string,\n instance: any,\n additionalData = {},\n) {\n if (!instance.telemetryId) {\n console.warn(\"No telemetry ID found for instance\");\n return;\n }\n\n const eventData = {\n function: `${instance.constructor.name}`,\n method: eventName,\n api_host: instance.host,\n timestamp: new Date().toISOString(),\n client_version: version,\n keys: additionalData?.keys || [],\n ...additionalData,\n };\n\n await telemetry.captureEvent(\n instance.telemetryId,\n `client.${eventName}`,\n eventData,\n );\n}\n\nexport { telemetry, captureClientEvent, generateHash };\n","/**\n * Converts a camelCase string to snake_case.\n */\nexport function camelToSnake(str: string): string {\n // Skip all-uppercase keys (e.g. OR, AND, NOT — logical operators)\n if (str === str.toUpperCase()) return str;\n return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n}\n\n/**\n * Converts a snake_case string to camelCase.\n */\nfunction snakeToCamel(str: string): string {\n return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n\n/**\n * Recursively converts all keys of an object from camelCase to snake_case.\n * Used for converting user-facing camelCase params to API snake_case payloads.\n */\nexport function camelToSnakeKeys(obj: any): any {\n if (obj === null || obj === undefined || typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map(camelToSnakeKeys);\n if (obj instanceof Date) return obj;\n\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [\n camelToSnake(key),\n camelToSnakeKeys(value),\n ]),\n );\n}\n\n/**\n * Recursively converts all keys of an object from snake_case to camelCase.\n * Used for converting API snake_case responses to user-facing camelCase.\n */\nexport function snakeToCamelKeys(obj: any): any {\n if (obj === null || obj === undefined || typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map(snakeToCamelKeys);\n if (obj instanceof Date) return obj;\n\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [\n snakeToCamel(key),\n snakeToCamelKeys(value),\n ]),\n );\n}\n","/**\n * Structured exception classes for mem0 TypeScript SDK.\n *\n * Provides specific, actionable exceptions with error codes, suggestions,\n * and debug information. Maps HTTP status codes to appropriate exception types.\n *\n * @example\n * ```typescript\n * import { RateLimitError, MemoryNotFoundError } from 'mem0ai'\n *\n * try {\n * await client.get(memoryId)\n * } catch (e) {\n * if (e instanceof MemoryNotFoundError) {\n * console.log(e.suggestion) // \"The requested resource was not found\"\n * } else if (e instanceof RateLimitError) {\n * await sleep(e.debugInfo.retryAfter ?? 60)\n * }\n * }\n * ```\n */\n\nexport interface MemoryErrorOptions {\n details?: Record<string, unknown>;\n suggestion?: string;\n debugInfo?: Record<string, unknown>;\n}\n\n/**\n * Base exception for all memory-related errors.\n *\n * Every mem0 exception includes an error code for programmatic handling,\n * optional details, a user-friendly suggestion, and debug information.\n */\nexport class MemoryError extends Error {\n readonly errorCode: string;\n readonly details: Record<string, unknown>;\n readonly suggestion?: string;\n readonly debugInfo: Record<string, unknown>;\n\n constructor(\n message: string,\n errorCode: string,\n options: MemoryErrorOptions = {},\n ) {\n super(message);\n this.name = \"MemoryError\";\n this.errorCode = errorCode;\n this.details = options.details ?? {};\n this.suggestion = options.suggestion;\n this.debugInfo = options.debugInfo ?? {};\n\n // Fix prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Raised when authentication fails (401, 403). */\nexport class AuthenticationError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"AuthenticationError\";\n }\n}\n\n/** Raised when rate limits are exceeded (429). */\nexport class RateLimitError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"RateLimitError\";\n }\n}\n\n/** Raised when input validation fails (400, 409, 422). */\nexport class ValidationError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"ValidationError\";\n }\n}\n\n/** Raised when a memory is not found (404). */\nexport class MemoryNotFoundError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"MemoryNotFoundError\";\n }\n}\n\n/** Raised when network connectivity issues occur (408, 502, 503, 504). */\nexport class NetworkError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"NetworkError\";\n }\n}\n\n/** Raised when client configuration is invalid. */\nexport class ConfigurationError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"ConfigurationError\";\n }\n}\n\n/** Raised when memory quota is exceeded (413). */\nexport class MemoryQuotaExceededError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"MemoryQuotaExceededError\";\n }\n}\n\n// ─── HTTP Status → Exception Mapping ─────────────────────\n\ntype MemoryErrorConstructor = new (\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n) => MemoryError;\n\nexport const HTTP_STATUS_TO_EXCEPTION: Record<number, MemoryErrorConstructor> =\n {\n 400: ValidationError,\n 401: AuthenticationError,\n 403: AuthenticationError,\n 404: MemoryNotFoundError,\n 408: NetworkError,\n 409: ValidationError,\n 413: MemoryQuotaExceededError,\n 422: ValidationError,\n 429: RateLimitError,\n 500: MemoryError,\n 502: NetworkError,\n 503: NetworkError,\n 504: NetworkError,\n };\n\nconst HTTP_SUGGESTIONS: Record<number, string> = {\n 400: \"Please check your request parameters and try again\",\n 401: \"Please check your API key and authentication credentials\",\n 403: \"You don't have permission to perform this operation\",\n 404: \"The requested resource was not found\",\n 408: \"Request timed out. Please try again\",\n 409: \"Resource conflict. Please check your request\",\n 413: \"Request too large. Please reduce the size of your request\",\n 422: \"Invalid request data. Please check your input\",\n 429: \"Rate limit exceeded. Please wait before making more requests\",\n 500: \"Internal server error. Please try again later\",\n 502: \"Service temporarily unavailable. Please try again later\",\n 503: \"Service unavailable. Please try again later\",\n 504: \"Gateway timeout. Please try again later\",\n};\n\n/**\n * Create an appropriate exception based on HTTP response status code.\n *\n * @param statusCode - HTTP status code from the response\n * @param responseText - Response body text\n * @param options - Additional error context (details, debugInfo)\n * @returns An instance of the appropriate MemoryError subclass\n */\nexport function createExceptionFromResponse(\n statusCode: number,\n responseText: string,\n options: Omit<MemoryErrorOptions, \"suggestion\"> = {},\n): MemoryError {\n const ExceptionClass = HTTP_STATUS_TO_EXCEPTION[statusCode] ?? MemoryError;\n const errorCode = `HTTP_${statusCode}`;\n const suggestion = HTTP_SUGGESTIONS[statusCode] ?? \"Please try again later\";\n\n return new ExceptionClass(\n responseText || `HTTP ${statusCode} error`,\n errorCode,\n { ...options, suggestion },\n );\n}\n","// ─── Entity Options (for add/delete — top-level identity) ───\nexport interface EntityOptions {\n userId?: string;\n agentId?: string;\n appId?: string;\n runId?: string;\n}\n\n// ─── Per-Method Options ─────────────────────────────────────\nexport interface AddMemoryOptions extends EntityOptions {\n metadata?: Record<string, any>;\n infer?: boolean;\n customCategories?: custom_categories[];\n customInstructions?: string;\n timestamp?: number;\n structuredDataSchema?: Record<string, any>;\n}\n\nexport interface SearchMemoryOptions {\n filters?: Record<string, any>;\n metadata?: Record<string, any>;\n topK?: number;\n threshold?: number;\n rerank?: boolean;\n fields?: string[];\n categories?: string[];\n}\n\nexport interface GetAllMemoryOptions {\n filters?: Record<string, any>;\n page?: number;\n pageSize?: number;\n startDate?: string;\n endDate?: string;\n categories?: string[];\n}\n\nexport interface DeleteAllMemoryOptions extends EntityOptions {}\n\n// ─── Project Options ────────────────────────────────────────\nexport interface ProjectOptions {\n fields?: string[];\n}\n\nexport interface PromptUpdatePayload {\n customInstructions?: string;\n customCategories?: custom_categories[];\n retrievalCriteria?: any[];\n version?: string;\n memoryDepth?: string | null;\n usecaseSetting?: string | number;\n multilingual?: boolean;\n [key: string]: any;\n}\n\n// ─── Enums ──────────────────────────────────────────────────\nexport enum Feedback {\n POSITIVE = \"POSITIVE\",\n NEGATIVE = \"NEGATIVE\",\n VERY_NEGATIVE = \"VERY_NEGATIVE\",\n}\n\n// ─── Message Types ──────────────────────────────────────────\nexport interface MultiModalMessages {\n type: \"image_url\";\n image_url: {\n url: string;\n };\n}\n\nexport interface Messages {\n role: \"user\" | \"assistant\";\n content: string | MultiModalMessages;\n}\n\nexport interface Message extends Messages {}\n\n// ─── Response Types (camelCase — converted from API snake_case) ─────\nexport interface MemoryData {\n memory: string;\n}\n\nenum Event {\n ADD = \"ADD\",\n UPDATE = \"UPDATE\",\n DELETE = \"DELETE\",\n NOOP = \"NOOP\",\n}\n\nexport interface Memory {\n id: string;\n messages?: Array<Messages>;\n event?: Event | string;\n data?: MemoryData | null;\n memory?: string;\n userId?: string;\n hash?: string;\n categories?: Array<string>;\n createdAt?: Date;\n updatedAt?: Date;\n memoryType?: string;\n score?: number;\n metadata?: any | null;\n owner?: string | null;\n agentId?: string | null;\n appId?: string | null;\n runId?: string | null;\n}\n\nexport interface MemoryHistory {\n id: string;\n memoryId: string;\n input: Array<Messages>;\n oldMemory: string | null;\n newMemory: string | null;\n userId: string;\n categories: Array<string>;\n event: Event | string;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface MemoryUpdateBody {\n memoryId: string;\n text: string;\n}\n\nexport interface User {\n id: string;\n name: string;\n createdAt: Date;\n updatedAt: Date;\n totalMemories: number;\n owner: string;\n type: string;\n}\n\nexport interface AllUsers {\n count: number;\n results: Array<User>;\n next: any;\n previous: any;\n}\n\nexport interface ProjectResponse {\n customInstructions?: string;\n customCategories?: string[];\n [key: string]: any;\n}\n\ninterface custom_categories {\n [key: string]: any;\n}\n\n// ─── Webhook Types ──────────────────────────────────────────\nexport enum WebhookEvent {\n MEMORY_ADDED = \"memory_add\",\n MEMORY_UPDATED = \"memory_update\",\n MEMORY_DELETED = \"memory_delete\",\n MEMORY_CATEGORIZED = \"memory_categorize\",\n}\n\nexport interface Webhook {\n webhookId?: string;\n name: string;\n url: string;\n project?: string;\n createdAt?: Date;\n updatedAt?: Date;\n isActive?: boolean;\n eventTypes?: WebhookEvent[];\n}\n\nexport interface WebhookCreatePayload {\n name: string;\n url: string;\n eventTypes: WebhookEvent[];\n}\n\nexport interface WebhookUpdatePayload {\n webhookId: string;\n name?: string;\n url?: string;\n eventTypes?: WebhookEvent[];\n}\n\n// ─── Feedback & Export Types ────────────────────────────────\nexport interface FeedbackPayload {\n memoryId: string;\n feedback?: Feedback | null;\n feedbackReason?: string | null;\n}\n\nexport interface CreateMemoryExportPayload {\n schema: Record<string, any>;\n filters: Record<string, any>;\n exportInstructions?: string;\n}\n\nexport interface GetMemoryExportPayload {\n filters?: Record<string, any>;\n memoryExportId?: string;\n}\n"],"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AAAA,cAAA,oBAAiB;AACjB,EAAAA,cAAA,oBAAiB;AACjB,EAAAA,cAAA,wBAAqB;AAJX,SAAAA;AAAA,GAAA;;;AL1HZ,IAAO,gBAAQ;","names":["_a","axios","_a","Feedback","WebhookEvent"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/index.ts","../src/client/mem0.ts","../src/client/telemetry.ts","../src/client/utils.ts","../src/common/exceptions.ts","../src/client/mem0.types.ts"],"sourcesContent":["import { MemoryClient } from \"./mem0\";\nimport type * as MemoryTypes from \"./mem0.types\";\n\n// Re-export all types from mem0.types\nexport type {\n AddMemoryOptions,\n SearchMemoryOptions,\n GetAllMemoryOptions,\n DeleteAllMemoryOptions,\n ProjectOptions,\n Memory,\n MemoryHistory,\n MemoryUpdateBody,\n ProjectResponse,\n PromptUpdatePayload,\n Webhook,\n WebhookCreatePayload,\n WebhookUpdatePayload,\n Messages,\n Message,\n AllUsers,\n User,\n FeedbackPayload,\n CreateMemoryExportPayload,\n GetMemoryExportPayload,\n} from \"./mem0.types\";\n\n// Re-export enums as values (not type-only)\nexport { Feedback, WebhookEvent } from \"./mem0.types\";\n\n// Export the main client\nexport { MemoryClient };\nexport default MemoryClient;\n\n// Export structured exceptions\nexport {\n MemoryError,\n AuthenticationError,\n RateLimitError,\n ValidationError,\n MemoryNotFoundError,\n NetworkError,\n ConfigurationError,\n MemoryQuotaExceededError,\n createExceptionFromResponse,\n} from \"../common/exceptions\";\n\nexport type { MemoryErrorOptions } from \"../common/exceptions\";\n","import axios from \"axios\";\nimport {\n AllUsers,\n ProjectOptions,\n Memory,\n MemoryHistory,\n AddMemoryOptions,\n SearchMemoryOptions,\n GetAllMemoryOptions,\n DeleteAllMemoryOptions,\n MemoryUpdateBody,\n ProjectResponse,\n PromptUpdatePayload,\n Webhook,\n WebhookCreatePayload,\n WebhookUpdatePayload,\n Message,\n FeedbackPayload,\n CreateMemoryExportPayload,\n GetMemoryExportPayload,\n} from \"./mem0.types\";\nimport { captureClientEvent, generateHash } from \"./telemetry\";\nimport { camelToSnake, camelToSnakeKeys, snakeToCamelKeys } from \"./utils\";\nimport { createExceptionFromResponse, MemoryError } from \"../common/exceptions\";\n\n// Entity params that must be passed via filters - check both snake_case and camelCase\nconst ENTITY_PARAMS = [\n \"user_id\",\n \"agent_id\",\n \"app_id\",\n \"run_id\",\n \"userId\",\n \"agentId\",\n \"appId\",\n \"runId\",\n];\n\n/**\n * Validates that no top-level entity parameters are passed.\n * @throws Error if entity params are found at top level\n */\nfunction rejectTopLevelEntityParams(\n options: Record<string, any> | undefined,\n methodName: string,\n): void {\n const invalidKeys = Object.keys(options ?? {}).filter((k) =>\n ENTITY_PARAMS.includes(k),\n );\n if (invalidKeys.length > 0) {\n throw new Error(\n `Top-level entity parameters [${invalidKeys.join(\", \")}] are not supported in ${methodName}(). ` +\n `Use filters: { user_id: \"...\" } instead.`,\n );\n }\n}\n\nclass APIError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"APIError\";\n }\n}\n\ninterface ClientOptions {\n apiKey: string;\n host?: string;\n}\n\nexport default class MemoryClient {\n apiKey: string;\n host: string;\n private organizationId: string | number | null;\n private projectId: string | number | null;\n headers: Record<string, string>;\n client: any;\n telemetryId: string;\n\n _validateApiKey(): any {\n if (!this.apiKey) {\n throw new Error(\"Mem0 API key is required\");\n }\n if (typeof this.apiKey !== \"string\") {\n throw new Error(\"Mem0 API key must be a string\");\n }\n if (this.apiKey.trim() === \"\") {\n throw new Error(\"Mem0 API key cannot be empty\");\n }\n }\n\n constructor(options: ClientOptions) {\n this.apiKey = options.apiKey;\n this.host = options.host || \"https://api.mem0.ai\";\n this.organizationId = null;\n this.projectId = null;\n\n this.headers = {\n Authorization: `Token ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n this.client = axios.create({\n baseURL: this.host,\n headers: { Authorization: `Token ${this.apiKey}` },\n timeout: 60000,\n });\n\n this._validateApiKey();\n this.telemetryId = \"\";\n this._initializeClient();\n }\n\n private async _initializeClient() {\n try {\n await this.ping();\n\n if (!this.telemetryId) {\n this.telemetryId = generateHash(this.apiKey);\n }\n\n captureClientEvent(\"init\", this, {\n client_type: \"MemoryClient\",\n }).catch((error: any) => {\n console.error(\"Failed to capture event:\", error);\n });\n } catch (error: any) {\n console.error(\"Failed to initialize client:\", error);\n await captureClientEvent(\"init_error\", this, {\n error: error?.message || \"Unknown error\",\n stack: error?.stack || \"No stack trace\",\n });\n }\n }\n\n private _captureEvent(methodName: string, args: any[]) {\n captureClientEvent(methodName, this, {\n success: true,\n args_count: args.length,\n keys: args.length > 0 ? args[0] : [],\n }).catch((error: any) => {\n console.error(\"Failed to capture event:\", error);\n });\n }\n\n async _fetchWithErrorHandling(url: string, options: any): Promise<any> {\n const response = await fetch(url, {\n ...options,\n headers: {\n ...options.headers,\n Authorization: `Token ${this.apiKey}`,\n \"Mem0-User-ID\": this.telemetryId,\n },\n });\n if (!response.ok) {\n const errorData = await response.text();\n throw createExceptionFromResponse(response.status, errorData);\n }\n const jsonResponse = await response.json();\n return snakeToCamelKeys(jsonResponse);\n }\n\n _preparePayload(\n messages: Array<Message>,\n options: Record<string, any>,\n ): object {\n const payload: any = {};\n payload.messages = messages;\n return camelToSnakeKeys({ ...payload, ...options });\n }\n\n _prepareParams(options: Record<string, any>): object {\n return Object.fromEntries(\n Object.entries(options).filter(([_, v]) => v != null),\n );\n }\n\n async ping(): Promise<void> {\n try {\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/ping/`,\n {\n method: \"GET\",\n headers: {\n Authorization: `Token ${this.apiKey}`,\n },\n },\n );\n\n if (!response || typeof response !== \"object\") {\n throw new APIError(\"Invalid response format from ping endpoint\");\n }\n\n if (response.status !== \"ok\") {\n throw new APIError(response.message || \"API Key is invalid\");\n }\n\n const { orgId, projectId, userEmail } = response;\n\n if (orgId) this.organizationId = orgId;\n if (projectId) this.projectId = projectId;\n if (userEmail) this.telemetryId = userEmail;\n } catch (error: any) {\n // Pass through structured exceptions and APIError\n if (error instanceof MemoryError || error instanceof APIError) {\n throw error;\n } else {\n throw new APIError(\n `Failed to ping server: ${error.message || \"Unknown error\"}`,\n );\n }\n }\n }\n\n async add(\n messages: Array<Message>,\n options: AddMemoryOptions & Record<string, any> = {},\n ): Promise<Array<Memory>> {\n if (this.telemetryId === \"\") await this.ping();\n\n const payload = this._preparePayload(messages, options);\n const payloadKeys = Object.keys(payload);\n this._captureEvent(\"add\", [payloadKeys]);\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v3/memories/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(payload),\n },\n );\n return response;\n }\n\n async update(\n memoryId: string,\n {\n text,\n metadata,\n timestamp,\n }: {\n text?: string;\n metadata?: Record<string, any>;\n timestamp?: number | string;\n },\n ): Promise<Array<Memory>> {\n if (\n text === undefined &&\n metadata === undefined &&\n timestamp === undefined\n ) {\n throw new Error(\n \"At least one of text, metadata, or timestamp must be provided for update.\",\n );\n }\n\n if (this.telemetryId === \"\") await this.ping();\n const payload: Record<string, any> = {};\n if (text !== undefined) payload.text = text;\n if (metadata !== undefined) payload.metadata = metadata;\n if (timestamp !== undefined) payload.timestamp = timestamp;\n\n const payloadKeys = Object.keys(payload);\n this._captureEvent(\"update\", [payloadKeys]);\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/memories/${memoryId}/`,\n {\n method: \"PUT\",\n headers: this.headers,\n body: JSON.stringify(payload),\n },\n );\n return response;\n }\n\n async get(memoryId: string): Promise<Memory> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"get\", []);\n return this._fetchWithErrorHandling(\n `${this.host}/v1/memories/${memoryId}/`,\n {\n headers: this.headers,\n },\n );\n }\n\n async getAll(options?: GetAllMemoryOptions): Promise<Array<Memory>> {\n // Reject top-level entity params - must use filters instead\n rejectTopLevelEntityParams(options as Record<string, any>, \"getAll\");\n\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(options || {});\n this._captureEvent(\"get_all\", [payloadKeys]);\n const { page, pageSize, filters, ...rest } = options ?? {};\n const body: Record<string, any> = {\n output_format: \"v1.1\",\n ...camelToSnakeKeys(rest),\n ...(filters && { filters }),\n };\n\n let url = `${this.host}/v2/memories/`;\n if (page && pageSize) {\n url += `?page=${page}&page_size=${pageSize}`;\n }\n\n const response = await this._fetchWithErrorHandling(url, {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(body),\n });\n return Array.isArray(response) ? response : (response?.results ?? response);\n }\n\n async search(\n query: string,\n options?: SearchMemoryOptions,\n ): Promise<{ results: Array<Memory> }> {\n // Reject top-level entity params - must use filters instead\n rejectTopLevelEntityParams(options as Record<string, any>, \"search\");\n\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(options || {});\n this._captureEvent(\"search\", [payloadKeys]);\n const { filters, ...rest } = options ?? {};\n const payload: Record<string, any> = {\n query,\n output_format: \"v1.1\",\n ...camelToSnakeKeys(rest),\n ...(filters && { filters }),\n };\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v3/memories/search/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(payload),\n },\n );\n return response;\n }\n\n async delete(memoryId: string): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"delete\", []);\n return this._fetchWithErrorHandling(\n `${this.host}/v1/memories/${memoryId}/`,\n {\n method: \"DELETE\",\n headers: this.headers,\n },\n );\n }\n\n async deleteAll(\n options: DeleteAllMemoryOptions = {},\n ): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(options || {});\n this._captureEvent(\"delete_all\", [payloadKeys]);\n const snakeOptions = camelToSnakeKeys(this._prepareParams(options));\n // @ts-ignore\n const params = new URLSearchParams(snakeOptions);\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/memories/?${params}`,\n {\n method: \"DELETE\",\n headers: this.headers,\n },\n );\n return response;\n }\n\n async history(memoryId: string): Promise<Array<MemoryHistory>> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"history\", []);\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/memories/${memoryId}/history/`,\n {\n headers: this.headers,\n },\n );\n return response;\n }\n\n async users(options?: {\n page?: number;\n pageSize?: number;\n }): Promise<AllUsers> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"users\", []);\n let url = `${this.host}/v1/entities/`;\n const params: string[] = [];\n if (options?.page) params.push(`page=${options.page}`);\n if (options?.pageSize) params.push(`page_size=${options.pageSize}`);\n if (params.length) url += `?${params.join(\"&\")}`;\n const response = await this._fetchWithErrorHandling(url, {\n headers: this.headers,\n });\n return response;\n }\n\n /**\n * @deprecated The method should not be used, use `deleteUsers` instead. This will be removed in version 2.2.0.\n */\n async deleteUser(data: {\n entity_id: number;\n entity_type: string;\n }): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"delete_user\", []);\n if (!data.entity_type) {\n data.entity_type = \"user\";\n }\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/entities/${data.entity_type}/${data.entity_id}/`,\n {\n method: \"DELETE\",\n headers: this.headers,\n },\n );\n return response;\n }\n\n async deleteUsers(\n params: {\n userId?: string;\n agentId?: string;\n appId?: string;\n runId?: string;\n } = {},\n ): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n\n let to_delete: Array<{ type: string; name: string }> = [];\n const { userId, agentId, appId, runId } = params;\n\n if (userId) {\n to_delete = [{ type: \"user\", name: userId }];\n } else if (agentId) {\n to_delete = [{ type: \"agent\", name: agentId }];\n } else if (appId) {\n to_delete = [{ type: \"app\", name: appId }];\n } else if (runId) {\n to_delete = [{ type: \"run\", name: runId }];\n } else {\n const entities = await this.users();\n to_delete = entities.results.map((entity) => ({\n type: entity.type,\n name: entity.name,\n }));\n }\n\n if (to_delete.length === 0) {\n throw new Error(\"No entities to delete\");\n }\n\n for (const entity of to_delete) {\n try {\n await this.client.delete(`/v2/entities/${entity.type}/${entity.name}/`);\n } catch (error: any) {\n throw new APIError(\n `Failed to delete ${entity.type} ${entity.name}: ${error.message}`,\n );\n }\n }\n\n this._captureEvent(\"delete_users\", [\n { userId, agentId, appId, runId, sync_type: \"sync\" },\n ]);\n\n return {\n message:\n userId || agentId || appId || runId\n ? \"Entity deleted successfully.\"\n : \"All users, agents, apps and runs deleted.\",\n };\n }\n\n async batchUpdate(memories: Array<MemoryUpdateBody>): Promise<string> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"batch_update\", []);\n const memoriesBody = memories.map((memory) => ({\n memory_id: memory.memoryId,\n text: memory.text,\n }));\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/batch/`,\n {\n method: \"PUT\",\n headers: this.headers,\n body: JSON.stringify({ memories: memoriesBody }),\n },\n );\n return response;\n }\n\n async batchDelete(memories: Array<string>): Promise<string> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"batch_delete\", []);\n const memoriesBody = memories.map((memory) => ({\n memory_id: memory,\n }));\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/batch/`,\n {\n method: \"DELETE\",\n headers: this.headers,\n body: JSON.stringify({ memories: memoriesBody }),\n },\n );\n return response;\n }\n\n async getProject(options: ProjectOptions): Promise<ProjectResponse> {\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(options || {});\n this._captureEvent(\"get_project\", [payloadKeys]);\n const { fields } = options;\n\n if (!(this.organizationId && this.projectId)) {\n throw new Error(\n \"organizationId and projectId must be set to access instructions or categories\",\n );\n }\n\n const params = new URLSearchParams();\n fields?.forEach((field) => params.append(\"fields\", camelToSnake(field)));\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/?${params.toString()}`,\n {\n headers: this.headers,\n },\n );\n return response;\n }\n\n async updateProject(\n prompts: PromptUpdatePayload,\n ): Promise<Record<string, any>> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"update_project\", []);\n if (!(this.organizationId && this.projectId)) {\n throw new Error(\n \"organizationId and projectId must be set to update instructions or categories\",\n );\n }\n\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/`,\n {\n method: \"PATCH\",\n headers: this.headers,\n body: JSON.stringify(camelToSnakeKeys(prompts)),\n },\n );\n return response;\n }\n\n // WebHooks\n async getWebhooks(data?: { projectId?: string }): Promise<Array<Webhook>> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"get_webhooks\", []);\n const project_id = data?.projectId || this.projectId;\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/webhooks/projects/${project_id}/`,\n {\n headers: this.headers,\n },\n );\n return response;\n }\n\n async createWebhook(webhook: WebhookCreatePayload): Promise<Webhook> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"create_webhook\", []);\n const body = {\n name: webhook.name,\n url: webhook.url,\n event_types: webhook.eventTypes,\n };\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/webhooks/projects/${this.projectId}/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(body),\n },\n );\n return response;\n }\n\n async updateWebhook(\n webhook: WebhookUpdatePayload,\n ): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"update_webhook\", []);\n const body: Record<string, any> = {};\n if (webhook.name != null) body.name = webhook.name;\n if (webhook.url != null) body.url = webhook.url;\n if (webhook.eventTypes != null) body.event_types = webhook.eventTypes;\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/webhooks/${webhook.webhookId}/`,\n {\n method: \"PUT\",\n headers: this.headers,\n body: JSON.stringify(body),\n },\n );\n return response;\n }\n\n async deleteWebhook(data: {\n webhookId: string;\n }): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"delete_webhook\", []);\n const webhook_id = data.webhookId || data;\n const response = await this._fetchWithErrorHandling(\n `${this.host}/api/v1/webhooks/${webhook_id}/`,\n {\n method: \"DELETE\",\n headers: this.headers,\n },\n );\n return response;\n }\n\n async feedback(data: FeedbackPayload): Promise<{ message: string }> {\n if (this.telemetryId === \"\") await this.ping();\n const payloadKeys = Object.keys(data || {});\n this._captureEvent(\"feedback\", [payloadKeys]);\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/feedback/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(camelToSnakeKeys(data)),\n },\n );\n return response;\n }\n\n async createMemoryExport(\n data: CreateMemoryExportPayload,\n ): Promise<{ message: string; id: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"create_memory_export\", []);\n\n if (!data.filters || !data.schema) {\n throw new Error(\"Missing filters or schema\");\n }\n\n const { filters, ...rest } = data;\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/exports/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify({\n ...camelToSnakeKeys(rest),\n filters,\n }),\n },\n );\n\n return response;\n }\n\n async getMemoryExport(\n data: GetMemoryExportPayload,\n ): Promise<{ message: string; id: string }> {\n if (this.telemetryId === \"\") await this.ping();\n this._captureEvent(\"get_memory_export\", []);\n\n if (!data.memoryExportId && !data.filters) {\n throw new Error(\"Missing memoryExportId or filters\");\n }\n\n const { filters, ...rest } = data;\n const response = await this._fetchWithErrorHandling(\n `${this.host}/v1/exports/get/`,\n {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify({\n ...camelToSnakeKeys(rest),\n ...(filters && { filters }),\n }),\n },\n );\n return response;\n }\n}\n\nexport { MemoryClient };\n","// @ts-nocheck\nimport type { TelemetryClient, TelemetryOptions } from \"./telemetry.types\";\n\nlet version = \"2.1.36\";\n\n// Safely check for process.env in different environments\nlet MEM0_TELEMETRY = true;\ntry {\n MEM0_TELEMETRY = process?.env?.MEM0_TELEMETRY === \"false\" ? false : true;\n} catch (error) {}\nconst POSTHOG_API_KEY = \"phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX\";\nconst POSTHOG_HOST = \"https://us.i.posthog.com/i/v0/e/\";\n\n// Simple hash function using random strings\nfunction generateHash(input: string): string {\n const randomStr =\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15);\n return randomStr;\n}\n\nclass UnifiedTelemetry implements TelemetryClient {\n private apiKey: string;\n private host: string;\n\n constructor(projectApiKey: string, host: string) {\n this.apiKey = projectApiKey;\n this.host = host;\n }\n\n async captureEvent(distinctId: string, eventName: string, properties = {}) {\n if (!MEM0_TELEMETRY) return;\n\n const eventProperties = {\n client_version: version,\n timestamp: new Date().toISOString(),\n ...properties,\n $process_person_profile: false,\n $lib: \"posthog-node\",\n };\n\n const payload = {\n api_key: this.apiKey,\n distinct_id: distinctId,\n event: eventName,\n properties: eventProperties,\n };\n\n try {\n const response = await fetch(this.host, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n console.error(\"Telemetry event capture failed:\", await response.text());\n }\n } catch (error) {\n console.error(\"Telemetry event capture failed:\", error);\n }\n }\n\n async shutdown() {\n // No shutdown needed for direct API calls\n }\n}\n\nconst telemetry = new UnifiedTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);\n\nasync function captureClientEvent(\n eventName: string,\n instance: any,\n additionalData = {},\n) {\n if (!instance.telemetryId) {\n console.warn(\"No telemetry ID found for instance\");\n return;\n }\n\n const eventData = {\n function: `${instance.constructor.name}`,\n method: eventName,\n api_host: instance.host,\n timestamp: new Date().toISOString(),\n client_version: version,\n keys: additionalData?.keys || [],\n ...additionalData,\n };\n\n await telemetry.captureEvent(\n instance.telemetryId,\n `client.${eventName}`,\n eventData,\n );\n}\n\nexport { telemetry, captureClientEvent, generateHash };\n","/**\n * Converts a camelCase string to snake_case.\n */\nexport function camelToSnake(str: string): string {\n // Skip all-uppercase keys (e.g. OR, AND, NOT — logical operators)\n if (str === str.toUpperCase()) return str;\n return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n}\n\n/**\n * Converts a snake_case string to camelCase.\n */\nfunction snakeToCamel(str: string): string {\n return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n\n/**\n * Recursively converts all keys of an object from camelCase to snake_case.\n * Used for converting user-facing camelCase params to API snake_case payloads.\n */\nexport function camelToSnakeKeys(obj: any): any {\n if (obj === null || obj === undefined || typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map(camelToSnakeKeys);\n if (obj instanceof Date) return obj;\n\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [\n camelToSnake(key),\n camelToSnakeKeys(value),\n ]),\n );\n}\n\n/**\n * Recursively converts all keys of an object from snake_case to camelCase.\n * Used for converting API snake_case responses to user-facing camelCase.\n */\nexport function snakeToCamelKeys(obj: any): any {\n if (obj === null || obj === undefined || typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map(snakeToCamelKeys);\n if (obj instanceof Date) return obj;\n\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [\n snakeToCamel(key),\n snakeToCamelKeys(value),\n ]),\n );\n}\n","/**\n * Structured exception classes for mem0 TypeScript SDK.\n *\n * Provides specific, actionable exceptions with error codes, suggestions,\n * and debug information. Maps HTTP status codes to appropriate exception types.\n *\n * @example\n * ```typescript\n * import { RateLimitError, MemoryNotFoundError } from 'mem0ai'\n *\n * try {\n * await client.get(memoryId)\n * } catch (e) {\n * if (e instanceof MemoryNotFoundError) {\n * console.log(e.suggestion) // \"The requested resource was not found\"\n * } else if (e instanceof RateLimitError) {\n * await sleep(e.debugInfo.retryAfter ?? 60)\n * }\n * }\n * ```\n */\n\nexport interface MemoryErrorOptions {\n details?: Record<string, unknown>;\n suggestion?: string;\n debugInfo?: Record<string, unknown>;\n}\n\n/**\n * Base exception for all memory-related errors.\n *\n * Every mem0 exception includes an error code for programmatic handling,\n * optional details, a user-friendly suggestion, and debug information.\n */\nexport class MemoryError extends Error {\n readonly errorCode: string;\n readonly details: Record<string, unknown>;\n readonly suggestion?: string;\n readonly debugInfo: Record<string, unknown>;\n\n constructor(\n message: string,\n errorCode: string,\n options: MemoryErrorOptions = {},\n ) {\n super(message);\n this.name = \"MemoryError\";\n this.errorCode = errorCode;\n this.details = options.details ?? {};\n this.suggestion = options.suggestion;\n this.debugInfo = options.debugInfo ?? {};\n\n // Fix prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Raised when authentication fails (401, 403). */\nexport class AuthenticationError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"AuthenticationError\";\n }\n}\n\n/** Raised when rate limits are exceeded (429). */\nexport class RateLimitError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"RateLimitError\";\n }\n}\n\n/** Raised when input validation fails (400, 409, 422). */\nexport class ValidationError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"ValidationError\";\n }\n}\n\n/** Raised when a memory is not found (404). */\nexport class MemoryNotFoundError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"MemoryNotFoundError\";\n }\n}\n\n/** Raised when network connectivity issues occur (408, 502, 503, 504). */\nexport class NetworkError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"NetworkError\";\n }\n}\n\n/** Raised when client configuration is invalid. */\nexport class ConfigurationError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"ConfigurationError\";\n }\n}\n\n/** Raised when memory quota is exceeded (413). */\nexport class MemoryQuotaExceededError extends MemoryError {\n constructor(\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n ) {\n super(message, errorCode, options);\n this.name = \"MemoryQuotaExceededError\";\n }\n}\n\n// ─── HTTP Status → Exception Mapping ─────────────────────\n\ntype MemoryErrorConstructor = new (\n message: string,\n errorCode: string,\n options?: MemoryErrorOptions,\n) => MemoryError;\n\nexport const HTTP_STATUS_TO_EXCEPTION: Record<number, MemoryErrorConstructor> =\n {\n 400: ValidationError,\n 401: AuthenticationError,\n 403: AuthenticationError,\n 404: MemoryNotFoundError,\n 408: NetworkError,\n 409: ValidationError,\n 413: MemoryQuotaExceededError,\n 422: ValidationError,\n 429: RateLimitError,\n 500: MemoryError,\n 502: NetworkError,\n 503: NetworkError,\n 504: NetworkError,\n };\n\nconst HTTP_SUGGESTIONS: Record<number, string> = {\n 400: \"Please check your request parameters and try again\",\n 401: \"Please check your API key and authentication credentials\",\n 403: \"You don't have permission to perform this operation\",\n 404: \"The requested resource was not found\",\n 408: \"Request timed out. Please try again\",\n 409: \"Resource conflict. Please check your request\",\n 413: \"Request too large. Please reduce the size of your request\",\n 422: \"Invalid request data. Please check your input\",\n 429: \"Rate limit exceeded. Please wait before making more requests\",\n 500: \"Internal server error. Please try again later\",\n 502: \"Service temporarily unavailable. Please try again later\",\n 503: \"Service unavailable. Please try again later\",\n 504: \"Gateway timeout. Please try again later\",\n};\n\n/**\n * Create an appropriate exception based on HTTP response status code.\n *\n * @param statusCode - HTTP status code from the response\n * @param responseText - Response body text\n * @param options - Additional error context (details, debugInfo)\n * @returns An instance of the appropriate MemoryError subclass\n */\nexport function createExceptionFromResponse(\n statusCode: number,\n responseText: string,\n options: Omit<MemoryErrorOptions, \"suggestion\"> = {},\n): MemoryError {\n const ExceptionClass = HTTP_STATUS_TO_EXCEPTION[statusCode] ?? MemoryError;\n const errorCode = `HTTP_${statusCode}`;\n const suggestion = HTTP_SUGGESTIONS[statusCode] ?? \"Please try again later\";\n\n return new ExceptionClass(\n responseText || `HTTP ${statusCode} error`,\n errorCode,\n { ...options, suggestion },\n );\n}\n","// ─── Entity Options (for add/delete — top-level identity) ───\nexport interface EntityOptions {\n userId?: string;\n agentId?: string;\n appId?: string;\n runId?: string;\n}\n\n// ─── Per-Method Options ─────────────────────────────────────\nexport interface AddMemoryOptions extends EntityOptions {\n metadata?: Record<string, any>;\n infer?: boolean;\n customCategories?: custom_categories[];\n customInstructions?: string;\n timestamp?: number;\n structuredDataSchema?: Record<string, any>;\n}\n\nexport interface SearchMemoryOptions {\n filters?: Record<string, any>;\n metadata?: Record<string, any>;\n topK?: number;\n threshold?: number;\n rerank?: boolean;\n fields?: string[];\n categories?: string[];\n}\n\nexport interface GetAllMemoryOptions {\n filters?: Record<string, any>;\n page?: number;\n pageSize?: number;\n startDate?: string;\n endDate?: string;\n categories?: string[];\n}\n\nexport interface DeleteAllMemoryOptions extends EntityOptions {}\n\n// ─── Project Options ────────────────────────────────────────\nexport interface ProjectOptions {\n fields?: string[];\n}\n\nexport interface PromptUpdatePayload {\n customInstructions?: string;\n customCategories?: custom_categories[];\n retrievalCriteria?: any[];\n version?: string;\n memoryDepth?: string | null;\n usecaseSetting?: string | number;\n multilingual?: boolean;\n [key: string]: any;\n}\n\n// ─── Enums ──────────────────────────────────────────────────\nexport enum Feedback {\n POSITIVE = \"POSITIVE\",\n NEGATIVE = \"NEGATIVE\",\n VERY_NEGATIVE = \"VERY_NEGATIVE\",\n}\n\n// ─── Message Types ──────────────────────────────────────────\nexport interface MultiModalMessages {\n type: \"image_url\";\n image_url: {\n url: string;\n };\n}\n\nexport interface Messages {\n role: \"user\" | \"assistant\";\n content: string | MultiModalMessages;\n}\n\nexport interface Message extends Messages {}\n\n// ─── Response Types (camelCase — converted from API snake_case) ─────\nexport interface MemoryData {\n memory: string;\n}\n\nenum Event {\n ADD = \"ADD\",\n UPDATE = \"UPDATE\",\n DELETE = \"DELETE\",\n NOOP = \"NOOP\",\n}\n\nexport interface Memory {\n id: string;\n messages?: Array<Messages>;\n event?: Event | string;\n data?: MemoryData | null;\n memory?: string;\n userId?: string;\n hash?: string;\n categories?: Array<string>;\n createdAt?: Date;\n updatedAt?: Date;\n memoryType?: string;\n score?: number;\n metadata?: any | null;\n owner?: string | null;\n agentId?: string | null;\n appId?: string | null;\n runId?: string | null;\n}\n\nexport interface MemoryHistory {\n id: string;\n memoryId: string;\n input: Array<Messages>;\n oldMemory: string | null;\n newMemory: string | null;\n userId: string;\n categories: Array<string>;\n event: Event | string;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface MemoryUpdateBody {\n memoryId: string;\n text: string;\n}\n\nexport interface User {\n id: string;\n name: string;\n createdAt: Date;\n updatedAt: Date;\n totalMemories: number;\n owner: string;\n type: string;\n}\n\nexport interface AllUsers {\n count: number;\n results: Array<User>;\n next: any;\n previous: any;\n}\n\nexport interface ProjectResponse {\n customInstructions?: string;\n customCategories?: string[];\n [key: string]: any;\n}\n\ninterface custom_categories {\n [key: string]: any;\n}\n\n// ─── Webhook Types ──────────────────────────────────────────\nexport enum WebhookEvent {\n MEMORY_ADDED = \"memory_add\",\n MEMORY_UPDATED = \"memory_update\",\n MEMORY_DELETED = \"memory_delete\",\n MEMORY_CATEGORIZED = \"memory_categorize\",\n}\n\nexport interface Webhook {\n webhookId?: string;\n name: string;\n url: string;\n project?: string;\n createdAt?: Date;\n updatedAt?: Date;\n isActive?: boolean;\n eventTypes?: WebhookEvent[];\n}\n\nexport interface WebhookCreatePayload {\n name: string;\n url: string;\n eventTypes: WebhookEvent[];\n}\n\nexport interface WebhookUpdatePayload {\n webhookId: string;\n name?: string;\n url?: string;\n eventTypes?: WebhookEvent[];\n}\n\n// ─── Feedback & Export Types ────────────────────────────────\nexport interface FeedbackPayload {\n memoryId: string;\n feedback?: Feedback | null;\n feedbackReason?: string | null;\n}\n\nexport interface CreateMemoryExportPayload {\n schema: Record<string, any>;\n filters: Record<string, any>;\n exportInstructions?: string;\n}\n\nexport interface GetMemoryExportPayload {\n filters?: Record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AI,KAAK,gBAAgB,GAAI,OAAM,KAAK,KAAK;AAC7C,SAAK,cAAc,qBAAqB,CAAC,CAAC;AAE1C,QAAI,CAAC,KAAK,kBAAkB,CAAC,KAAK,SAAS;AACzC,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAEA,UAAM,EAAE,SAAS,GAAG,KAAK,IAAI;AAC7B,UAAM,WAAW,MAAM,KAAK;AAAA,MAC1B,GAAG,KAAK,IAAI;AAAA,MACZ;AAAA,QACE,QAAQ;AAAA,QACR,SAAS,KAAK;AAAA,QACd,MAAM,KAAK,UAAU;AAAA,UACnB,GAAG,iBAAiB,IAAI;AAAA,UACxB,GAAI,WAAW,EAAE,QAAQ;AAAA,QAC3B,CAAC;AAAA,MACH;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;;;AI9nBO,IAAK,WAAL,kBAAKC,cAAL;AACL,EAAAA,UAAA,cAAW;AACX,EAAAA,UAAA,cAAW;AACX,EAAAA,UAAA,mBAAgB;AAHN,SAAAA;AAAA,GAAA;AAmGL,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,kBAAe;AACf,EAAAA,cAAA,oBAAiB;AACjB,EAAAA,cAAA,oBAAiB;AACjB,EAAAA,cAAA,wBAAqB;AAJX,SAAAA;AAAA,GAAA;;;AL3HZ,IAAO,gBAAQ;","names":["_a","axios","_a","Feedback","WebhookEvent"]}
|
package/dist/index.mjs
CHANGED
|
@@ -204,6 +204,26 @@ function createExceptionFromResponse(statusCode, responseText, options = {}) {
|
|
|
204
204
|
}
|
|
205
205
|
|
|
206
206
|
// src/client/mem0.ts
|
|
207
|
+
var ENTITY_PARAMS = [
|
|
208
|
+
"user_id",
|
|
209
|
+
"agent_id",
|
|
210
|
+
"app_id",
|
|
211
|
+
"run_id",
|
|
212
|
+
"userId",
|
|
213
|
+
"agentId",
|
|
214
|
+
"appId",
|
|
215
|
+
"runId"
|
|
216
|
+
];
|
|
217
|
+
function rejectTopLevelEntityParams(options, methodName) {
|
|
218
|
+
const invalidKeys = Object.keys(options != null ? options : {}).filter(
|
|
219
|
+
(k) => ENTITY_PARAMS.includes(k)
|
|
220
|
+
);
|
|
221
|
+
if (invalidKeys.length > 0) {
|
|
222
|
+
throw new Error(
|
|
223
|
+
`Top-level entity parameters [${invalidKeys.join(", ")}] are not supported in ${methodName}(). Use filters: { user_id: "..." } instead.`
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
207
227
|
var APIError = class extends Error {
|
|
208
228
|
constructor(message) {
|
|
209
229
|
super(message);
|
|
@@ -331,7 +351,7 @@ var MemoryClient = class {
|
|
|
331
351
|
const payloadKeys = Object.keys(payload);
|
|
332
352
|
this._captureEvent("add", [payloadKeys]);
|
|
333
353
|
const response = await this._fetchWithErrorHandling(
|
|
334
|
-
`${this.host}/
|
|
354
|
+
`${this.host}/v3/memories/`,
|
|
335
355
|
{
|
|
336
356
|
method: "POST",
|
|
337
357
|
headers: this.headers,
|
|
@@ -379,13 +399,15 @@ var MemoryClient = class {
|
|
|
379
399
|
}
|
|
380
400
|
async getAll(options) {
|
|
381
401
|
var _a2;
|
|
402
|
+
rejectTopLevelEntityParams(options, "getAll");
|
|
382
403
|
if (this.telemetryId === "") await this.ping();
|
|
383
404
|
const payloadKeys = Object.keys(options || {});
|
|
384
405
|
this._captureEvent("get_all", [payloadKeys]);
|
|
385
|
-
const { page, pageSize, ...rest } = options != null ? options : {};
|
|
406
|
+
const { page, pageSize, filters, ...rest } = options != null ? options : {};
|
|
386
407
|
const body = {
|
|
387
408
|
output_format: "v1.1",
|
|
388
|
-
...camelToSnakeKeys(rest)
|
|
409
|
+
...camelToSnakeKeys(rest),
|
|
410
|
+
...filters && { filters }
|
|
389
411
|
};
|
|
390
412
|
let url = `${this.host}/v2/memories/`;
|
|
391
413
|
if (page && pageSize) {
|
|
@@ -399,24 +421,26 @@ var MemoryClient = class {
|
|
|
399
421
|
return Array.isArray(response) ? response : (_a2 = response == null ? void 0 : response.results) != null ? _a2 : response;
|
|
400
422
|
}
|
|
401
423
|
async search(query, options) {
|
|
402
|
-
|
|
424
|
+
rejectTopLevelEntityParams(options, "search");
|
|
403
425
|
if (this.telemetryId === "") await this.ping();
|
|
404
426
|
const payloadKeys = Object.keys(options || {});
|
|
405
427
|
this._captureEvent("search", [payloadKeys]);
|
|
428
|
+
const { filters, ...rest } = options != null ? options : {};
|
|
406
429
|
const payload = {
|
|
407
430
|
query,
|
|
408
431
|
output_format: "v1.1",
|
|
409
|
-
...camelToSnakeKeys(
|
|
432
|
+
...camelToSnakeKeys(rest),
|
|
433
|
+
...filters && { filters }
|
|
410
434
|
};
|
|
411
435
|
const response = await this._fetchWithErrorHandling(
|
|
412
|
-
`${this.host}/
|
|
436
|
+
`${this.host}/v3/memories/search/`,
|
|
413
437
|
{
|
|
414
438
|
method: "POST",
|
|
415
439
|
headers: this.headers,
|
|
416
440
|
body: JSON.stringify(payload)
|
|
417
441
|
}
|
|
418
442
|
);
|
|
419
|
-
return
|
|
443
|
+
return response;
|
|
420
444
|
}
|
|
421
445
|
async delete(memoryId) {
|
|
422
446
|
if (this.telemetryId === "") await this.ping();
|
|
@@ -676,12 +700,16 @@ var MemoryClient = class {
|
|
|
676
700
|
if (!data.filters || !data.schema) {
|
|
677
701
|
throw new Error("Missing filters or schema");
|
|
678
702
|
}
|
|
703
|
+
const { filters, ...rest } = data;
|
|
679
704
|
const response = await this._fetchWithErrorHandling(
|
|
680
705
|
`${this.host}/v1/exports/`,
|
|
681
706
|
{
|
|
682
707
|
method: "POST",
|
|
683
708
|
headers: this.headers,
|
|
684
|
-
body: JSON.stringify(
|
|
709
|
+
body: JSON.stringify({
|
|
710
|
+
...camelToSnakeKeys(rest),
|
|
711
|
+
filters
|
|
712
|
+
})
|
|
685
713
|
}
|
|
686
714
|
);
|
|
687
715
|
return response;
|
|
@@ -692,12 +720,16 @@ var MemoryClient = class {
|
|
|
692
720
|
if (!data.memoryExportId && !data.filters) {
|
|
693
721
|
throw new Error("Missing memoryExportId or filters");
|
|
694
722
|
}
|
|
723
|
+
const { filters, ...rest } = data;
|
|
695
724
|
const response = await this._fetchWithErrorHandling(
|
|
696
725
|
`${this.host}/v1/exports/get/`,
|
|
697
726
|
{
|
|
698
727
|
method: "POST",
|
|
699
728
|
headers: this.headers,
|
|
700
|
-
body: JSON.stringify(
|
|
729
|
+
body: JSON.stringify({
|
|
730
|
+
...camelToSnakeKeys(rest),
|
|
731
|
+
...filters && { filters }
|
|
732
|
+
})
|
|
701
733
|
}
|
|
702
734
|
);
|
|
703
735
|
return response;
|