feat(integrations): add Zapier app for Mem0
A Zapier Platform CLI app (TypeScript) wrapping the hosted Mem0 v3 REST API: Add / Search / Get Memories / Delete actions with custom API-key auth. - Written in TypeScript, compiles to dist/; offline unit tests (mocked z.request) plus live E2E; `zapier validate` clean - Add supports custom_instructions, custom_categories, includes, excludes; Wait-for-Completion defaults off (extraction can exceed Zapier's 30s step limit) - Middleware surfaces non-2xx as errors (no silent empty results) - Anonymous opt-out telemetry (MEM0_TELEMETRY=false) - Docs page + docs.json/llms.txt entry, ci-gate wiring, AGENTS.md rows Split out of #6057 per review (separate PRs per integration).
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
node_modules/
|
||||
package-lock.json
|
||||
.env
|
||||
.zapierapprc
|
||||
build/
|
||||
dist/
|
||||
coverage/
|
||||
*.log
|
||||
.DS_Store
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Mem0
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Zapier integration for Mem0
|
||||
|
||||
A [Zapier](https://zapier.com) integration for [Mem0](https://mem0.ai) — the memory layer for AI agents. Add, search, list, and delete long-term memories from any Zap.
|
||||
|
||||
Built with the [Zapier Platform CLI](https://docs.zapier.com/platform/quickstart/cli-tutorial).
|
||||
|
||||
## Actions
|
||||
|
||||
| Type | Name | Endpoint |
|
||||
| --- | --- | --- |
|
||||
| Create | **Add Memory** | `POST /v3/memories/add/` |
|
||||
| Create | **Delete Memory** | `DELETE /v1/memories/{id}/` |
|
||||
| Search | **Search Memories** | `POST /v3/memories/search/` |
|
||||
| Search | **Get Memories** | `POST /v3/memories/` |
|
||||
|
||||
**Add Memory** runs LLM extraction asynchronously and returns immediately with an event ID by default. Turn on **Wait for Completion** to have the action poll until extraction finishes and return the resulting memories — note that extraction can take longer than Zapier allows a single step to run, and a timeout there does **not** mean the add failed (it typically still completes server-side). Set **Infer = false** to store the message verbatim instead of extracting.
|
||||
|
||||
**Get Memories** returns one page at a time; use the **Page** and **Limit** fields to page through larger result sets.
|
||||
|
||||
## Authentication
|
||||
|
||||
Custom (API key) auth. Provide a Mem0 API key from [app.mem0.ai](https://app.mem0.ai) → Settings → API Keys. It is sent as `Authorization: Token <key>`.
|
||||
|
||||
## Development
|
||||
|
||||
Written in TypeScript; the app compiles to `dist/` (Zapier runs the compiled JS).
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm build # compile src/ → dist/
|
||||
pnpm test:unit # offline unit tests (mocked, no network)
|
||||
MEM0_API_KEY=m0-... pnpm test # unit + live E2E against api.mem0.ai
|
||||
```
|
||||
|
||||
Anonymous usage telemetry is sent to Mem0; opt out with `MEM0_TELEMETRY=false`.
|
||||
|
||||
To deploy (maintainers): `pnpm build && zapier push`.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "zapier-mem0",
|
||||
"version": "0.1.0",
|
||||
"description": "Zapier integration for Mem0 — the memory layer for AI agents.",
|
||||
"keywords": [
|
||||
"zapier",
|
||||
"mem0",
|
||||
"memory",
|
||||
"ai",
|
||||
"agents"
|
||||
],
|
||||
"homepage": "https://mem0.ai",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
"email": "founders@mem0.ai"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/mem0ai/mem0",
|
||||
"directory": "integrations/zapier-mem0"
|
||||
},
|
||||
"license": "MIT",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test": "jest --testTimeout 180000",
|
||||
"test:unit": "jest test/unit.test.ts"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18",
|
||||
"npm": ">=5.6.0"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"jest": {
|
||||
"testEnvironment": "node",
|
||||
"testMatch": ["**/test/**/*.test.ts"],
|
||||
"transform": {
|
||||
"^.+\\.tsx?$": ["ts-jest", {}]
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"zapier-platform-core": "19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^22.9.0",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
Generated
+3158
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,30 @@
|
||||
import type { ZObject, Bundle } from './types';
|
||||
|
||||
// Custom (API key) authentication for Mem0.
|
||||
// The key is sent as "Authorization: Token <apiKey>" (matches Mem0's SDKs).
|
||||
const test = (z: ZObject, _bundle: Bundle) => z.request({ url: '/v1/ping/', method: 'GET' });
|
||||
|
||||
export default {
|
||||
type: 'custom',
|
||||
test,
|
||||
fields: [
|
||||
{
|
||||
key: 'apiKey',
|
||||
label: 'Mem0 API Key',
|
||||
type: 'string',
|
||||
required: true,
|
||||
helpText:
|
||||
'Your Mem0 API key (starts with `m0-`). Create one at [app.mem0.ai](https://app.mem0.ai) → Settings → API Keys.',
|
||||
},
|
||||
{
|
||||
key: 'baseUrl',
|
||||
label: 'Base URL',
|
||||
type: 'string',
|
||||
required: false,
|
||||
default: 'https://api.mem0.ai',
|
||||
helpText: 'Override only for self-hosted or non-default deployments.',
|
||||
},
|
||||
],
|
||||
// Shown on the connection label in the Zap editor.
|
||||
connectionLabel: 'Mem0',
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
import type { ZObject, Bundle, AddResponse, EventResponse } from '../types';
|
||||
import { captureEvent } from '../telemetry';
|
||||
|
||||
const POLL_INTERVAL_MS = 1500;
|
||||
// Bounded so the poll budget stays under Zapier's per-step execution timeout.
|
||||
const MAX_POLL_ATTEMPTS = 12;
|
||||
|
||||
// Polls GET /v1/event/{id}/ until the async memory-addition event resolves.
|
||||
const pollEvent = async (z: ZObject, eventId: string): Promise<EventResponse> => {
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
|
||||
const res = await z.request({ url: `/v1/event/${eventId}/`, method: 'GET' });
|
||||
const data = res.data as EventResponse;
|
||||
const status = data && data.status;
|
||||
if (status === 'SUCCEEDED') {
|
||||
return data;
|
||||
}
|
||||
if (status === 'FAILED') {
|
||||
const reason = (data && (data.error || data.message)) || 'unknown error';
|
||||
throw new z.errors.Error(`Mem0 memory event ${eventId} failed: ${reason}`, 'Mem0EventFailed', 400);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
||||
}
|
||||
throw new z.errors.Error(
|
||||
`Timed out waiting for memory event ${eventId}. The add was accepted and is ` +
|
||||
`likely still completing on the server — a timeout here does not mean it failed.`,
|
||||
'Mem0Timeout',
|
||||
408,
|
||||
);
|
||||
};
|
||||
|
||||
const perform = async (z: ZObject, bundle: Bundle): Promise<AddResponse | EventResponse> => {
|
||||
// Zapier boolean fields can arrive as the strings 'true'/'false'; coerce
|
||||
// explicitly so "Infer = No" / "Wait = No" are honored.
|
||||
const infer = String(bundle.inputData.infer) !== 'false';
|
||||
// Waiting is opt-in (the poll path can exceed Zapier's step timeout).
|
||||
const wait = String(bundle.inputData.waitForCompletion) === 'true';
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
messages: [{ role: bundle.inputData.role || 'user', content: bundle.inputData.content }],
|
||||
infer,
|
||||
};
|
||||
if (bundle.inputData.user_id) body.user_id = bundle.inputData.user_id;
|
||||
if (bundle.inputData.agent_id) body.agent_id = bundle.inputData.agent_id;
|
||||
if (bundle.inputData.run_id) body.run_id = bundle.inputData.run_id;
|
||||
if (bundle.inputData.metadata) {
|
||||
try {
|
||||
body.metadata =
|
||||
typeof bundle.inputData.metadata === 'string'
|
||||
? JSON.parse(bundle.inputData.metadata)
|
||||
: bundle.inputData.metadata;
|
||||
} catch {
|
||||
throw new z.errors.Error('Metadata must be valid JSON.', 'InvalidInput', 400);
|
||||
}
|
||||
}
|
||||
// Custom extraction controls (optional): steer what the API extracts.
|
||||
if (bundle.inputData.custom_instructions) {
|
||||
body.custom_instructions = bundle.inputData.custom_instructions;
|
||||
}
|
||||
if (bundle.inputData.custom_categories) {
|
||||
try {
|
||||
body.custom_categories =
|
||||
typeof bundle.inputData.custom_categories === 'string'
|
||||
? JSON.parse(bundle.inputData.custom_categories)
|
||||
: bundle.inputData.custom_categories;
|
||||
} catch {
|
||||
throw new z.errors.Error('Custom Categories must be valid JSON.', 'InvalidInput', 400);
|
||||
}
|
||||
}
|
||||
if (bundle.inputData.includes) body.includes = bundle.inputData.includes;
|
||||
if (bundle.inputData.excludes) body.excludes = bundle.inputData.excludes;
|
||||
|
||||
captureEvent('zapier.add_memory', bundle.authData?.apiKey, { infer, wait });
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/add/',
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
|
||||
const data = response.data as AddResponse;
|
||||
|
||||
// Add returns {event_id, status:PENDING|RUNNING}; poll only when opted in.
|
||||
if (wait && data.event_id && data.status !== 'SUCCEEDED' && data.status !== 'FAILED') {
|
||||
return pollEvent(z, data.event_id);
|
||||
}
|
||||
if (data.status === 'FAILED') {
|
||||
const reason = data.error || data.message || 'unknown error';
|
||||
throw new z.errors.Error(`Mem0 memory add failed: ${reason}`, 'Mem0EventFailed', 400);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
export default {
|
||||
key: 'add_memory',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Add Memory',
|
||||
description: 'Extract and store memories from a message.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{
|
||||
key: 'content',
|
||||
label: 'Content',
|
||||
type: 'text',
|
||||
required: true,
|
||||
helpText: 'The message content to extract memories from.',
|
||||
},
|
||||
{
|
||||
key: 'role',
|
||||
label: 'Role',
|
||||
choices: { user: 'User', assistant: 'Assistant', system: 'System' },
|
||||
default: 'user',
|
||||
},
|
||||
{ key: 'user_id', label: 'User ID', type: 'string' },
|
||||
{ key: 'agent_id', label: 'Agent ID', type: 'string' },
|
||||
{ key: 'run_id', label: 'Run ID', type: 'string' },
|
||||
{ key: 'metadata', label: 'Metadata (JSON)', type: 'string' },
|
||||
{
|
||||
key: 'custom_instructions',
|
||||
label: 'Custom Instructions',
|
||||
type: 'text',
|
||||
helpText: 'Optional instructions that steer what the extractor keeps or ignores.',
|
||||
},
|
||||
{
|
||||
key: 'custom_categories',
|
||||
label: 'Custom Categories (JSON)',
|
||||
type: 'string',
|
||||
helpText:
|
||||
'Optional taxonomy for categorising memories, as a JSON array of {category: description} objects.',
|
||||
},
|
||||
{
|
||||
key: 'includes',
|
||||
label: 'Includes',
|
||||
type: 'text',
|
||||
helpText: 'Optional: only extract memories matching this description.',
|
||||
},
|
||||
{
|
||||
key: 'excludes',
|
||||
label: 'Excludes',
|
||||
type: 'text',
|
||||
helpText: 'Optional: skip memories matching this description.',
|
||||
},
|
||||
{
|
||||
key: 'infer',
|
||||
label: 'Infer',
|
||||
type: 'boolean',
|
||||
default: 'true',
|
||||
helpText: 'Run LLM extraction over the message. Turn off to store it verbatim.',
|
||||
},
|
||||
{
|
||||
key: 'waitForCompletion',
|
||||
label: 'Wait for Completion',
|
||||
type: 'boolean',
|
||||
default: 'false',
|
||||
helpText:
|
||||
'Poll until extraction finishes and return the resulting memories. ' +
|
||||
'Leave off (default) to return immediately with an event ID — extraction can take ' +
|
||||
'longer than Zapier allows this step to run, and a timeout does not mean the add failed.',
|
||||
},
|
||||
],
|
||||
sample: { status: 'SUCCEEDED', event_id: '00000000-0000-0000-0000-000000000000', results: [] },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ZObject, Bundle } from '../types';
|
||||
|
||||
const perform = async (z: ZObject, bundle: Bundle) => {
|
||||
// Trailing slash required (Django APPEND_SLASH); id encoded so a stray slash can't mistarget the path.
|
||||
const response = await z.request({
|
||||
url: `/v1/memories/${encodeURIComponent(String(bundle.inputData.memory_id))}/`,
|
||||
method: 'DELETE',
|
||||
});
|
||||
return response.data || { message: 'Deleted', memory_id: bundle.inputData.memory_id };
|
||||
};
|
||||
|
||||
export default {
|
||||
key: 'delete_memory',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Delete Memory',
|
||||
description: 'Delete a single memory by its ID.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [{ key: 'memory_id', label: 'Memory ID', type: 'string', required: true }],
|
||||
sample: { message: 'Memory deleted successfully' },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import authentication from './authentication';
|
||||
import { includeApiKey, handleBadResponses } from './middleware';
|
||||
import addMemory from './creates/add_memory';
|
||||
import deleteMemory from './creates/delete_memory';
|
||||
import searchMemories from './searches/search_memories';
|
||||
import getMemories from './searches/get_memories';
|
||||
|
||||
// Read version at runtime from the package manifest (one directory up from dist/).
|
||||
const { version } = require('../package.json');
|
||||
const platformVersion = require('zapier-platform-core').version;
|
||||
|
||||
const app = {
|
||||
version,
|
||||
platformVersion,
|
||||
|
||||
authentication,
|
||||
|
||||
beforeRequest: [includeApiKey],
|
||||
afterResponse: [handleBadResponses],
|
||||
|
||||
creates: {
|
||||
[addMemory.key]: addMemory,
|
||||
[deleteMemory.key]: deleteMemory,
|
||||
},
|
||||
|
||||
searches: {
|
||||
[searchMemories.key]: searchMemories,
|
||||
[getMemories.key]: getMemories,
|
||||
},
|
||||
|
||||
resources: {},
|
||||
triggers: {},
|
||||
};
|
||||
|
||||
export = app;
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ZObject, Bundle, MutableRequest, ZResponse } from './types';
|
||||
|
||||
// Prepend the configured base URL and inject the auth header on every request.
|
||||
export const includeApiKey = (
|
||||
request: MutableRequest,
|
||||
_z: ZObject,
|
||||
bundle: Bundle,
|
||||
): MutableRequest => {
|
||||
if (bundle.authData && bundle.authData.apiKey) {
|
||||
request.headers = request.headers || {};
|
||||
request.headers.Authorization = `Token ${bundle.authData.apiKey}`;
|
||||
}
|
||||
// Resolve relative URLs against the configured base URL.
|
||||
if (request.url && request.url.startsWith('/')) {
|
||||
const base = (bundle.authData && bundle.authData.baseUrl) || 'https://api.mem0.ai';
|
||||
request.url = `${base.replace(/\/$/, '')}${request.url}`;
|
||||
}
|
||||
return request;
|
||||
};
|
||||
|
||||
// Surface HTTP failures as errors. z.request does NOT throw on non-2xx by
|
||||
// default, so without this a 4xx/5xx would flow downstream as a fake success
|
||||
// (empty search results / error body returned as a created memory).
|
||||
export const handleBadResponses = (
|
||||
response: ZResponse,
|
||||
z: ZObject,
|
||||
_bundle: Bundle,
|
||||
): ZResponse => {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new z.errors.Error(
|
||||
'The Mem0 API key you supplied is invalid or lacks access.',
|
||||
'AuthenticationError',
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
if (response.status >= 400) {
|
||||
const data = (response.data as Record<string, unknown>) || {};
|
||||
const detail = (data.detail ||
|
||||
data.error ||
|
||||
data.message ||
|
||||
response.content ||
|
||||
'unknown error') as string;
|
||||
throw new z.errors.Error(
|
||||
`Mem0 API request failed (HTTP ${response.status}): ${detail}`,
|
||||
'Mem0ApiError',
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { ZObject, Bundle, Memory } from '../types';
|
||||
import { captureEvent } from '../telemetry';
|
||||
|
||||
const perform = async (z: ZObject, bundle: Bundle): Promise<Memory[]> => {
|
||||
const body: Record<string, unknown> = {};
|
||||
if (bundle.inputData.user_id) body.filters = { user_id: bundle.inputData.user_id };
|
||||
|
||||
captureEvent('zapier.get_memories', bundle.authData?.apiKey);
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/',
|
||||
method: 'POST',
|
||||
params: {
|
||||
page: Math.max(1, Math.floor(Number(bundle.inputData.page) || 1)),
|
||||
page_size: Math.max(1, Math.floor(Number(bundle.inputData.limit) || 50)),
|
||||
},
|
||||
body,
|
||||
});
|
||||
const data = response.data as Memory[] | { results?: Memory[] };
|
||||
return Array.isArray(data) ? data : data.results || [];
|
||||
};
|
||||
|
||||
export default {
|
||||
key: 'get_memories',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Get Memories',
|
||||
description: 'List stored memories for a user.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{ key: 'user_id', label: 'User ID', type: 'string', required: true },
|
||||
{
|
||||
key: 'limit',
|
||||
label: 'Limit',
|
||||
type: 'integer',
|
||||
default: '50',
|
||||
helpText: 'Max memories per page. Use Page to page through larger result sets.',
|
||||
},
|
||||
{
|
||||
key: 'page',
|
||||
label: 'Page',
|
||||
type: 'integer',
|
||||
default: '1',
|
||||
helpText: 'Which page of results to return (1-based).',
|
||||
},
|
||||
],
|
||||
sample: { id: '00000000-0000-0000-0000-000000000000', memory: 'User loves hiking' },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ZObject, Bundle, Memory } from '../types';
|
||||
import { captureEvent } from '../telemetry';
|
||||
|
||||
const perform = async (z: ZObject, bundle: Bundle): Promise<Memory[]> => {
|
||||
const body: Record<string, unknown> = {
|
||||
query: bundle.inputData.query,
|
||||
output_format: 'v1.1',
|
||||
top_k: Math.max(1, Math.floor(Number(bundle.inputData.limit) || 50)),
|
||||
};
|
||||
if (bundle.inputData.user_id) body.filters = { user_id: bundle.inputData.user_id };
|
||||
|
||||
captureEvent('zapier.search_memories', bundle.authData?.apiKey);
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/search/',
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
// Searches must return an array.
|
||||
const data = response.data as Memory[] | { results?: Memory[] };
|
||||
return Array.isArray(data) ? data : data.results || [];
|
||||
};
|
||||
|
||||
export default {
|
||||
key: 'search_memories',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Search Memories',
|
||||
description: 'Semantic search over stored memories.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{ key: 'query', label: 'Query', type: 'string', required: true },
|
||||
{ key: 'user_id', label: 'User ID', type: 'string', required: true },
|
||||
{ key: 'limit', label: 'Limit', type: 'integer', default: '50' },
|
||||
],
|
||||
sample: { id: '00000000-0000-0000-0000-000000000000', memory: 'User loves hiking' },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
// Anonymous usage telemetry via PostHog, mirroring the Mem0 CLI / plugins.
|
||||
// Fire-and-forget: never awaited, never throws, so it can neither slow down
|
||||
// nor break an action. Opt out with MEM0_TELEMETRY=false.
|
||||
const POSTHOG_API_KEY = 'phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX';
|
||||
const POSTHOG_HOST = 'https://us.i.posthog.com/i/v0/e/';
|
||||
|
||||
export function captureEvent(
|
||||
event: string,
|
||||
apiKey: string | undefined,
|
||||
properties: Record<string, unknown> = {},
|
||||
): void {
|
||||
if (process.env.MEM0_TELEMETRY === 'false') return;
|
||||
try {
|
||||
// Hash the API key so events are attributable to one account without
|
||||
// ever transmitting the key itself.
|
||||
const distinctId = apiKey ? createHash('md5').update(apiKey).digest('hex') : 'zapier-anon';
|
||||
const payload = {
|
||||
api_key: POSTHOG_API_KEY,
|
||||
event,
|
||||
distinct_id: distinctId,
|
||||
properties: {
|
||||
source: 'ZAPIER',
|
||||
$process_person_profile: false,
|
||||
...properties,
|
||||
},
|
||||
};
|
||||
void fetch(POSTHOG_HOST, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
}).catch(() => {
|
||||
/* swallow — telemetry must never surface to the user */
|
||||
});
|
||||
} catch {
|
||||
/* swallow — telemetry must never break the action */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ZObject, Bundle } from 'zapier-platform-core';
|
||||
|
||||
export type { ZObject, Bundle };
|
||||
|
||||
/** Mutable outgoing request, as seen by the beforeRequest middleware. */
|
||||
export interface MutableRequest {
|
||||
url?: string;
|
||||
headers?: Record<string, string>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** Response as seen by the afterResponse middleware. */
|
||||
export interface ZResponse {
|
||||
status: number;
|
||||
data?: Record<string, unknown> | unknown[] | null;
|
||||
content?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** Async add response from POST /v3/memories/add/. */
|
||||
export interface AddResponse {
|
||||
event_id?: string;
|
||||
status?: string;
|
||||
error?: string;
|
||||
message?: string;
|
||||
results?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** GET /v1/event/{id}/ response. */
|
||||
export interface EventResponse {
|
||||
status?: string;
|
||||
error?: string;
|
||||
message?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** A stored memory object returned by search / list. */
|
||||
export interface Memory {
|
||||
id?: string;
|
||||
memory?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import * as zapier from 'zapier-platform-core';
|
||||
import App from '../src';
|
||||
|
||||
const appTester = zapier.createAppTester(App as any);
|
||||
|
||||
const authData = {
|
||||
apiKey: process.env.MEM0_API_KEY,
|
||||
baseUrl: process.env.MEM0_BASE_URL || 'https://api.mem0.ai',
|
||||
};
|
||||
|
||||
const userId = `zapier-e2e-${Date.now()}`;
|
||||
|
||||
// Retry an async op until `done` is satisfied or attempts run out. Extraction is
|
||||
// async, so the default Add returns before the memory is searchable.
|
||||
const until = async <T>(
|
||||
fn: () => Promise<T>,
|
||||
done: (r: T) => boolean,
|
||||
{ attempts = 30, delayMs = 2000 } = {},
|
||||
): Promise<T> => {
|
||||
let last: T = undefined as unknown as T;
|
||||
for (let i = 0; i < attempts; i++) {
|
||||
last = await fn();
|
||||
if (done(last)) return last;
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
return last;
|
||||
};
|
||||
|
||||
// The E2E suite hits the live Mem0 API, so it only runs when MEM0_API_KEY is
|
||||
// set (locally / with a secret). In CI without a key it is skipped, not failed.
|
||||
const describeE2E = authData.apiKey ? describe : describe.skip;
|
||||
|
||||
describeE2E('Mem0 Zapier integration (E2E)', () => {
|
||||
it('authentication.test succeeds', async () => {
|
||||
const res: any = await appTester((App as any).authentication.test, { authData });
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('adds, searches, lists, and deletes a memory', async () => {
|
||||
// Add via the default path: returns immediately with an event id.
|
||||
const added: any = await appTester((App as any).creates.add_memory.operation.perform, {
|
||||
authData,
|
||||
inputData: {
|
||||
content: 'I love hiking in the Alps and my favorite food is sushi',
|
||||
user_id: userId,
|
||||
},
|
||||
});
|
||||
expect(added.event_id).toBeDefined();
|
||||
|
||||
// Extraction is async; retry search until the memory is indexed.
|
||||
// Budget generously — live extraction can occasionally exceed a minute.
|
||||
const found: any[] = await until(
|
||||
() =>
|
||||
appTester((App as any).searches.search_memories.operation.perform, {
|
||||
authData,
|
||||
inputData: { query: 'outdoor activities', user_id: userId, limit: 5 },
|
||||
}),
|
||||
(r: any[]) => Array.isArray(r) && r.length > 0,
|
||||
{ attempts: 60, delayMs: 2000 },
|
||||
);
|
||||
expect(Array.isArray(found)).toBe(true);
|
||||
expect(found.length).toBeGreaterThan(0);
|
||||
|
||||
// Get all
|
||||
const all: any[] = await appTester((App as any).searches.get_memories.operation.perform, {
|
||||
authData,
|
||||
inputData: { user_id: userId },
|
||||
});
|
||||
expect(Array.isArray(all)).toBe(true);
|
||||
expect(all.length).toBeGreaterThan(0);
|
||||
|
||||
// Cleanup: delete every memory we created
|
||||
for (const mem of all) {
|
||||
await appTester((App as any).creates.delete_memory.operation.perform, {
|
||||
authData,
|
||||
inputData: { memory_id: mem.id },
|
||||
});
|
||||
}
|
||||
|
||||
const afterDelete: any[] = await appTester(
|
||||
(App as any).searches.get_memories.operation.perform,
|
||||
{ authData, inputData: { user_id: userId } },
|
||||
);
|
||||
expect(afterDelete.length).toBe(0);
|
||||
});
|
||||
|
||||
it('surfaces API errors instead of returning an empty array (search needs a filter)', async () => {
|
||||
// filters is required by the API; omitting it must throw, not return [].
|
||||
await expect(
|
||||
appTester((App as any).searches.search_memories.operation.perform, {
|
||||
authData,
|
||||
inputData: { query: 'anything' },
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
// Offline unit tests: they mock `z.request`, so they run unconditionally in CI
|
||||
// (unlike the live E2E suite in mem0.test.ts, gated on MEM0_API_KEY). They cover
|
||||
// what `zapier validate` can't: boolean coercion, URL join, metadata, array shapes.
|
||||
|
||||
import addMemory from '../src/creates/add_memory';
|
||||
import deleteMemory from '../src/creates/delete_memory';
|
||||
import searchMemories from '../src/searches/search_memories';
|
||||
import getMemories from '../src/searches/get_memories';
|
||||
import { includeApiKey } from '../src/middleware';
|
||||
|
||||
// Minimal `z` stub: hands back queued responses and records every request.
|
||||
const makeZ = (responses: any[] = []): any => {
|
||||
const queue = [...responses];
|
||||
const requests: any[] = [];
|
||||
return {
|
||||
requests,
|
||||
request: async (opts: any) => {
|
||||
requests.push(opts);
|
||||
const next = queue.shift();
|
||||
return next !== undefined ? next : { data: {} };
|
||||
},
|
||||
errors: {
|
||||
Error: class Mem0Error extends Error {
|
||||
name: string;
|
||||
status?: number;
|
||||
constructor(message: string, name?: string, status?: number) {
|
||||
super(message);
|
||||
this.name = name || 'Error';
|
||||
this.status = status;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
describe('add_memory (offline)', () => {
|
||||
it('coerces infer="false" to a boolean and does not poll by default', async () => {
|
||||
const z = makeZ([{ data: { event_id: 'e1', status: 'PENDING' } }]);
|
||||
const res = await addMemory.operation.perform(z, {
|
||||
inputData: { content: 'hi', user_id: 'u1', infer: 'false' },
|
||||
} as any);
|
||||
// waitForCompletion defaults off -> a single request (the add), no poll.
|
||||
expect(z.requests).toHaveLength(1);
|
||||
expect(z.requests[0].body.infer).toBe(false);
|
||||
expect((res as any).status).toBe('PENDING');
|
||||
});
|
||||
|
||||
it('polls the event only when waitForCompletion="true"', async () => {
|
||||
const z = makeZ([
|
||||
{ data: { event_id: 'e1', status: 'PENDING' } },
|
||||
{ data: { status: 'SUCCEEDED', results: [{ id: 'm1' }] } },
|
||||
]);
|
||||
const res = await addMemory.operation.perform(z, {
|
||||
inputData: { content: 'hi', user_id: 'u1', waitForCompletion: 'true' },
|
||||
} as any);
|
||||
expect(z.requests).toHaveLength(2);
|
||||
expect(z.requests[1].url).toBe('/v1/event/e1/');
|
||||
expect((res as any).status).toBe('SUCCEEDED');
|
||||
});
|
||||
|
||||
it('throws a clear error on invalid JSON metadata', async () => {
|
||||
const z = makeZ();
|
||||
await expect(
|
||||
addMemory.operation.perform(z, {
|
||||
inputData: { content: 'hi', user_id: 'u1', metadata: '{not json' },
|
||||
} as any),
|
||||
).rejects.toThrow('Metadata must be valid JSON.');
|
||||
});
|
||||
|
||||
it('forwards custom_instructions and parses custom_categories JSON', async () => {
|
||||
const z = makeZ([{ data: { event_id: 'e1', status: 'PENDING' } }]);
|
||||
await addMemory.operation.perform(z, {
|
||||
inputData: {
|
||||
content: 'hi',
|
||||
user_id: 'u1',
|
||||
custom_instructions: 'keep durable facts',
|
||||
custom_categories: '[{"work":"job related"}]',
|
||||
},
|
||||
} as any);
|
||||
expect(z.requests[0].body.custom_instructions).toBe('keep durable facts');
|
||||
expect(z.requests[0].body.custom_categories).toEqual([{ work: 'job related' }]);
|
||||
});
|
||||
|
||||
it('throws a clear error on invalid Custom Categories JSON', async () => {
|
||||
const z = makeZ();
|
||||
await expect(
|
||||
addMemory.operation.perform(z, {
|
||||
inputData: { content: 'hi', user_id: 'u1', custom_categories: '{bad' },
|
||||
} as any),
|
||||
).rejects.toThrow('Custom Categories must be valid JSON.');
|
||||
});
|
||||
|
||||
it('forwards includes and excludes when provided', async () => {
|
||||
const z = makeZ([{ data: { event_id: 'e1', status: 'PENDING' } }]);
|
||||
await addMemory.operation.perform(z, {
|
||||
inputData: { content: 'hi', user_id: 'u1', includes: 'work facts', excludes: 'small talk' },
|
||||
} as any);
|
||||
expect(z.requests[0].body.includes).toBe('work facts');
|
||||
expect(z.requests[0].body.excludes).toBe('small talk');
|
||||
});
|
||||
});
|
||||
|
||||
describe('search / get array-shape enforcement (offline)', () => {
|
||||
it('search unwraps an object {results:[...]} into an array', async () => {
|
||||
const z = makeZ([{ data: { results: [{ id: 'm1' }] } }]);
|
||||
const res = await searchMemories.operation.perform(z, {
|
||||
inputData: { query: 'x', user_id: 'u1' },
|
||||
} as any);
|
||||
expect(Array.isArray(res)).toBe(true);
|
||||
expect(res).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('get_memories returns [] when the API returns neither array nor results', async () => {
|
||||
const z = makeZ([{ data: {} }]);
|
||||
const res = await getMemories.operation.perform(z, { inputData: { user_id: 'u1' } } as any);
|
||||
expect(Array.isArray(res)).toBe(true);
|
||||
expect(res).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('get_memories forwards page and page_size as numbers', async () => {
|
||||
const z = makeZ([{ data: { results: [] } }]);
|
||||
await getMemories.operation.perform(z, {
|
||||
inputData: { user_id: 'u1', page: '2', limit: '10' },
|
||||
} as any);
|
||||
expect(z.requests[0].params).toEqual({ page: 2, page_size: 10 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete_memory (offline)', () => {
|
||||
it('encodes the memory id in the URL path', async () => {
|
||||
const z = makeZ([{ data: {} }]);
|
||||
await deleteMemory.operation.perform(z, { inputData: { memory_id: 'a/b c' } } as any);
|
||||
expect(z.requests[0].url).toBe('/v1/memories/a%2Fb%20c/');
|
||||
});
|
||||
});
|
||||
|
||||
describe('includeApiKey middleware (offline)', () => {
|
||||
it('prepends the base URL and injects the auth header', () => {
|
||||
const req = includeApiKey({ url: '/v3/memories/' }, null as any, {
|
||||
authData: { apiKey: 'k', baseUrl: 'https://api.mem0.ai/' },
|
||||
} as any);
|
||||
expect(req.url).toBe('https://api.mem0.ai/v3/memories/');
|
||||
expect(req.headers!.Authorization).toBe('Token k');
|
||||
});
|
||||
|
||||
it('leaves absolute URLs untouched', () => {
|
||||
const req = includeApiKey({ url: 'https://other.example/x' }, null as any, {
|
||||
authData: { apiKey: 'k' },
|
||||
} as any);
|
||||
expect(req.url).toBe('https://other.example/x');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"declaration": false,
|
||||
"sourceMap": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules", "dist", "test"]
|
||||
}
|
||||
Reference in New Issue
Block a user