Spaces:
Paused
Paused
Commit ·
5ec8557
1
Parent(s): ad75abf
mem0 self-hosted: full deployment (auth fix, nginx routing, 9router LLM config)
Browse files- .env.example +77 -0
- .gitignore +2 -0
- Dockerfile +172 -0
- README.md +136 -3
- docker-compose.yml +32 -0
- entrypoint.sh +191 -0
- init-db.sh +30 -0
- nginx-proxy.conf +16 -0
- nginx.conf +123 -0
- requirements.txt +42 -0
- server/README.md +22 -0
- server/alembic.ini +37 -0
- server/alembic/env.py +44 -0
- server/alembic/script.py.mako +26 -0
- server/alembic/versions/001_create_users_and_api_keys.py +49 -0
- server/alembic/versions/002_create_request_logs.py +36 -0
- server/alembic/versions/003_create_settings.py +30 -0
- server/alembic/versions/004_unique_admin_role.py +31 -0
- server/alembic/versions/005_refresh_token_jtis.py +39 -0
- server/alembic/versions/006_request_logs_brin.py +26 -0
- server/auth.py +224 -0
- server/dashboard/.env.example +2 -0
- server/dashboard/components.json +17 -0
- server/dashboard/entrypoint.sh +17 -0
- server/dashboard/next.config.mjs +46 -0
- server/dashboard/package.json +84 -0
- server/dashboard/postcss.config.js +6 -0
- server/dashboard/src/README.md +24 -0
- server/dashboard/tailwind.config.ts +327 -0
- server/dashboard/tsconfig.json +30 -0
- server/db.py +31 -0
- server/errors.py +94 -0
- server/main.py +559 -0
- server/models.py +74 -0
- server/rate_limit.py +4 -0
- server/routers/__init__.py +1 -0
- server/routers/api_keys.py +93 -0
- server/routers/auth.py +221 -0
- server/routers/entities.py +77 -0
- server/routers/requests.py +46 -0
- server/schemas.py +5 -0
- server/server_state.py +104 -0
- server/telemetry.py +129 -0
- supervisord.conf +73 -0
.env.example
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mem0 Self-Hosted - Environment Variables
|
| 2 |
+
# Copy this file to .env and fill in your values
|
| 3 |
+
|
| 4 |
+
# =============================================================================
|
| 5 |
+
# REQUIRED - Must be set before starting
|
| 6 |
+
# =============================================================================
|
| 7 |
+
|
| 8 |
+
# PostgreSQL password (required for pgvector/pgvector:pg17)
|
| 9 |
+
# Generate with: openssl rand -base64 32
|
| 10 |
+
POSTGRES_PASSWORD=your-secure-postgres-password-here
|
| 11 |
+
|
| 12 |
+
# OpenAI API Key (required for default LLM and embedder)
|
| 13 |
+
# Get from: https://platform.openai.com/api-keys
|
| 14 |
+
OPENAI_API_KEY=sk-your-openai-api-key-here
|
| 15 |
+
|
| 16 |
+
# JWT Secret for authentication (required when AUTH_DISABLED=false)
|
| 17 |
+
# Generate with: openssl rand -base64 48
|
| 18 |
+
JWT_SECRET=your-jwt-secret-here
|
| 19 |
+
|
| 20 |
+
# =============================================================================
|
| 21 |
+
# OPTIONAL - Authentication
|
| 22 |
+
# =============================================================================
|
| 23 |
+
|
| 24 |
+
# Admin API Key (optional - alternative to dashboard admin registration)
|
| 25 |
+
# Generate with: openssl rand -base64 32
|
| 26 |
+
# If set, use as Bearer token or X-API-Key header for admin access
|
| 27 |
+
ADMIN_API_KEY=
|
| 28 |
+
|
| 29 |
+
# Disable authentication (local development ONLY - not for production)
|
| 30 |
+
# AUTH_DISABLED=true
|
| 31 |
+
|
| 32 |
+
# =============================================================================
|
| 33 |
+
# OPTIONAL - Model Configuration
|
| 34 |
+
# =============================================================================
|
| 35 |
+
|
| 36 |
+
# Default LLM model (must be supported by your API key)
|
| 37 |
+
MEM0_DEFAULT_LLM_MODEL=gpt-5-mini
|
| 38 |
+
|
| 39 |
+
# Default embedder model
|
| 40 |
+
MEM0_DEFAULT_EMBEDDER_MODEL=text-embedding-3-small
|
| 41 |
+
|
| 42 |
+
# =============================================================================
|
| 43 |
+
# OPTIONAL - Dashboard & API URLs
|
| 44 |
+
# =============================================================================
|
| 45 |
+
|
| 46 |
+
# Dashboard URL (used for CORS and redirects)
|
| 47 |
+
DASHBOARD_URL=http://localhost:7860
|
| 48 |
+
|
| 49 |
+
# Public API URL (used by dashboard for API calls)
|
| 50 |
+
NEXT_PUBLIC_API_URL=http://localhost:7860/api
|
| 51 |
+
|
| 52 |
+
# Instance name shown in dashboard
|
| 53 |
+
NEXT_PUBLIC_INSTANCE_NAME=Mem0
|
| 54 |
+
|
| 55 |
+
# =============================================================================
|
| 56 |
+
# OPTIONAL - Telemetry
|
| 57 |
+
# =============================================================================
|
| 58 |
+
|
| 59 |
+
# Disable anonymous telemetry (enabled by default)
|
| 60 |
+
# MEM0_TELEMETRY=false
|
| 61 |
+
|
| 62 |
+
# =============================================================================
|
| 63 |
+
# OPTIONAL - Advanced Configuration
|
| 64 |
+
# =============================================================================
|
| 65 |
+
|
| 66 |
+
# PostgreSQL connection (usually don't need to change)
|
| 67 |
+
POSTGRES_HOST=localhost
|
| 68 |
+
POSTGRES_PORT=5432
|
| 69 |
+
POSTGRES_DB=postgres
|
| 70 |
+
POSTGRES_USER=mem0
|
| 71 |
+
POSTGRES_COLLECTION_NAME=memories
|
| 72 |
+
|
| 73 |
+
# History database path
|
| 74 |
+
HISTORY_DB_PATH=/opt/data/history/history.db
|
| 75 |
+
|
| 76 |
+
# Sync interval for backup (seconds)
|
| 77 |
+
SYNC_INTERVAL=60
|
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
llm-config.json
|
Dockerfile
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mem0 Self-Hosted - Dockerfile
|
| 2 |
+
|
| 3 |
+
# Multi-stage build for mem0 self-hosted on HF Spaces
|
| 4 |
+
# Stage 1: Build mem0 API and Dashboard
|
| 5 |
+
# Stage 2: Runtime with PostgreSQL, supervisord, nginx
|
| 6 |
+
|
| 7 |
+
# =============================================================================
|
| 8 |
+
# Stage 1: Build mem0 API (Python)
|
| 9 |
+
# =============================================================================
|
| 10 |
+
FROM python:3.12-slim-bookworm AS api-builder
|
| 11 |
+
|
| 12 |
+
WORKDIR /build/api
|
| 13 |
+
|
| 14 |
+
# Install system dependencies for building
|
| 15 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 16 |
+
build-essential \
|
| 17 |
+
git \
|
| 18 |
+
curl \
|
| 19 |
+
ca-certificates \
|
| 20 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 21 |
+
|
| 22 |
+
# Copy mem0 server source and root requirements
|
| 23 |
+
COPY server/ /build/api/
|
| 24 |
+
COPY requirements.txt /build/api/requirements.txt
|
| 25 |
+
|
| 26 |
+
# Install Python dependencies
|
| 27 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 28 |
+
|
| 29 |
+
# =============================================================================
|
| 30 |
+
# Stage 2: Build Dashboard (Next.js)
|
| 31 |
+
# =============================================================================
|
| 32 |
+
FROM node:20-alpine AS dashboard-builder
|
| 33 |
+
|
| 34 |
+
WORKDIR /build/dashboard
|
| 35 |
+
|
| 36 |
+
# Copy dashboard config files (package.json, next.config, tailwind, etc.)
|
| 37 |
+
COPY server/dashboard/ /build/dashboard/
|
| 38 |
+
|
| 39 |
+
# Fetch dashboard source from upstream mem0 repo (sparse clone of src/ and public/)
|
| 40 |
+
RUN apk add --no-cache git \
|
| 41 |
+
&& git clone --depth 1 --filter=blob:none --sparse \
|
| 42 |
+
https://github.com/mem0ai/mem0.git /tmp/mem0src \
|
| 43 |
+
&& cd /tmp/mem0src && git sparse-checkout set server/dashboard/src server/dashboard/public \
|
| 44 |
+
&& rm -rf /build/dashboard/src && cp -r /tmp/mem0src/server/dashboard/src /build/dashboard/src \
|
| 45 |
+
&& (cp -r /tmp/mem0src/server/dashboard/public /build/dashboard/public 2>/dev/null || mkdir -p /build/dashboard/public) \
|
| 46 |
+
&& rm -rf /tmp/mem0src
|
| 47 |
+
|
| 48 |
+
# Install dependencies
|
| 49 |
+
RUN npm install --no-audit --legacy-peer-deps
|
| 50 |
+
|
| 51 |
+
# Build Next.js standalone output - NEXT_PUBLIC_API_URL must be set at build time
|
| 52 |
+
ENV NEXT_TELEMETRY_DISABLED=1
|
| 53 |
+
ENV NEXT_PUBLIC_API_URL=/api
|
| 54 |
+
RUN npm run build
|
| 55 |
+
|
| 56 |
+
# Fix upstream bug: .env.http://localhost:7860/api is not a valid JS identifier
|
| 57 |
+
# Affects both server chunks (process.env.) and minified client bundles (s.env.)
|
| 58 |
+
# Server-side: replace with literal internal API URL
|
| 59 |
+
# Client-side: restore to NEXT_PUBLIC_API_URL with hardcoded fallback
|
| 60 |
+
RUN find /build/dashboard/.next -name '*.js' -exec \
|
| 61 |
+
sed -i 's|process\.env\.http://localhost:7860/api|"http://localhost:8000"|g' {} + 2>/dev/null || true && \
|
| 62 |
+
find /build/dashboard/.next -name '*.js' -exec \
|
| 63 |
+
sed -i 's|\.env\.http://localhost:7860/api|.env.NEXT_PUBLIC_API_URL||\"http://localhost:7860/api\"|g' {} + 2>/dev/null || true
|
| 64 |
+
|
| 65 |
+
# NOTE: Do NOT rewrite client PUT/DELETE on /api/auth/refresh to POST.
|
| 66 |
+
# Upstream contract (correct): PUT stores refresh_token cookie, POST rotates it,
|
| 67 |
+
# DELETE clears it. nginx routes /api/auth/refresh to the Next.js dashboard
|
| 68 |
+
# (see nginx.conf), which owns the httpOnly cookie — not to FastAPI.'
|
| 69 |
+
|
| 70 |
+
# =============================================================================
|
| 71 |
+
# Stage 3: Runtime - python:3.12-slim-bookworm with PostgreSQL, supervisord, nginx
|
| 72 |
+
# Pinned to bookworm so glibc matches api-builder exactly
|
| 73 |
+
# =============================================================================
|
| 74 |
+
FROM python:3.12-slim-bookworm
|
| 75 |
+
|
| 76 |
+
SHELL ["/bin/bash", "-c"]
|
| 77 |
+
|
| 78 |
+
# Environment variables
|
| 79 |
+
ENV PYTHONUNBUFFERED=1
|
| 80 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 81 |
+
ENV PGDATA=/data/pgdata
|
| 82 |
+
ENV PGPORT=5432
|
| 83 |
+
|
| 84 |
+
# Add PGDG apt repository for PostgreSQL 15 + pgvector
|
| 85 |
+
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates gnupg \
|
| 86 |
+
&& curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor -o /usr/share/keyrings/postgresql.gpg \
|
| 87 |
+
&& echo "deb [signed-by=/usr/share/keyrings/postgresql.gpg] https://apt.postgresql.org/pub/repos/apt bookworm-pgdg main" \
|
| 88 |
+
> /etc/apt/sources.list.d/pgdg.list \
|
| 89 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 90 |
+
|
| 91 |
+
# Install system dependencies
|
| 92 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 93 |
+
# PostgreSQL 15 + pgvector (from PGDG)
|
| 94 |
+
postgresql-15 \
|
| 95 |
+
postgresql-15-pgvector \
|
| 96 |
+
postgresql-client-15 \
|
| 97 |
+
# Node.js for dashboard runtime
|
| 98 |
+
nodejs \
|
| 99 |
+
npm \
|
| 100 |
+
# Process management
|
| 101 |
+
supervisor \
|
| 102 |
+
# Web server
|
| 103 |
+
nginx \
|
| 104 |
+
# Utilities
|
| 105 |
+
curl \
|
| 106 |
+
ca-certificates \
|
| 107 |
+
gosu \
|
| 108 |
+
procps \
|
| 109 |
+
vim \
|
| 110 |
+
nano \
|
| 111 |
+
htop \
|
| 112 |
+
bash \
|
| 113 |
+
git \
|
| 114 |
+
git-lfs \
|
| 115 |
+
gettext-base \
|
| 116 |
+
openssh-client \
|
| 117 |
+
tar \
|
| 118 |
+
gzip \
|
| 119 |
+
xz-utils \
|
| 120 |
+
bzip2 \
|
| 121 |
+
rsync \
|
| 122 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 123 |
+
|
| 124 |
+
# Create UID 1000 user for HF Spaces FUSE compatibility
|
| 125 |
+
RUN useradd -u 1000 -m -d /opt/data mem0 && \
|
| 126 |
+
mkdir -p /opt/data/{pgdata,sessions,logs,history} && \
|
| 127 |
+
chown -R 1000:1000 /opt/data
|
| 128 |
+
|
| 129 |
+
# Copy built API from builder stage (python:3.12-slim base means Python runtime is already present)
|
| 130 |
+
COPY --from=api-builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
|
| 131 |
+
COPY --from=api-builder /usr/local/bin/uvicorn /usr/local/bin/uvicorn
|
| 132 |
+
COPY --from=api-builder /build/api /opt/mem0/api
|
| 133 |
+
|
| 134 |
+
# Copy built Dashboard from builder stage
|
| 135 |
+
# dashboard/entrypoint.sh does `cd /app`, so deploy there
|
| 136 |
+
COPY --from=dashboard-builder /build/dashboard/.next/standalone /app
|
| 137 |
+
COPY --from=dashboard-builder /build/dashboard/.next/static /app/.next/static
|
| 138 |
+
COPY --from=dashboard-builder /build/dashboard/public /app/public
|
| 139 |
+
COPY --from=dashboard-builder /build/dashboard/entrypoint.sh /app/entrypoint.sh
|
| 140 |
+
RUN chmod +x /app/entrypoint.sh && \
|
| 141 |
+
chown -R 1000:1000 /app
|
| 142 |
+
# Keep /opt/mem0/dashboard as a symlink for compatibility
|
| 143 |
+
RUN ln -s /app /opt/mem0/dashboard
|
| 144 |
+
|
| 145 |
+
# Copy configuration files
|
| 146 |
+
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
|
| 147 |
+
COPY nginx.conf /etc/nginx/nginx.conf
|
| 148 |
+
COPY nginx-proxy.conf /etc/nginx/proxy.conf
|
| 149 |
+
COPY entrypoint.sh /entrypoint.sh
|
| 150 |
+
COPY init-db.sh /init-db.sh
|
| 151 |
+
|
| 152 |
+
RUN chmod +x /entrypoint.sh /init-db.sh
|
| 153 |
+
|
| 154 |
+
# Create runtime directories writable by mem0 (UID 1000)
|
| 155 |
+
RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx \
|
| 156 |
+
/var/log/supervisor /run/supervisor /var/run/postgresql \
|
| 157 |
+
/var/lib/nginx/body /var/lib/nginx/fastcgi \
|
| 158 |
+
/var/lib/nginx/proxy /var/lib/nginx/scgi /var/lib/nginx/uwsgi \
|
| 159 |
+
/app && \
|
| 160 |
+
chown -R 1000:1000 /var/log/nginx /var/cache/nginx /run/nginx \
|
| 161 |
+
/var/log/supervisor /run/supervisor /var/run/postgresql \
|
| 162 |
+
/var/lib/nginx
|
| 163 |
+
|
| 164 |
+
# Expose HF Spaces port
|
| 165 |
+
EXPOSE 7860
|
| 166 |
+
|
| 167 |
+
# Health check
|
| 168 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
| 169 |
+
CMD curl -f http://localhost:7860/health || exit 1
|
| 170 |
+
|
| 171 |
+
# Run as root for initialization, then drop to UID 1000
|
| 172 |
+
ENTRYPOINT ["/entrypoint.sh"]
|
README.md
CHANGED
|
@@ -1,10 +1,143 @@
|
|
| 1 |
-
---
|
| 2 |
title: Mem0
|
| 3 |
emoji: 📉
|
| 4 |
colorFrom: pink
|
| 5 |
colorTo: pink
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
-
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
title: Mem0
|
| 2 |
emoji: 📉
|
| 3 |
colorFrom: pink
|
| 4 |
colorTo: pink
|
| 5 |
sdk: docker
|
| 6 |
pinned: false
|
|
|
|
| 7 |
|
| 8 |
+
# mem0 Self-Hosted on HuggingFace Spaces
|
| 9 |
+
|
| 10 |
+
Single-container deployment of mem0 (API + Dashboard + PostgreSQL) for HuggingFace Spaces, following the patterns from `buzz` (single-container) and `hermes` (supervisord + nginx).
|
| 11 |
+
|
| 12 |
+
## Architecture
|
| 13 |
+
|
| 14 |
+
```
|
| 15 |
+
┌─────────────────────────────────────────────────────────────┐
|
| 16 |
+
│ Single Container (Port 7860) │
|
| 17 |
+
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
|
| 18 |
+
│ │ PostgreSQL │ │ mem0 API │ │ mem0 Dashboard │ │
|
| 19 |
+
│ │ (5432) │ │ (8000) │ │ (3000) │ │
|
| 20 |
+
│ └──────┬──────┘ └──────┬──────┘ └──────────┬──────────┘ │
|
| 21 |
+
│ │ │ │ │
|
| 22 |
+
│ └────────────────┼──────────────────────┘ │
|
| 23 |
+
│ ▼ │
|
| 24 |
+
│ ┌─────────────┐ │
|
| 25 |
+
│ │ Nginx │ │
|
| 26 |
+
│ │ (7860) │ │
|
| 27 |
+
│ └─────────────┘ │
|
| 28 |
+
│ │ │
|
| 29 |
+
│ ┌─────┴─────┐ │
|
| 30 |
+
│ │ Supervisord │
|
| 31 |
+
│ └───────────┘ │
|
| 32 |
+
└─────────────────────────────────────────────────────────────┘
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## Quick Start
|
| 36 |
+
|
| 37 |
+
### 1. Clone and Setup
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
cd mem0
|
| 41 |
+
cp .env.example .env
|
| 42 |
+
# Edit .env with your values (required: POSTGRES_PASSWORD, OPENAI_API_KEY, JWT_SECRET)
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
### 2. Build and Run
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
docker compose build
|
| 49 |
+
docker compose up -d
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
### 3. Access
|
| 53 |
+
|
| 54 |
+
- **Dashboard**: http://localhost:7860
|
| 55 |
+
- **API Docs**: http://localhost:7860/docs
|
| 56 |
+
- **Health Check**: http://localhost:7860/health
|
| 57 |
+
|
| 58 |
+
## Required Environment Variables
|
| 59 |
+
|
| 60 |
+
| Variable | Description | Required |
|
| 61 |
+
|----------|-------------|----------|
|
| 62 |
+
| `POSTGRES_PASSWORD` | PostgreSQL password (generate: `openssl rand -base64 32`) | Yes |
|
| 63 |
+
| `OPENAI_API_KEY` | OpenAI API key for LLM/embeddings | Yes |
|
| 64 |
+
| `JWT_SECRET` | JWT signing secret (generate: `openssl rand -base64 48`) | Yes |
|
| 65 |
+
| `ADMIN_API_KEY` | Optional admin API key (generate: `openssl rand -base64 32`) | No |
|
| 66 |
+
| `AUTH_DISABLED` | Set to `true` for local dev only | No (default: false) |
|
| 67 |
+
|
| 68 |
+
## Features
|
| 69 |
+
|
| 70 |
+
- ✅ **Single container** - All services in one container (like buzz)
|
| 71 |
+
- ✅ **HF Spaces compatible** - Singleton guard prevents duplicate runners
|
| 72 |
+
- ✅ **UID 1000** - Works with HF FUSE idmapped mounts
|
| 73 |
+
- ✅ **Supervisord** - Manages PostgreSQL, API, Dashboard, Nginx
|
| 74 |
+
- ✅ **Nginx routing** - Single port 7860 routes to all services
|
| 75 |
+
- ✅ **Persistent storage** - PostgreSQL data persisted to `/data` volume
|
| 76 |
+
- ✅ **Auth enabled by default** - Secure by default (JWT + API keys)
|
| 77 |
+
- ✅ **Health checks** - Built-in health endpoints
|
| 78 |
+
|
| 79 |
+
## Nginx Routing
|
| 80 |
+
|
| 81 |
+
| Path | Proxies To |
|
| 82 |
+
|------|------------|
|
| 83 |
+
| `/` | Dashboard (Next.js on 3000) |
|
| 84 |
+
| `/api/` | mem0 API (FastAPI on 8000) |
|
| 85 |
+
| `/docs` | OpenAPI docs |
|
| 86 |
+
| `/redoc` | ReDoc docs |
|
| 87 |
+
| `/openapi.json` | OpenAPI spec |
|
| 88 |
+
| `/health` | Health check (direct) |
|
| 89 |
+
|
| 90 |
+
## Data Persistence
|
| 91 |
+
|
| 92 |
+
- **PostgreSQL**: `/data/pgdata` → mapped to `mem0_data` volume
|
| 93 |
+
- **Request logs**: `/opt/data/history` → mapped to `mem0_history` volume
|
| 94 |
+
- **Backup/Restore**: Automatic sync to/from `/data` on startup/shutdown
|
| 95 |
+
|
| 96 |
+
## Development
|
| 97 |
+
|
| 98 |
+
### View Logs
|
| 99 |
+
|
| 100 |
+
```bash
|
| 101 |
+
docker compose logs -f mem0
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
### Access Container
|
| 105 |
+
|
| 106 |
+
```bash
|
| 107 |
+
docker compose exec mem0 bash
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
### Run Migrations Manually
|
| 111 |
+
|
| 112 |
+
```bash
|
| 113 |
+
docker compose exec mem0 gosu mem0 alembic upgrade head
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
## HF Spaces Deployment
|
| 117 |
+
|
| 118 |
+
1. Create new Space with **Docker** SDK
|
| 119 |
+
2. Push this repository
|
| 120 |
+
3. Set required secrets in Space settings:
|
| 121 |
+
- `POSTGRES_PASSWORD`
|
| 122 |
+
- `OPENAI_API_KEY`
|
| 123 |
+
- `JWT_SECRET`
|
| 124 |
+
- `ADMIN_API_KEY` (optional)
|
| 125 |
+
4. Space will auto-deploy on port 7860
|
| 126 |
+
|
| 127 |
+
## Troubleshooting
|
| 128 |
+
|
| 129 |
+
### PostgreSQL won't start
|
| 130 |
+
Check logs: `docker compose logs mem0 | grep postgresql`
|
| 131 |
+
|
| 132 |
+
### Dashboard shows "API connection failed"
|
| 133 |
+
Verify `NEXT_PUBLIC_API_URL=http://localhost:7860/api` in environment
|
| 134 |
+
|
| 135 |
+
### Auth errors
|
| 136 |
+
Ensure `JWT_SECRET` is set and `AUTH_DISABLED=false` (default)
|
| 137 |
+
|
| 138 |
+
### Port conflicts
|
| 139 |
+
Change port mapping in `docker-compose.yml`: `"7860:7860"` → `"YOUR_PORT:7860"`
|
| 140 |
+
|
| 141 |
+
## License
|
| 142 |
+
|
| 143 |
+
Apache 2.0 - Based on mem0 (https://github.com/mem0ai/mem0)
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mem0 Self-Hosted - docker-compose.yml
|
| 2 |
+
|
| 3 |
+
services:
|
| 4 |
+
mem0:
|
| 5 |
+
build: .
|
| 6 |
+
container_name: mem0
|
| 7 |
+
ports:
|
| 8 |
+
- "7864:7860"
|
| 9 |
+
env_file:
|
| 10 |
+
- .env
|
| 11 |
+
environment:
|
| 12 |
+
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
|
| 13 |
+
- OPENAI_API_KEY=${OPENAI_API_KEY}
|
| 14 |
+
- JWT_SECRET=${JWT_SECRET}
|
| 15 |
+
- ADMIN_API_KEY=${ADMIN_API_KEY:-}
|
| 16 |
+
- AUTH_DISABLED=${AUTH_DISABLED:-false}
|
| 17 |
+
- MEM0_TELEMETRY=${MEM0_TELEMETRY:-true}
|
| 18 |
+
- DASHBOARD_URL=http://localhost:7860
|
| 19 |
+
- NEXT_PUBLIC_API_URL=/api
|
| 20 |
+
- NEXT_PUBLIC_INSTANCE_NAME=Mem0
|
| 21 |
+
# 127.0.0.1, not localhost: Node >=17 resolves localhost to ::1 first and
|
| 22 |
+
# uvicorn listens on IPv4 only -> ECONNREFUSED during token rotation
|
| 23 |
+
- API_INTERNAL_URL=http://127.0.0.1:8000
|
| 24 |
+
- MEM0_DEFAULT_LLM_MODEL=${MEM0_DEFAULT_LLM_MODEL:-gpt-5-mini}
|
| 25 |
+
- MEM0_DEFAULT_EMBEDDER_MODEL=${MEM0_DEFAULT_EMBEDDER_MODEL:-text-embedding-3-small}
|
| 26 |
+
volumes:
|
| 27 |
+
- mem0_data:/data
|
| 28 |
+
- mem0_history:/opt/mem0/api/history
|
| 29 |
+
|
| 30 |
+
volumes:
|
| 31 |
+
mem0_data:
|
| 32 |
+
mem0_history:
|
entrypoint.sh
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
BOOT_START=$(date +%s)
|
| 5 |
+
|
| 6 |
+
echo "[entrypoint] mem0 Self-Hosted on HuggingFace Spaces"
|
| 7 |
+
echo "==============================================================================="
|
| 8 |
+
|
| 9 |
+
# ── Configuration ───────────────────────────────────────────────────────────
|
| 10 |
+
MEM0_WORK="/opt/data" # Fast local filesystem (working dir)
|
| 11 |
+
MEM0_BACKUP="/data" # HF mounted bucket (backup only)
|
| 12 |
+
MEM0_UID=1000
|
| 13 |
+
MEM0_GID=1000
|
| 14 |
+
SYNC_INTERVAL="${SYNC_INTERVAL:-60}" # Default: sync every 1 minute
|
| 15 |
+
|
| 16 |
+
# ── Singleton guard ──────────────────────────────────────────────────────────
|
| 17 |
+
# Hanya satu instance yang menjalankan steps. Instance duplikat (dari HF rapid-
|
| 18 |
+
# restart) cukup sleep infinity — tidak exit (exit = HF restart lagi).
|
| 19 |
+
# MEM0_ENTRYPOINT_OWNER di-export sebelum exec gosu sehingga instance setelah
|
| 20 |
+
# privilege-drop tahu dia adalah kelanjutan sah, bukan duplikat.
|
| 21 |
+
ENTRYPOINT_PID_FILE="/tmp/mem0-entrypoint.pid"
|
| 22 |
+
ENTRYPOINT_LOG="/tmp/mem0-entrypoint.log"
|
| 23 |
+
|
| 24 |
+
# Always clear stale PID file at container startup (new container = new PID namespace)
|
| 25 |
+
rm -f "$ENTRYPOINT_PID_FILE" "$ENTRYPOINT_LOG" 2>/dev/null || true
|
| 26 |
+
|
| 27 |
+
if [ -z "${MEM0_ENTRYPOINT_OWNER:-}" ]; then
|
| 28 |
+
# Instance baru tanpa token → cek apakah ada instance lain yang sudah running
|
| 29 |
+
if [ -f "$ENTRYPOINT_PID_FILE" ]; then
|
| 30 |
+
OLD_PID=$(cat "$ENTRYPOINT_PID_FILE" 2>/dev/null || echo "")
|
| 31 |
+
if [ -n "$OLD_PID" ] && kill -0 "$OLD_PID" 2>/dev/null; then
|
| 32 |
+
echo "[entrypoint] Instance $OLD_PID already running — standing by silently."
|
| 33 |
+
sleep infinity
|
| 34 |
+
exit 0
|
| 35 |
+
else
|
| 36 |
+
echo "[entrypoint] Stale PID $OLD_PID (dead) — taking over..."
|
| 37 |
+
rm -f "$ENTRYPOINT_PID_FILE" "$ENTRYPOINT_LOG" 2>/dev/null || true
|
| 38 |
+
fi
|
| 39 |
+
fi
|
| 40 |
+
echo $$ > "$ENTRYPOINT_PID_FILE"
|
| 41 |
+
export MEM0_ENTRYPOINT_OWNER=$$
|
| 42 |
+
# Buat log world-writable sekarang (sebagai root) agar mem0 bisa write setelah gosu
|
| 43 |
+
touch "$ENTRYPOINT_LOG" && chmod 666 "$ENTRYPOINT_LOG"
|
| 44 |
+
fi
|
| 45 |
+
|
| 46 |
+
exec > >(tee -a "$ENTRYPOINT_LOG") 2>&1
|
| 47 |
+
|
| 48 |
+
# ── Helper: Safe Sync (EXCLUDE large/temp files) ───────────────────────────
|
| 49 |
+
safe_sync() {
|
| 50 |
+
local SRC="$1"
|
| 51 |
+
local DST="$2"
|
| 52 |
+
|
| 53 |
+
if [ ! -d "$SRC" ]; then
|
| 54 |
+
echo " Source $SRC does not exist, skipping sync"
|
| 55 |
+
return 0
|
| 56 |
+
fi
|
| 57 |
+
|
| 58 |
+
mkdir -p "$DST"
|
| 59 |
+
|
| 60 |
+
echo " Syncing: $SRC -> $DST"
|
| 61 |
+
echo " Excluding: node_modules, .cache, logs, *.tmp, *.lock, *.pid, __pycache__"
|
| 62 |
+
|
| 63 |
+
rsync -a --checksum --delete \
|
| 64 |
+
--no-owner --no-group \
|
| 65 |
+
--exclude='node_modules' \
|
| 66 |
+
--exclude='.cache' \
|
| 67 |
+
--exclude='.next/cache' \
|
| 68 |
+
--exclude='logs' \
|
| 69 |
+
--exclude='*.log' \
|
| 70 |
+
--exclude='*.log.*' \
|
| 71 |
+
--exclude='*.tmp' \
|
| 72 |
+
--exclude='*.lock' \
|
| 73 |
+
--exclude='*.pid' \
|
| 74 |
+
--exclude='__pycache__' \
|
| 75 |
+
--exclude='*.pyc' \
|
| 76 |
+
--exclude='state.db-wal' \
|
| 77 |
+
--exclude='state.db-shm' \
|
| 78 |
+
"$SRC/" "$DST/"
|
| 79 |
+
|
| 80 |
+
echo " ✓ Sync completed"
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
# ── Stage 1: Restore from backup (as root, before privilege drop) ──────────
|
| 84 |
+
if [ "$(id -u)" = "0" ]; then
|
| 85 |
+
echo ""
|
| 86 |
+
echo "=== 1. Restoring mem0 data from persistent storage ==="
|
| 87 |
+
|
| 88 |
+
# Create working directory on fast local filesystem
|
| 89 |
+
mkdir -p "$MEM0_WORK"/{pgdata,sessions,logs,history}
|
| 90 |
+
mkdir -p "$MEM0_BACKUP"/{pgdata,sessions,logs,history}
|
| 91 |
+
chown -R ${MEM0_UID}:${MEM0_GID} "$MEM0_BACKUP"
|
| 92 |
+
|
| 93 |
+
# Restore from backup if exists
|
| 94 |
+
if [ -d "$MEM0_BACKUP/pgdata" ] && [ "$(ls -A $MEM0_BACKUP/pgdata 2>/dev/null | wc -l)" -gt 0 ]; then
|
| 95 |
+
echo "Found existing PostgreSQL data in $MEM0_BACKUP/pgdata"
|
| 96 |
+
RESTORE_START=$(date +%s)
|
| 97 |
+
safe_sync "$MEM0_BACKUP/pgdata" "$MEM0_WORK/pgdata"
|
| 98 |
+
RESTORE_END=$(date +%s)
|
| 99 |
+
echo "[TIMER] Restore from backup: $((RESTORE_END - RESTORE_START))s"
|
| 100 |
+
echo "PostgreSQL data restored"
|
| 101 |
+
else
|
| 102 |
+
echo "No existing backup found, will initialize fresh PostgreSQL"
|
| 103 |
+
fi
|
| 104 |
+
|
| 105 |
+
# Restore history if exists
|
| 106 |
+
if [ -d "$MEM0_BACKUP/history" ] && [ "$(ls -A $MEM0_BACKUP/history 2>/dev/null | wc -l)" -gt 0 ]; then
|
| 107 |
+
echo "Found existing history in $MEM0_BACKUP/history"
|
| 108 |
+
safe_sync "$MEM0_BACKUP/history" "$MEM0_WORK/history"
|
| 109 |
+
echo "History restored"
|
| 110 |
+
fi
|
| 111 |
+
fi
|
| 112 |
+
|
| 113 |
+
# ── Stage 2: Initialize PostgreSQL (as root) ───────────────────────────────
|
| 114 |
+
if [ "$(id -u)" = "0" ]; then
|
| 115 |
+
echo ""
|
| 116 |
+
echo "=== 2. Initializing PostgreSQL ==="
|
| 117 |
+
|
| 118 |
+
PGDATA="$MEM0_WORK/pgdata"
|
| 119 |
+
PGLOG="/var/log/postgresql/pg.log"
|
| 120 |
+
|
| 121 |
+
mkdir -p /var/log/postgresql
|
| 122 |
+
chown -R ${MEM0_UID}:${MEM0_GID} /var/log/postgresql
|
| 123 |
+
|
| 124 |
+
# Initialize PostgreSQL if not already initialized
|
| 125 |
+
if [ ! -f "$PGDATA/PG_VERSION" ]; then
|
| 126 |
+
echo "Initializing new PostgreSQL cluster..."
|
| 127 |
+
INIT_START=$(date +%s)
|
| 128 |
+
|
| 129 |
+
# Run initdb as mem0 user
|
| 130 |
+
gosu mem0 /usr/lib/postgresql/15/bin/initdb -D "$PGDATA" --auth=trust --encoding=UTF8 --locale=C.UTF-8
|
| 131 |
+
|
| 132 |
+
# Configure PostgreSQL for local connections
|
| 133 |
+
cat >> "$PGDATA/postgresql.conf" <<EOF
|
| 134 |
+
listen_addresses = 'localhost'
|
| 135 |
+
port = 5432
|
| 136 |
+
max_connections = 100
|
| 137 |
+
shared_buffers = 128MB
|
| 138 |
+
effective_cache_size = 512MB
|
| 139 |
+
maintenance_work_mem = 64MB
|
| 140 |
+
checkpoint_completion_target = 0.9
|
| 141 |
+
wal_buffers = 16MB
|
| 142 |
+
default_statistics_target = 100
|
| 143 |
+
random_page_cost = 1.1
|
| 144 |
+
effective_io_concurrency = 200
|
| 145 |
+
work_mem = 4MB
|
| 146 |
+
min_wal_size = 1GB
|
| 147 |
+
max_wal_size = 4GB
|
| 148 |
+
EOF
|
| 149 |
+
|
| 150 |
+
# Allow local connections without password
|
| 151 |
+
cat > "$PGDATA/pg_hba.conf" <<EOF
|
| 152 |
+
local all all trust
|
| 153 |
+
host all all 127.0.0.1/32 trust
|
| 154 |
+
host all all ::1/128 trust
|
| 155 |
+
EOF
|
| 156 |
+
|
| 157 |
+
chown -R ${MEM0_UID}:${MEM0_GID} "$PGDATA"
|
| 158 |
+
|
| 159 |
+
INIT_END=$(date +%s)
|
| 160 |
+
echo "[TIMER] PostgreSQL init: $((INIT_END - INIT_START))s"
|
| 161 |
+
echo "PostgreSQL initialized"
|
| 162 |
+
else
|
| 163 |
+
echo "PostgreSQL already initialized"
|
| 164 |
+
fi
|
| 165 |
+
|
| 166 |
+
# Start postgres temporarily to run init-db, then stop it
|
| 167 |
+
echo "Running database initialization script..."
|
| 168 |
+
PGLOG="/tmp/pg-init.log"
|
| 169 |
+
touch "$PGLOG" && chown ${MEM0_UID}:${MEM0_GID} "$PGLOG"
|
| 170 |
+
set +e
|
| 171 |
+
gosu mem0 /usr/lib/postgresql/15/bin/pg_ctl -D "$PGDATA" -l "$PGLOG" -w start
|
| 172 |
+
PG_START_RC=$?
|
| 173 |
+
set -e
|
| 174 |
+
echo "[pg_ctl start exit: $PG_START_RC]"
|
| 175 |
+
echo "=== pg startup log ==="
|
| 176 |
+
cat "$PGLOG"
|
| 177 |
+
echo "=== end pg log ==="
|
| 178 |
+
if [ "$PG_START_RC" -ne 0 ]; then
|
| 179 |
+
echo "[ERROR] PostgreSQL failed to start; aborting"
|
| 180 |
+
exit 1
|
| 181 |
+
fi
|
| 182 |
+
gosu mem0 /init-db.sh
|
| 183 |
+
gosu mem0 /usr/lib/postgresql/15/bin/pg_ctl -D "$PGDATA" -w stop
|
| 184 |
+
fi
|
| 185 |
+
|
| 186 |
+
# ── Stage 3: Start supervisord (drop to mem0 user) ─────────────────────────
|
| 187 |
+
echo ""
|
| 188 |
+
echo "=== 3. Starting services via supervisord ==="
|
| 189 |
+
|
| 190 |
+
# Drop privileges and run supervisord as mem0 user
|
| 191 |
+
exec gosu mem0 supervisord -c /etc/supervisor/conf.d/supervisord.conf
|
init-db.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
echo "[init-db] Initializing mem0 database..."
|
| 5 |
+
|
| 6 |
+
# Wait for PostgreSQL to be ready
|
| 7 |
+
until pg_isready -q -h localhost -p 5432 -U mem0; do
|
| 8 |
+
echo "[init-db] Waiting for PostgreSQL..."
|
| 9 |
+
sleep 2
|
| 10 |
+
done
|
| 11 |
+
|
| 12 |
+
echo "[init-db] PostgreSQL is ready"
|
| 13 |
+
|
| 14 |
+
# Create database and user if they don't exist
|
| 15 |
+
psql -h localhost -p 5432 -U mem0 -d postgres <<-EOSQL
|
| 16 |
+
-- Create mem0 database
|
| 17 |
+
SELECT 'CREATE DATABASE mem0' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mem0')\gexec
|
| 18 |
+
|
| 19 |
+
-- Create mem0_app database for auth/config
|
| 20 |
+
SELECT 'CREATE DATABASE mem0_app' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mem0_app')\gexec
|
| 21 |
+
|
| 22 |
+
-- Enable pgvector extension on both databases
|
| 23 |
+
\c mem0
|
| 24 |
+
CREATE EXTENSION IF NOT EXISTS vector;
|
| 25 |
+
|
| 26 |
+
\c mem0_app
|
| 27 |
+
CREATE EXTENSION IF NOT EXISTS vector;
|
| 28 |
+
EOSQL
|
| 29 |
+
|
| 30 |
+
echo "[init-db] Database initialization complete"
|
nginx-proxy.conf
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Proxy configuration for nginx
|
| 2 |
+
proxy_set_header Host $host;
|
| 3 |
+
proxy_set_header X-Real-IP $remote_addr;
|
| 4 |
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
| 5 |
+
proxy_set_header X-Forwarded-Proto $scheme;
|
| 6 |
+
proxy_set_header X-Forwarded-Host $host;
|
| 7 |
+
proxy_set_header X-Forwarded-Port $server_port;
|
| 8 |
+
proxy_set_header Upgrade $http_upgrade;
|
| 9 |
+
proxy_set_header Connection "upgrade";
|
| 10 |
+
proxy_redirect off;
|
| 11 |
+
proxy_read_timeout 300s;
|
| 12 |
+
proxy_send_timeout 300s;
|
| 13 |
+
proxy_connect_timeout 10s;
|
| 14 |
+
proxy_buffering off;
|
| 15 |
+
proxy_request_buffering off;
|
| 16 |
+
proxy_http_version 1.1;
|
nginx.conf
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
worker_processes auto;
|
| 2 |
+
error_log /var/log/nginx/error.log warn;
|
| 3 |
+
pid /var/log/nginx/nginx.pid;
|
| 4 |
+
|
| 5 |
+
events {
|
| 6 |
+
worker_connections 1024;
|
| 7 |
+
use epoll;
|
| 8 |
+
multi_accept on;
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
http {
|
| 12 |
+
include /etc/nginx/mime.types;
|
| 13 |
+
default_type application/octet-stream;
|
| 14 |
+
|
| 15 |
+
# Logging
|
| 16 |
+
access_log /var/log/nginx/access.log combined;
|
| 17 |
+
error_log /var/log/nginx/error.log warn;
|
| 18 |
+
|
| 19 |
+
# Performance
|
| 20 |
+
sendfile on;
|
| 21 |
+
tcp_nopush on;
|
| 22 |
+
tcp_nodelay on;
|
| 23 |
+
keepalive_timeout 65;
|
| 24 |
+
types_hash_max_size 2048;
|
| 25 |
+
client_max_body_size 50M;
|
| 26 |
+
|
| 27 |
+
# Gzip
|
| 28 |
+
gzip on;
|
| 29 |
+
gzip_vary on;
|
| 30 |
+
gzip_min_length 1024;
|
| 31 |
+
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml application/json application/rss+xml;
|
| 32 |
+
|
| 33 |
+
# Upstream servers
|
| 34 |
+
upstream mem0_api {
|
| 35 |
+
server 127.0.0.1:8000;
|
| 36 |
+
keepalive 32;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
upstream mem0_dashboard {
|
| 40 |
+
server 127.0.0.1:3000;
|
| 41 |
+
keepalive 32;
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
# Include proxy config
|
| 45 |
+
include /etc/nginx/proxy.conf;
|
| 46 |
+
|
| 47 |
+
server {
|
| 48 |
+
listen 7860;
|
| 49 |
+
listen [::]:7860;
|
| 50 |
+
server_name _;
|
| 51 |
+
|
| 52 |
+
# Root for static files (dashboard)
|
| 53 |
+
root /opt/mem0/dashboard/public;
|
| 54 |
+
|
| 55 |
+
# Health check endpoint (before auth)
|
| 56 |
+
location /health {
|
| 57 |
+
access_log off;
|
| 58 |
+
return 200 "healthy\n";
|
| 59 |
+
add_header Content-Type text/plain;
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
# Auth cookie endpoints are owned by the Next.js dashboard (sets/clears
|
| 63 |
+
# the httpOnly mem0_refresh_token cookie) - must match before /api/
|
| 64 |
+
location = /api/auth/refresh {
|
| 65 |
+
proxy_pass http://mem0_dashboard/api/auth/refresh;
|
| 66 |
+
include /etc/nginx/proxy.conf;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
# API routes - proxy to mem0 API
|
| 70 |
+
location /api/ {
|
| 71 |
+
proxy_pass http://mem0_api/;
|
| 72 |
+
include /etc/nginx/proxy.conf;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
# OpenAPI docs
|
| 76 |
+
location /docs {
|
| 77 |
+
proxy_pass http://mem0_api/docs;
|
| 78 |
+
include /etc/nginx/proxy.conf;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
location /redoc {
|
| 82 |
+
proxy_pass http://mem0_api/redoc;
|
| 83 |
+
include /etc/nginx/proxy.conf;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
location /openapi.json {
|
| 87 |
+
proxy_pass http://mem0_api/openapi.json;
|
| 88 |
+
include /etc/nginx/proxy.conf;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
# Dashboard - proxy to Next.js
|
| 92 |
+
location / {
|
| 93 |
+
proxy_pass http://mem0_dashboard/;
|
| 94 |
+
include /etc/nginx/proxy.conf;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
# Static files - serve directly for performance
|
| 98 |
+
location /_next/static/ {
|
| 99 |
+
alias /opt/mem0/dashboard/.next/static/;
|
| 100 |
+
expires 1y;
|
| 101 |
+
add_header Cache-Control "public, immutable";
|
| 102 |
+
access_log off;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
location /_next/image/ {
|
| 106 |
+
proxy_pass http://mem0_dashboard/_next/image/;
|
| 107 |
+
include /etc/nginx/proxy.conf;
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
# Favicon and public assets
|
| 111 |
+
location ~* \.(ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$ {
|
| 112 |
+
expires 1y;
|
| 113 |
+
add_header Cache-Control "public, immutable";
|
| 114 |
+
access_log off;
|
| 115 |
+
try_files $uri @dashboard;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
location @dashboard {
|
| 119 |
+
proxy_pass http://mem0_dashboard;
|
| 120 |
+
include /etc/nginx/proxy.conf;
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mem0 Self-Hosted - Python Requirements
|
| 2 |
+
# Based on mem0 server/requirements.txt
|
| 3 |
+
|
| 4 |
+
# Core FastAPI
|
| 5 |
+
fastapi==0.115.8
|
| 6 |
+
uvicorn==0.34.0
|
| 7 |
+
pydantic[email]==2.10.4
|
| 8 |
+
python-dotenv==1.2.2
|
| 9 |
+
|
| 10 |
+
# Database
|
| 11 |
+
sqlalchemy>=2.0,<3.0
|
| 12 |
+
alembic>=1.13,<2.0
|
| 13 |
+
psycopg>=3.2.8
|
| 14 |
+
psycopg-pool>=3.2.6,<4.0.0
|
| 15 |
+
|
| 16 |
+
# Auth
|
| 17 |
+
passlib[bcrypt]>=1.7,<2.0
|
| 18 |
+
bcrypt==4.0.1
|
| 19 |
+
python-jose[cryptography]>=3.3,<4.0
|
| 20 |
+
cryptography>=46.0.4
|
| 21 |
+
|
| 22 |
+
# Rate limiting
|
| 23 |
+
slowapi>=0.1.9,<1.0
|
| 24 |
+
|
| 25 |
+
# Telemetry
|
| 26 |
+
posthog>=3.0,<8.0
|
| 27 |
+
|
| 28 |
+
# LLM Providers (bundled)
|
| 29 |
+
anthropic>=0.39,<1.0
|
| 30 |
+
google-generativeai>=0.8,<1.0
|
| 31 |
+
|
| 32 |
+
# OpenAI-compatible proxy client (mem0.proxy.main)
|
| 33 |
+
litellm>=1.40
|
| 34 |
+
openai>=1.0,<2.0
|
| 35 |
+
|
| 36 |
+
# mem0 core
|
| 37 |
+
mem0ai>=0.1.48
|
| 38 |
+
|
| 39 |
+
# Utilities
|
| 40 |
+
pyyaml>=6.0
|
| 41 |
+
requests>=2.31
|
| 42 |
+
httpx>=0.27
|
server/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mem0 Self-Hosted - Server Directory Structure
|
| 2 |
+
# This directory should contain the mem0 server source code
|
| 3 |
+
# Copy from https://github.com/mem0ai/mem0/tree/main/server
|
| 4 |
+
|
| 5 |
+
# Required files:
|
| 6 |
+
# - main.py (FastAPI app)
|
| 7 |
+
# - auth.py
|
| 8 |
+
# - db.py
|
| 9 |
+
# - models.py
|
| 10 |
+
# - schemas.py
|
| 11 |
+
# - routers/ (api_keys, auth, entities, requests)
|
| 12 |
+
# - alembic/ (migrations)
|
| 13 |
+
# - alembic.ini
|
| 14 |
+
# - init-db.sh (already created at root)
|
| 15 |
+
|
| 16 |
+
# For now, this is a placeholder. The actual server code should be copied from
|
| 17 |
+
# the mem0 repository: https://github.com/mem0ai/mem0/tree/main/server
|
| 18 |
+
|
| 19 |
+
# To set up:
|
| 20 |
+
# 1. git clone https://github.com/mem0ai/mem0.git /tmp/mem0
|
| 21 |
+
# 2. cp -r /tmp/mem0/server/* ./server/
|
| 22 |
+
# 3. cp /tmp/mem0/server/dashboard ./server/dashboard
|
server/alembic.ini
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[alembic]
|
| 2 |
+
script_location = alembic
|
| 3 |
+
prepend_sys_path = .
|
| 4 |
+
sqlalchemy.url = postgresql+psycopg://mem0:postgres@localhost:5432/mem0_app
|
| 5 |
+
|
| 6 |
+
[loggers]
|
| 7 |
+
keys = root,sqlalchemy,alembic
|
| 8 |
+
|
| 9 |
+
[handlers]
|
| 10 |
+
keys = console
|
| 11 |
+
|
| 12 |
+
[formatters]
|
| 13 |
+
keys = generic
|
| 14 |
+
|
| 15 |
+
[logger_root]
|
| 16 |
+
level = WARN
|
| 17 |
+
handlers = console
|
| 18 |
+
|
| 19 |
+
[logger_sqlalchemy]
|
| 20 |
+
level = WARN
|
| 21 |
+
handlers =
|
| 22 |
+
qualname = sqlalchemy.engine
|
| 23 |
+
|
| 24 |
+
[logger_alembic]
|
| 25 |
+
level = INFO
|
| 26 |
+
handlers =
|
| 27 |
+
qualname = alembic
|
| 28 |
+
|
| 29 |
+
[handler_console]
|
| 30 |
+
class = StreamHandler
|
| 31 |
+
args = (sys.stderr,)
|
| 32 |
+
level = NOTSET
|
| 33 |
+
formatter = generic
|
| 34 |
+
|
| 35 |
+
[formatter_generic]
|
| 36 |
+
format = %(levelname)-5.5s [%(name)s] %(message)s
|
| 37 |
+
datefmt = %H:%M:%S
|
server/alembic/env.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Import models so Base.metadata picks up all tables
|
| 2 |
+
import models # noqa: F401
|
| 3 |
+
|
| 4 |
+
from logging.config import fileConfig
|
| 5 |
+
|
| 6 |
+
from alembic import context
|
| 7 |
+
from sqlalchemy import engine_from_config, pool
|
| 8 |
+
|
| 9 |
+
from db import Base, _build_database_url
|
| 10 |
+
|
| 11 |
+
config = context.config
|
| 12 |
+
|
| 13 |
+
if config.config_file_name is not None:
|
| 14 |
+
fileConfig(config.config_file_name)
|
| 15 |
+
|
| 16 |
+
target_metadata = Base.metadata
|
| 17 |
+
|
| 18 |
+
# Override sqlalchemy.url from alembic.ini with the runtime database URL
|
| 19 |
+
config.set_main_option("sqlalchemy.url", _build_database_url())
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def run_migrations_offline() -> None:
|
| 23 |
+
url = config.get_main_option("sqlalchemy.url")
|
| 24 |
+
context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
|
| 25 |
+
with context.begin_transaction():
|
| 26 |
+
context.run_migrations()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def run_migrations_online() -> None:
|
| 30 |
+
connectable = engine_from_config(
|
| 31 |
+
config.get_section(config.config_ini_section, {}),
|
| 32 |
+
prefix="sqlalchemy.",
|
| 33 |
+
poolclass=pool.NullPool,
|
| 34 |
+
)
|
| 35 |
+
with connectable.connect() as connection:
|
| 36 |
+
context.configure(connection=connection, target_metadata=target_metadata)
|
| 37 |
+
with context.begin_transaction():
|
| 38 |
+
context.run_migrations()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if context.is_offline_mode():
|
| 42 |
+
run_migrations_offline()
|
| 43 |
+
else:
|
| 44 |
+
run_migrations_online()
|
server/alembic/script.py.mako
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""${message}
|
| 2 |
+
|
| 3 |
+
Revision ID: ${up_revision}
|
| 4 |
+
Revises: ${down_revision | comma,n}
|
| 5 |
+
Create Date: ${create_date}
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from typing import Sequence, Union
|
| 9 |
+
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
${imports if imports else ""}
|
| 13 |
+
|
| 14 |
+
# revision identifiers, used by Alembic.
|
| 15 |
+
revision: str = ${repr(up_revision)}
|
| 16 |
+
down_revision: Union[str, None] = ${repr(down_revision)}
|
| 17 |
+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
| 18 |
+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def upgrade() -> None:
|
| 22 |
+
${upgrades if upgrades else "pass"}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def downgrade() -> None:
|
| 26 |
+
${downgrades if downgrades else "pass"}
|
server/alembic/versions/001_create_users_and_api_keys.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Create users and api_keys tables
|
| 2 |
+
|
| 3 |
+
Revision ID: 001
|
| 4 |
+
Revises: None
|
| 5 |
+
Create Date: 2026-04-10
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Sequence, Union
|
| 10 |
+
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
from alembic import op
|
| 13 |
+
|
| 14 |
+
revision: str = "001"
|
| 15 |
+
down_revision: Union[str, None] = None
|
| 16 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 17 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def upgrade() -> None:
|
| 21 |
+
op.create_table(
|
| 22 |
+
"users",
|
| 23 |
+
sa.Column("id", sa.Uuid(), primary_key=True),
|
| 24 |
+
sa.Column("name", sa.String(255), nullable=False),
|
| 25 |
+
sa.Column("email", sa.String(255), nullable=False),
|
| 26 |
+
sa.Column("password_hash", sa.Text(), nullable=False),
|
| 27 |
+
sa.Column("role", sa.String(20), nullable=False, server_default="admin"),
|
| 28 |
+
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
| 29 |
+
sa.Column("last_login_at", sa.DateTime(timezone=True), nullable=True),
|
| 30 |
+
sa.UniqueConstraint("email"),
|
| 31 |
+
)
|
| 32 |
+
op.create_index("ix_users_email", "users", ["email"])
|
| 33 |
+
|
| 34 |
+
op.create_table(
|
| 35 |
+
"api_keys",
|
| 36 |
+
sa.Column("id", sa.Uuid(), primary_key=True),
|
| 37 |
+
sa.Column("key_prefix", sa.String(12), nullable=False),
|
| 38 |
+
sa.Column("key_hash", sa.Text(), nullable=False),
|
| 39 |
+
sa.Column("label", sa.String(255), nullable=False),
|
| 40 |
+
sa.Column("created_by", sa.Uuid(), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
|
| 41 |
+
sa.Column("last_used_at", sa.DateTime(timezone=True), nullable=True),
|
| 42 |
+
sa.Column("revoked_at", sa.DateTime(timezone=True), nullable=True),
|
| 43 |
+
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def downgrade() -> None:
|
| 48 |
+
op.drop_table("api_keys")
|
| 49 |
+
op.drop_table("users")
|
server/alembic/versions/002_create_request_logs.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Create request_logs table
|
| 2 |
+
|
| 3 |
+
Revision ID: 002
|
| 4 |
+
Revises: 001
|
| 5 |
+
Create Date: 2026-04-13
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Sequence, Union
|
| 10 |
+
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
from alembic import op
|
| 13 |
+
|
| 14 |
+
revision: str = "002"
|
| 15 |
+
down_revision: Union[str, None] = "001"
|
| 16 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 17 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def upgrade() -> None:
|
| 21 |
+
op.create_table(
|
| 22 |
+
"request_logs",
|
| 23 |
+
sa.Column("id", sa.Uuid(), primary_key=True),
|
| 24 |
+
sa.Column("method", sa.String(16), nullable=False),
|
| 25 |
+
sa.Column("path", sa.String(512), nullable=False),
|
| 26 |
+
sa.Column("status_code", sa.Integer(), nullable=False),
|
| 27 |
+
sa.Column("latency_ms", sa.Float(), nullable=False),
|
| 28 |
+
sa.Column("auth_type", sa.String(32), nullable=False, server_default="none"),
|
| 29 |
+
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
| 30 |
+
)
|
| 31 |
+
op.create_index("ix_request_logs_created_at", "request_logs", ["created_at"])
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def downgrade() -> None:
|
| 35 |
+
op.drop_index("ix_request_logs_created_at", table_name="request_logs")
|
| 36 |
+
op.drop_table("request_logs")
|
server/alembic/versions/003_create_settings.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Create settings table
|
| 2 |
+
|
| 3 |
+
Revision ID: 003
|
| 4 |
+
Revises: 002
|
| 5 |
+
Create Date: 2026-04-15
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Sequence, Union
|
| 10 |
+
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
from alembic import op
|
| 13 |
+
|
| 14 |
+
revision: str = "003"
|
| 15 |
+
down_revision: Union[str, None] = "002"
|
| 16 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 17 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def upgrade() -> None:
|
| 21 |
+
op.create_table(
|
| 22 |
+
"settings",
|
| 23 |
+
sa.Column("key", sa.String(255), primary_key=True),
|
| 24 |
+
sa.Column("value", sa.Text(), nullable=False),
|
| 25 |
+
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def downgrade() -> None:
|
| 30 |
+
op.drop_table("settings")
|
server/alembic/versions/004_unique_admin_role.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Enforce at-most-one admin via partial unique index
|
| 2 |
+
|
| 3 |
+
Revision ID: 004
|
| 4 |
+
Revises: 003
|
| 5 |
+
Create Date: 2026-04-21
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Sequence, Union
|
| 10 |
+
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
from alembic import op
|
| 13 |
+
|
| 14 |
+
revision: str = "004"
|
| 15 |
+
down_revision: Union[str, None] = "003"
|
| 16 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 17 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def upgrade() -> None:
|
| 21 |
+
op.create_index(
|
| 22 |
+
"ix_users_only_one_admin",
|
| 23 |
+
"users",
|
| 24 |
+
["role"],
|
| 25 |
+
unique=True,
|
| 26 |
+
postgresql_where=sa.text("role = 'admin'"),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def downgrade() -> None:
|
| 31 |
+
op.drop_index("ix_users_only_one_admin", table_name="users")
|
server/alembic/versions/005_refresh_token_jtis.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Create refresh_token_jtis table for single-use refresh tokens
|
| 2 |
+
|
| 3 |
+
Revision ID: 005
|
| 4 |
+
Revises: 004
|
| 5 |
+
Create Date: 2026-04-21
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Sequence, Union
|
| 10 |
+
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
from alembic import op
|
| 13 |
+
|
| 14 |
+
revision: str = "005"
|
| 15 |
+
down_revision: Union[str, None] = "004"
|
| 16 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 17 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def upgrade() -> None:
|
| 21 |
+
op.create_table(
|
| 22 |
+
"refresh_token_jtis",
|
| 23 |
+
sa.Column("jti", sa.Uuid(), primary_key=True),
|
| 24 |
+
sa.Column(
|
| 25 |
+
"user_id",
|
| 26 |
+
sa.Uuid(),
|
| 27 |
+
sa.ForeignKey("users.id", ondelete="CASCADE"),
|
| 28 |
+
nullable=False,
|
| 29 |
+
),
|
| 30 |
+
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
| 31 |
+
sa.Column("used_at", sa.DateTime(timezone=True), nullable=True),
|
| 32 |
+
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
| 33 |
+
)
|
| 34 |
+
op.create_index("ix_refresh_token_jtis_expires_at", "refresh_token_jtis", ["expires_at"])
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def downgrade() -> None:
|
| 38 |
+
op.drop_index("ix_refresh_token_jtis_expires_at", table_name="refresh_token_jtis")
|
| 39 |
+
op.drop_table("refresh_token_jtis")
|
server/alembic/versions/006_request_logs_brin.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Swap request_logs.created_at btree index for a BRIN index
|
| 2 |
+
|
| 3 |
+
Revision ID: 006
|
| 4 |
+
Revises: 005
|
| 5 |
+
Create Date: 2026-04-21
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Sequence, Union
|
| 10 |
+
|
| 11 |
+
from alembic import op
|
| 12 |
+
|
| 13 |
+
revision: str = "006"
|
| 14 |
+
down_revision: Union[str, None] = "005"
|
| 15 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 16 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def upgrade() -> None:
|
| 20 |
+
op.drop_index("ix_request_logs_created_at", table_name="request_logs")
|
| 21 |
+
op.execute("CREATE INDEX ix_request_logs_created_at ON request_logs USING BRIN (created_at)")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def downgrade() -> None:
|
| 25 |
+
op.drop_index("ix_request_logs_created_at", table_name="request_logs")
|
| 26 |
+
op.create_index("ix_request_logs_created_at", "request_logs", ["created_at"])
|
server/auth.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import secrets
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime, timedelta, timezone
|
| 5 |
+
|
| 6 |
+
from db import SessionLocal
|
| 7 |
+
from fastapi import Depends, HTTPException, Request
|
| 8 |
+
from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer
|
| 9 |
+
from jose import JWTError, jwt
|
| 10 |
+
from models import APIKey, RefreshTokenJti, User
|
| 11 |
+
from passlib.context import CryptContext
|
| 12 |
+
from sqlalchemy import select, update
|
| 13 |
+
from sqlalchemy.orm import Session
|
| 14 |
+
|
| 15 |
+
JWT_SECRET = os.environ.get("JWT_SECRET", "")
|
| 16 |
+
JWT_ALGORITHM = "HS256"
|
| 17 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
| 18 |
+
REFRESH_TOKEN_EXPIRE_DAYS = 30
|
| 19 |
+
ADMIN_API_KEY = os.environ.get("ADMIN_API_KEY", "")
|
| 20 |
+
AUTH_DISABLED = os.environ.get("AUTH_DISABLED", "").lower() in {"1", "true", "yes", "on"}
|
| 21 |
+
|
| 22 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def hash_password(password: str) -> str:
|
| 26 |
+
return pwd_context.hash(password)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def verify_password(plain: str, hashed: str) -> bool:
|
| 30 |
+
return pwd_context.verify(plain, hashed)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def dummy_verify_password() -> None:
|
| 34 |
+
"""Burn the same bcrypt cycles as a real verify so login timing doesn't leak whether an email exists."""
|
| 35 |
+
pwd_context.dummy_verify()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def generate_api_key() -> tuple[str, str, str]:
|
| 39 |
+
"""Returns (full_key, prefix, hash)."""
|
| 40 |
+
raw = secrets.token_urlsafe(32)
|
| 41 |
+
full_key = f"m0sk_{raw}"
|
| 42 |
+
prefix = full_key[:12]
|
| 43 |
+
key_hash = pwd_context.hash(full_key)
|
| 44 |
+
return full_key, prefix, key_hash
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def verify_api_key_hash(plain_key: str, hashed: str) -> bool:
|
| 48 |
+
return pwd_context.verify(plain_key, hashed)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _get_secret() -> str:
|
| 52 |
+
if not JWT_SECRET:
|
| 53 |
+
raise HTTPException(status_code=500, detail="JWT_SECRET is not configured.")
|
| 54 |
+
return JWT_SECRET
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def create_access_token(user_id: str, role: str) -> str:
|
| 58 |
+
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 59 |
+
payload = {"sub": user_id, "role": role, "exp": expire, "type": "access"}
|
| 60 |
+
return jwt.encode(payload, _get_secret(), algorithm=JWT_ALGORITHM)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def create_refresh_token(user_id: str, db: Session) -> str:
|
| 64 |
+
expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
|
| 65 |
+
jti = uuid.uuid4()
|
| 66 |
+
db.add(RefreshTokenJti(jti=jti, user_id=uuid.UUID(user_id), expires_at=expire))
|
| 67 |
+
db.commit()
|
| 68 |
+
payload = {"sub": user_id, "exp": expire, "jti": str(jti), "type": "refresh"}
|
| 69 |
+
return jwt.encode(payload, _get_secret(), algorithm=JWT_ALGORITHM)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def consume_refresh_jti(jti: str, db: Session) -> None:
|
| 73 |
+
"""Atomically mark a refresh token's jti as used. Raises 401 if missing, already used, or expired.
|
| 74 |
+
|
| 75 |
+
The conditional UPDATE closes the read-check-write race: concurrent replays of the same
|
| 76 |
+
token race on a single row, so at most one update affects a row and the rest see rowcount 0.
|
| 77 |
+
"""
|
| 78 |
+
try:
|
| 79 |
+
jti_uuid = uuid.UUID(jti)
|
| 80 |
+
except (TypeError, ValueError):
|
| 81 |
+
raise HTTPException(status_code=401, detail="Refresh token is no longer valid.")
|
| 82 |
+
now = datetime.now(timezone.utc)
|
| 83 |
+
result = db.execute(
|
| 84 |
+
update(RefreshTokenJti).where(
|
| 85 |
+
RefreshTokenJti.jti == jti_uuid,
|
| 86 |
+
RefreshTokenJti.used_at.is_(None),
|
| 87 |
+
RefreshTokenJti.expires_at > now,
|
| 88 |
+
).values(used_at=now)
|
| 89 |
+
)
|
| 90 |
+
if result.rowcount == 0:
|
| 91 |
+
raise HTTPException(status_code=401, detail="Refresh token is no longer valid.")
|
| 92 |
+
db.commit()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def decode_token(token: str) -> dict:
|
| 96 |
+
try:
|
| 97 |
+
return jwt.decode(token, _get_secret(), algorithms=[JWT_ALGORITHM])
|
| 98 |
+
except JWTError:
|
| 99 |
+
raise HTTPException(status_code=401, detail="Invalid or expired token.")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
bearer_scheme = HTTPBearer(auto_error=False)
|
| 103 |
+
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _mark_auth_type(request: Request, auth_type: str) -> None:
|
| 107 |
+
request.state.auth_type = auth_type
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _get_default_user(db: Session) -> User | None:
|
| 111 |
+
return db.scalar(select(User).order_by(User.created_at.asc()))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _resolve_user_from_jwt(token: str, db: Session) -> User:
|
| 115 |
+
payload = decode_token(token)
|
| 116 |
+
if payload.get("type") != "access":
|
| 117 |
+
raise HTTPException(status_code=401, detail="Invalid token type.")
|
| 118 |
+
user = db.get(User, payload.get("sub"))
|
| 119 |
+
if user is None:
|
| 120 |
+
raise HTTPException(status_code=401, detail="User not found.")
|
| 121 |
+
return user
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _resolve_user_from_api_key(key: str, db: Session) -> User:
|
| 125 |
+
prefix = key[:12] if len(key) >= 12 else key
|
| 126 |
+
candidates = (
|
| 127 |
+
db.execute(select(APIKey).where(APIKey.key_prefix == prefix, APIKey.revoked_at.is_(None))).scalars().all()
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
for candidate in candidates:
|
| 131 |
+
if verify_api_key_hash(key, candidate.key_hash):
|
| 132 |
+
candidate.last_used_at = datetime.now(timezone.utc)
|
| 133 |
+
db.commit()
|
| 134 |
+
user = db.get(User, candidate.created_by)
|
| 135 |
+
if user is None:
|
| 136 |
+
raise HTTPException(status_code=401, detail="API key owner not found.")
|
| 137 |
+
return user
|
| 138 |
+
|
| 139 |
+
raise HTTPException(status_code=401, detail="Invalid API key.")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
async def verify_auth(
|
| 143 |
+
request: Request,
|
| 144 |
+
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
| 145 |
+
x_api_key: str | None = Depends(api_key_header),
|
| 146 |
+
) -> User | None:
|
| 147 |
+
"""Authenticate via JWT, X-API-Key, or legacy ADMIN_API_KEY. Returns User or None.
|
| 148 |
+
|
| 149 |
+
A short-lived session is opened only on the branches that query the DB, so no
|
| 150 |
+
pooled connection is held for the lifetime of the (possibly long-running) request.
|
| 151 |
+
"""
|
| 152 |
+
if credentials is not None:
|
| 153 |
+
_mark_auth_type(request, "bearer")
|
| 154 |
+
with SessionLocal() as db:
|
| 155 |
+
return _resolve_user_from_jwt(credentials.credentials, db)
|
| 156 |
+
|
| 157 |
+
if x_api_key is not None:
|
| 158 |
+
if ADMIN_API_KEY and secrets.compare_digest(x_api_key, ADMIN_API_KEY):
|
| 159 |
+
_mark_auth_type(request, "admin_api_key")
|
| 160 |
+
return None
|
| 161 |
+
_mark_auth_type(request, "api_key")
|
| 162 |
+
with SessionLocal() as db:
|
| 163 |
+
return _resolve_user_from_api_key(x_api_key, db)
|
| 164 |
+
|
| 165 |
+
if AUTH_DISABLED:
|
| 166 |
+
_mark_auth_type(request, "disabled")
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
raise HTTPException(
|
| 170 |
+
status_code=401,
|
| 171 |
+
detail="Authentication required. Provide a Bearer token or X-API-Key header.",
|
| 172 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
async def require_auth(
|
| 177 |
+
request: Request,
|
| 178 |
+
user: User | None = Depends(verify_auth),
|
| 179 |
+
) -> User:
|
| 180 |
+
"""Like verify_auth but guarantees a non-None User. Use for endpoints that require auth."""
|
| 181 |
+
if user is None:
|
| 182 |
+
if getattr(request.state, "auth_type", "none") in {"admin_api_key", "disabled"}:
|
| 183 |
+
with SessionLocal() as db:
|
| 184 |
+
default_user = _get_default_user(db)
|
| 185 |
+
if default_user is not None:
|
| 186 |
+
return default_user
|
| 187 |
+
raise HTTPException(status_code=401, detail="Authentication required.")
|
| 188 |
+
raise HTTPException(status_code=401, detail="Authentication required.")
|
| 189 |
+
return user
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
_BOOTSTRAP_ADMIN = User(
|
| 193 |
+
id=uuid.UUID(int=0),
|
| 194 |
+
name="admin_api_key",
|
| 195 |
+
email="",
|
| 196 |
+
password_hash="",
|
| 197 |
+
role="admin",
|
| 198 |
+
created_at=datetime.min.replace(tzinfo=timezone.utc),
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
async def require_admin(
|
| 203 |
+
request: Request,
|
| 204 |
+
user: User | None = Depends(verify_auth),
|
| 205 |
+
) -> User:
|
| 206 |
+
"""Like require_auth but also enforces admin role.
|
| 207 |
+
|
| 208 |
+
ADMIN_API_KEY and AUTH_DISABLED callers are treated as admin even when
|
| 209 |
+
the users table is empty (fresh-deploy bootstrap).
|
| 210 |
+
"""
|
| 211 |
+
auth_type = getattr(request.state, "auth_type", "none")
|
| 212 |
+
if user is None:
|
| 213 |
+
if auth_type in {"admin_api_key", "disabled"}:
|
| 214 |
+
with SessionLocal() as db:
|
| 215 |
+
default_user = _get_default_user(db)
|
| 216 |
+
if default_user is not None:
|
| 217 |
+
if default_user.role != "admin":
|
| 218 |
+
raise HTTPException(status_code=403, detail="Admin role required.")
|
| 219 |
+
return default_user
|
| 220 |
+
return _BOOTSTRAP_ADMIN
|
| 221 |
+
raise HTTPException(status_code=401, detail="Authentication required.")
|
| 222 |
+
if user.role != "admin":
|
| 223 |
+
raise HTTPException(status_code=403, detail="Admin role required.")
|
| 224 |
+
return user
|
server/dashboard/.env.example
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NEXT_PUBLIC_API_URL=http://localhost:7860/api
|
| 2 |
+
NEXT_PUBLIC_INSTANCE_NAME=Mem0
|
server/dashboard/components.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$schema": "https://ui.shadcn.com/schema.json",
|
| 3 |
+
"style": "new-york",
|
| 4 |
+
"rsc": true,
|
| 5 |
+
"tsx": true,
|
| 6 |
+
"tailwind": {
|
| 7 |
+
"config": "tailwind.config.ts",
|
| 8 |
+
"css": "src/styles/globals.css",
|
| 9 |
+
"baseColor": "zinc",
|
| 10 |
+
"cssVariables": true,
|
| 11 |
+
"prefix": ""
|
| 12 |
+
},
|
| 13 |
+
"aliases": {
|
| 14 |
+
"components": "@/components",
|
| 15 |
+
"utils": "@/lib/utils"
|
| 16 |
+
}
|
| 17 |
+
}
|
server/dashboard/entrypoint.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
cd /app
|
| 5 |
+
|
| 6 |
+
# Swap NEXT_PUBLIC_* placeholders baked into .next/ at build time with the
|
| 7 |
+
# container's real env values. Each placeholder must be declared in the
|
| 8 |
+
# Dockerfile as `ENV NAME=NAME` so Next.js inlines the literal name. Currently:
|
| 9 |
+
# NEXT_PUBLIC_API_URL, NEXT_PUBLIC_INSTANCE_NAME
|
| 10 |
+
# New NEXT_PUBLIC_* vars must be added to the Dockerfile or this loop won't substitute them.
|
| 11 |
+
printenv | grep '^NEXT_PUBLIC_' | while IFS='=' read -r key value; do
|
| 12 |
+
escaped=$(printf '%s' "$value" | sed -e 's/[\\&|]/\\&/g')
|
| 13 |
+
find .next/ -type f -exec sed -i "s|$key|$escaped|g" {} \;
|
| 14 |
+
done
|
| 15 |
+
echo "Done replacing env variables NEXT_PUBLIC_ with real values"
|
| 16 |
+
|
| 17 |
+
exec "$@"
|
server/dashboard/next.config.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/** @type {import('next').NextConfig} */
|
| 2 |
+
const nextConfig = {
|
| 3 |
+
output: "standalone",
|
| 4 |
+
eslint: {
|
| 5 |
+
ignoreDuringBuilds: false,
|
| 6 |
+
},
|
| 7 |
+
typescript: {
|
| 8 |
+
ignoreBuildErrors: false,
|
| 9 |
+
},
|
| 10 |
+
experimental: {
|
| 11 |
+
optimizePackageImports: ["@/components", "@/lib", "@/utils"],
|
| 12 |
+
},
|
| 13 |
+
compress: true,
|
| 14 |
+
images: {
|
| 15 |
+
formats: ["image/webp", "image/avif"],
|
| 16 |
+
},
|
| 17 |
+
async headers() {
|
| 18 |
+
return [
|
| 19 |
+
{
|
| 20 |
+
source: "/(.*)",
|
| 21 |
+
headers: [
|
| 22 |
+
{ key: "X-Frame-Options", value: "DENY" },
|
| 23 |
+
{ key: "Content-Security-Policy", value: "frame-ancestors 'none'" },
|
| 24 |
+
{ key: "X-Content-Type-Options", value: "nosniff" },
|
| 25 |
+
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
| 26 |
+
],
|
| 27 |
+
},
|
| 28 |
+
];
|
| 29 |
+
},
|
| 30 |
+
redirects: async () => {
|
| 31 |
+
return [
|
| 32 |
+
{
|
| 33 |
+
source: "/",
|
| 34 |
+
destination: "/dashboard",
|
| 35 |
+
permanent: false,
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
source: "/settings",
|
| 39 |
+
destination: "/dashboard/settings",
|
| 40 |
+
permanent: false,
|
| 41 |
+
},
|
| 42 |
+
];
|
| 43 |
+
},
|
| 44 |
+
};
|
| 45 |
+
|
| 46 |
+
export default nextConfig;
|
server/dashboard/package.json
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "mem0-dashboard",
|
| 3 |
+
"version": "0.1.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"packageManager": "pnpm@10.34.2",
|
| 6 |
+
"scripts": {
|
| 7 |
+
"dev": "next dev",
|
| 8 |
+
"build": "next build",
|
| 9 |
+
"start": "next start",
|
| 10 |
+
"lint": "prettier --check .",
|
| 11 |
+
"format": "prettier --write .",
|
| 12 |
+
"typecheck": "tsc --noEmit"
|
| 13 |
+
},
|
| 14 |
+
"dependencies": {
|
| 15 |
+
"@hookform/resolvers": "^3.6.0",
|
| 16 |
+
"@radix-ui/react-accordion": "^1.2.0",
|
| 17 |
+
"@radix-ui/react-alert-dialog": "^1.1.4",
|
| 18 |
+
"@radix-ui/react-avatar": "^1.0.4",
|
| 19 |
+
"@radix-ui/react-checkbox": "^1.0.4",
|
| 20 |
+
"@radix-ui/react-collapsible": "^1.1.3",
|
| 21 |
+
"@radix-ui/react-dialog": "^1.1.1",
|
| 22 |
+
"@radix-ui/react-dropdown-menu": "^2.0.6",
|
| 23 |
+
"@radix-ui/react-hover-card": "^1.1.1",
|
| 24 |
+
"@radix-ui/react-icons": "^1.3.0",
|
| 25 |
+
"@radix-ui/react-label": "^2.1.0",
|
| 26 |
+
"@radix-ui/react-popover": "^1.0.7",
|
| 27 |
+
"@radix-ui/react-progress": "^1.1.0",
|
| 28 |
+
"@radix-ui/react-radio-group": "^1.2.0",
|
| 29 |
+
"@radix-ui/react-scroll-area": "^1.0.5",
|
| 30 |
+
"@radix-ui/react-select": "^2.1.1",
|
| 31 |
+
"@radix-ui/react-separator": "^1.1.0",
|
| 32 |
+
"@radix-ui/react-slider": "^1.2.2",
|
| 33 |
+
"@radix-ui/react-slot": "^1.2.3",
|
| 34 |
+
"@radix-ui/react-switch": "^1.1.2",
|
| 35 |
+
"@radix-ui/react-tabs": "^1.1.0",
|
| 36 |
+
"@radix-ui/react-toast": "^1.2.1",
|
| 37 |
+
"@radix-ui/react-tooltip": "^1.0.7",
|
| 38 |
+
"@reduxjs/toolkit": "^2.3.0",
|
| 39 |
+
"@tanstack/react-table": "^8.17.3",
|
| 40 |
+
"axios": "^1.18.0",
|
| 41 |
+
"class-variance-authority": "^0.7.1",
|
| 42 |
+
"clsx": "^2.1.0",
|
| 43 |
+
"cmdk": "^1.0.0",
|
| 44 |
+
"date-fns": "^4.1.0",
|
| 45 |
+
"framer-motion": "^12.23.12",
|
| 46 |
+
"lodash": "^4.18.1",
|
| 47 |
+
"lucide-react": "^0.542.0",
|
| 48 |
+
"next": "15.5.21",
|
| 49 |
+
"next-themes": "^0.4.4",
|
| 50 |
+
"react": "^19.0.0",
|
| 51 |
+
"react-copy-to-clipboard": "^5.1.0",
|
| 52 |
+
"react-day-picker": "8.10.1",
|
| 53 |
+
"react-dom": "^19.0.0",
|
| 54 |
+
"react-hook-form": "^7.52.0",
|
| 55 |
+
"react-redux": "^9.1.2",
|
| 56 |
+
"react-syntax-highlighter": "^15.5.0",
|
| 57 |
+
"recharts": "^2.15.0",
|
| 58 |
+
"redux": "^5.0.1",
|
| 59 |
+
"sonner": "^1.4.41",
|
| 60 |
+
"tailwind-merge": "^2.2.0",
|
| 61 |
+
"tailwindcss-animate": "^1.0.7",
|
| 62 |
+
"use-debounce": "^10.0.4",
|
| 63 |
+
"uuid": "^11.1.1",
|
| 64 |
+
"vaul": "^0.9.1",
|
| 65 |
+
"zod": "^3.23.8"
|
| 66 |
+
},
|
| 67 |
+
"devDependencies": {
|
| 68 |
+
"@tailwindcss/typography": "^0.5.13",
|
| 69 |
+
"@types/lodash": "^4.17.7",
|
| 70 |
+
"@types/node": "22.5.4",
|
| 71 |
+
"@types/react": "^19.0.0",
|
| 72 |
+
"@types/react-dom": "^19.0.0",
|
| 73 |
+
"@types/react-copy-to-clipboard": "^5.0.7",
|
| 74 |
+
"@types/react-syntax-highlighter": "^15.5.13",
|
| 75 |
+
"@types/uuid": "^9.0.8",
|
| 76 |
+
"autoprefixer": "^10.0.1",
|
| 77 |
+
"eslint": "^8",
|
| 78 |
+
"eslint-config-next": "15.5.18",
|
| 79 |
+
"postcss": "^8",
|
| 80 |
+
"prettier": "^3.5.2",
|
| 81 |
+
"tailwindcss": "^3.3.0",
|
| 82 |
+
"typescript": "^5.6.3"
|
| 83 |
+
}
|
| 84 |
+
}
|
server/dashboard/postcss.config.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module.exports = {
|
| 2 |
+
plugins: {
|
| 3 |
+
tailwindcss: {},
|
| 4 |
+
autoprefixer: {},
|
| 5 |
+
},
|
| 6 |
+
};
|
server/dashboard/src/README.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mem0 Dashboard Source
|
| 2 |
+
# This directory should contain the mem0 dashboard source code
|
| 3 |
+
# Copy from https://github.com/mem0ai/mem0/tree/main/server/dashboard/src
|
| 4 |
+
|
| 5 |
+
# Required structure:
|
| 6 |
+
# src/
|
| 7 |
+
# app/ - Next.js App Router pages
|
| 8 |
+
# components/ - React components (shadcn/ui based)
|
| 9 |
+
# constants/ - Application constants
|
| 10 |
+
# hooks/ - Custom React hooks
|
| 11 |
+
# lib/ - Utility libraries
|
| 12 |
+
# store/ - Redux store
|
| 13 |
+
# styles/ - Global styles (globals.css)
|
| 14 |
+
# types/ - TypeScript types
|
| 15 |
+
# utils/ - Utility functions
|
| 16 |
+
# middleware.ts - Next.js middleware for auth
|
| 17 |
+
|
| 18 |
+
# For now, this is a placeholder. The actual dashboard code should be copied from
|
| 19 |
+
# the mem0 repository: https://github.com/mem0ai/mem0/tree/main/server/dashboard/src
|
| 20 |
+
|
| 21 |
+
# To set up:
|
| 22 |
+
# 1. git clone https://github.com/mem0ai/mem0.git /tmp/mem0
|
| 23 |
+
# 2. cp -r /tmp/mem0/server/dashboard/src ./src
|
| 24 |
+
# 3. cp /tmp/mem0/server/dashboard/public ./public
|
server/dashboard/tailwind.config.ts
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Config } from "tailwindcss";
|
| 2 |
+
|
| 3 |
+
const config = {
|
| 4 |
+
darkMode: ["class"],
|
| 5 |
+
content: [
|
| 6 |
+
"./pages/**/*.{ts,tsx}",
|
| 7 |
+
"./components/**/*.{ts,tsx}",
|
| 8 |
+
"./app/**/*.{ts,tsx}",
|
| 9 |
+
"./src/**/*.{ts,tsx}",
|
| 10 |
+
],
|
| 11 |
+
future: {
|
| 12 |
+
hoverOnlyWhenSupported: true,
|
| 13 |
+
},
|
| 14 |
+
experimental: {
|
| 15 |
+
optimizeUniversalDefaults: true,
|
| 16 |
+
},
|
| 17 |
+
prefix: "",
|
| 18 |
+
theme: {
|
| 19 |
+
container: {
|
| 20 |
+
center: true,
|
| 21 |
+
padding: "2rem",
|
| 22 |
+
screens: {
|
| 23 |
+
"2xl": "1400px",
|
| 24 |
+
},
|
| 25 |
+
},
|
| 26 |
+
extend: {
|
| 27 |
+
spacing: {
|
| 28 |
+
"2.5": "0.625rem",
|
| 29 |
+
},
|
| 30 |
+
fontFamily: {
|
| 31 |
+
sans: ["Inter", "system-ui"],
|
| 32 |
+
serif: ["ui-serif", "Georgia"],
|
| 33 |
+
mono: ["Monaco", "Consolas", '"Courier New"', "monospace"],
|
| 34 |
+
"inter-display": ["var(--font-inter)", "sans-serif"],
|
| 35 |
+
inter: ["var(--font-inter)", "sans-serif"],
|
| 36 |
+
roboto: ["var(--font-roboto-mono)", "sans-serif"],
|
| 37 |
+
fustat: ["var(--font-fustat, ui-sans-serif)", "sans-serif"],
|
| 38 |
+
"dm-mono": ["var(--font-dm-mono, ui-monospace)", "monospace"],
|
| 39 |
+
},
|
| 40 |
+
colors: {
|
| 41 |
+
onSurface: {
|
| 42 |
+
primary: "hsla(var(--onSurface-primary))",
|
| 43 |
+
tertiary: "hsla(var(--onSurface-tertiary))",
|
| 44 |
+
secondary: "hsla(var(--onSurface-secondary))",
|
| 45 |
+
default: {
|
| 46 |
+
primary: "var(--on-surface-default-primary)",
|
| 47 |
+
secondary: "var(--on-surface-default-secondary)",
|
| 48 |
+
tertiary: "var(--on-surface-default-tertiary)",
|
| 49 |
+
brand: "var(--on-surface-default-brand)",
|
| 50 |
+
"brand-hover": "var(--on-surface-default-brand-hover)",
|
| 51 |
+
},
|
| 52 |
+
event: {
|
| 53 |
+
add: "var(--on-surface-event-add)",
|
| 54 |
+
search: "var(--on-surface-event-search)",
|
| 55 |
+
delete: "var(--on-surface-event-delete)",
|
| 56 |
+
get: "var(--on-surface-event-get)",
|
| 57 |
+
},
|
| 58 |
+
positive: {
|
| 59 |
+
primary: "var(--on-surface-positive-primary)",
|
| 60 |
+
secondary: "var(--on-surface-positive-secondary)",
|
| 61 |
+
},
|
| 62 |
+
danger: {
|
| 63 |
+
primary: "var(--on-surface-danger-primary)",
|
| 64 |
+
secondary: "var(--on-surface-danger-secondary)",
|
| 65 |
+
},
|
| 66 |
+
info: {
|
| 67 |
+
primary: "var(--on-surface-info-primary)",
|
| 68 |
+
secondary: "var(--on-surface-info-secondary)",
|
| 69 |
+
},
|
| 70 |
+
},
|
| 71 |
+
surface: {
|
| 72 |
+
primary: "hsla(var(--surface-primary))",
|
| 73 |
+
secondary: "hsla(var(--surface-secondary))",
|
| 74 |
+
tertiary: "hsla(var(--surface-tertiary))",
|
| 75 |
+
default: {
|
| 76 |
+
primary: "var(--surface-default-primary)",
|
| 77 |
+
"primary-hover": "var(--surface-default-primary-hover)",
|
| 78 |
+
secondary: "var(--surface-default-secondary)",
|
| 79 |
+
"secondary-hover": "var(--surface-default-secondary-hover)",
|
| 80 |
+
"fg-primary": "var(--surface-default-fg-primary)",
|
| 81 |
+
"fg-primary-hover": "var(--surface-default-fg-primary-hover)",
|
| 82 |
+
"fg-secondary": "var(--surface-default-fg-secondary)",
|
| 83 |
+
"fg-secondary-hover": "var(--surface-default-fg-secondary-hover)",
|
| 84 |
+
tertiary: "var(--surface-default-tertiary)",
|
| 85 |
+
"tertiary-hover": "var(--surface-default-tertiary-hover)",
|
| 86 |
+
brand: "var(--surface-default-brand)",
|
| 87 |
+
"brand-hover": "var(--surface-default-brand-hover)",
|
| 88 |
+
},
|
| 89 |
+
event: {
|
| 90 |
+
add: "var(--surface-event-add)",
|
| 91 |
+
search: "var(--surface-event-search)",
|
| 92 |
+
delete: "var(--surface-event-delete)",
|
| 93 |
+
get: "var(--surface-event-get)",
|
| 94 |
+
},
|
| 95 |
+
positive: {
|
| 96 |
+
primary: "var(--surface-positive-primary)",
|
| 97 |
+
"primary-hover": "var(--surface-positive-primary-hover)",
|
| 98 |
+
},
|
| 99 |
+
danger: {
|
| 100 |
+
primary: "var(--surface-danger-primary)",
|
| 101 |
+
"primary-hover": "var(--surface-danger-primary-hover)",
|
| 102 |
+
},
|
| 103 |
+
info: {
|
| 104 |
+
primary: "var(--surface-info-primary)",
|
| 105 |
+
"primary-hover": "var(--surface-info-primary-hover)",
|
| 106 |
+
},
|
| 107 |
+
},
|
| 108 |
+
elevationLight: {
|
| 109 |
+
"2": "hsla(var(--elevation-light-2))",
|
| 110 |
+
},
|
| 111 |
+
neutral: {
|
| 112 |
+
"0": "hsl(var(--neutral-0))",
|
| 113 |
+
"50": "hsl(var(--neutral-50))",
|
| 114 |
+
"100": "hsl(var(--neutral-100))",
|
| 115 |
+
"200": "hsl(var(--neutral-200))",
|
| 116 |
+
"300": "hsl(var(--neutral-300))",
|
| 117 |
+
"400": "hsl(var(--neutral-400))",
|
| 118 |
+
"500": "hsl(var(--neutral-500))",
|
| 119 |
+
"600": "hsl(var(--neutral-600))",
|
| 120 |
+
"700": "hsl(var(--neutral-700))",
|
| 121 |
+
"800": "hsl(var(--neutral-800))",
|
| 122 |
+
"900": "hsl(var(--neutral-900))",
|
| 123 |
+
"950": "hsl(var(--neutral-950))",
|
| 124 |
+
},
|
| 125 |
+
border: "hsl(var(--border))",
|
| 126 |
+
input: "hsl(var(--input))",
|
| 127 |
+
ring: "hsl(var(--ring))",
|
| 128 |
+
background: "hsl(var(--background))",
|
| 129 |
+
foreground: "hsl(var(--foreground))",
|
| 130 |
+
primary: {
|
| 131 |
+
DEFAULT: "hsl(var(--primary))",
|
| 132 |
+
foreground: "hsl(var(--primary-foreground))",
|
| 133 |
+
border: "var(--border-primary)",
|
| 134 |
+
borderLight: "rgba(39, 39, 42, 1)",
|
| 135 |
+
},
|
| 136 |
+
secondary: {
|
| 137 |
+
DEFAULT: "hsl(var(--secondary))",
|
| 138 |
+
foreground: "hsl(var(--secondary-foreground))",
|
| 139 |
+
},
|
| 140 |
+
memoindigo: {
|
| 141 |
+
DEFAULT: "hsla(244, 96%, 90%, 1)",
|
| 142 |
+
strong: "hsl(244deg 54.62% 77.69%)",
|
| 143 |
+
light: "hsla(244, 96%, 90%, 0.2)",
|
| 144 |
+
medium: "hsla(244, 96%, 90%, 0.5)",
|
| 145 |
+
foreground: "hsl(243.14deg 71.07% 52.55%)",
|
| 146 |
+
},
|
| 147 |
+
memoblue: {
|
| 148 |
+
DEFAULT: "hsla(191, 100%, 88%, 1)",
|
| 149 |
+
strong: "hsl(191.72deg 100% 82.94%)",
|
| 150 |
+
light: "hsla(191, 100%, 88%, 0.3)",
|
| 151 |
+
medium: "hsla(191, 100%, 88%, 0.5)",
|
| 152 |
+
foreground: "hsl(191.61deg 100% 27.42%)",
|
| 153 |
+
},
|
| 154 |
+
memogreen: {
|
| 155 |
+
DEFAULT: "hsla(76, 100%, 82%, 1)",
|
| 156 |
+
strong: "hsl(76.48deg 79.17% 71.1%)",
|
| 157 |
+
light: "hsla(76, 100%, 82%, 0.3)",
|
| 158 |
+
medium: "hsla(76, 100%, 82%, 0.5)",
|
| 159 |
+
foreground: "hsl(76deg 100% 20.59%)",
|
| 160 |
+
},
|
| 161 |
+
destructive: {
|
| 162 |
+
DEFAULT: "hsl(var(--destructive))",
|
| 163 |
+
foreground: "hsl(var(--destructive-foreground))",
|
| 164 |
+
},
|
| 165 |
+
muted: {
|
| 166 |
+
DEFAULT: "hsl(var(--muted))",
|
| 167 |
+
foreground: "hsl(var(--muted-foreground))",
|
| 168 |
+
},
|
| 169 |
+
accent: {
|
| 170 |
+
DEFAULT: "hsl(var(--accent))",
|
| 171 |
+
foreground: "hsl(var(--accent-foreground))",
|
| 172 |
+
},
|
| 173 |
+
popover: {
|
| 174 |
+
DEFAULT: "hsl(var(--popover))",
|
| 175 |
+
foreground: "hsl(var(--popover-foreground))",
|
| 176 |
+
},
|
| 177 |
+
card: {
|
| 178 |
+
DEFAULT: "hsl(var(--card))",
|
| 179 |
+
foreground: "hsl(var(--card-foreground))",
|
| 180 |
+
},
|
| 181 |
+
sidebar: {
|
| 182 |
+
DEFAULT: "hsl(var(--sidebar-background))",
|
| 183 |
+
foreground: "hsl(var(--sidebar-foreground))",
|
| 184 |
+
primary: "hsl(var(--sidebar-primary))",
|
| 185 |
+
"primary-foreground": "hsl(var(--sidebar-primary-foreground))",
|
| 186 |
+
accent: "hsl(var(--sidebar-accent))",
|
| 187 |
+
"accent-foreground": "hsl(var(--sidebar-accent-foreground))",
|
| 188 |
+
border: "hsl(var(--sidebar-border))",
|
| 189 |
+
ring: "hsl(var(--sidebar-ring))",
|
| 190 |
+
},
|
| 191 |
+
memNeutral: {
|
| 192 |
+
50: "var(--mem-neutral-50)",
|
| 193 |
+
100: "var(--mem-neutral-100)",
|
| 194 |
+
150: "var(--mem-neutral-150)",
|
| 195 |
+
200: "var(--mem-neutral-200)",
|
| 196 |
+
300: "var(--mem-neutral-300)",
|
| 197 |
+
400: "var(--mem-neutral-400)",
|
| 198 |
+
450: "var(--mem-neutral-450)",
|
| 199 |
+
500: "var(--mem-neutral-500)",
|
| 200 |
+
550: "var(--mem-neutral-550)",
|
| 201 |
+
600: "var(--mem-neutral-600)",
|
| 202 |
+
700: "var(--mem-neutral-700)",
|
| 203 |
+
800: "var(--mem-neutral-800)",
|
| 204 |
+
850: "var(--mem-neutral-850)",
|
| 205 |
+
900: "var(--mem-neutral-900)",
|
| 206 |
+
950: "var(--mem-neutral-950)",
|
| 207 |
+
},
|
| 208 |
+
memPurple: {
|
| 209 |
+
50: "var(--mem-purple-50)",
|
| 210 |
+
100: "var(--mem-purple-100)",
|
| 211 |
+
150: "var(--mem-purple-150)",
|
| 212 |
+
200: "var(--mem-purple-200)",
|
| 213 |
+
300: "var(--mem-purple-300)",
|
| 214 |
+
400: "var(--mem-purple-400)",
|
| 215 |
+
500: "var(--mem-purple-500)",
|
| 216 |
+
600: "var(--mem-purple-600)",
|
| 217 |
+
700: "var(--mem-purple-700)",
|
| 218 |
+
800: "var(--mem-purple-800)",
|
| 219 |
+
900: "var(--mem-purple-900)",
|
| 220 |
+
950: "var(--mem-purple-950)",
|
| 221 |
+
},
|
| 222 |
+
memGold: {
|
| 223 |
+
50: "var(--mem-gold-50)",
|
| 224 |
+
100: "var(--mem-gold-100)",
|
| 225 |
+
150: "var(--mem-gold-150)",
|
| 226 |
+
200: "var(--mem-gold-200)",
|
| 227 |
+
300: "var(--mem-gold-300)",
|
| 228 |
+
400: "var(--mem-gold-400)",
|
| 229 |
+
500: "var(--mem-gold-500)",
|
| 230 |
+
600: "var(--mem-gold-600)",
|
| 231 |
+
700: "var(--mem-gold-700)",
|
| 232 |
+
800: "var(--mem-gold-800)",
|
| 233 |
+
900: "var(--mem-gold-900)",
|
| 234 |
+
950: "var(--mem-gold-950)",
|
| 235 |
+
},
|
| 236 |
+
memBlue: {
|
| 237 |
+
50: "var(--mem-blue-50)",
|
| 238 |
+
100: "var(--mem-blue-100)",
|
| 239 |
+
200: "var(--mem-blue-200)",
|
| 240 |
+
300: "var(--mem-blue-300)",
|
| 241 |
+
400: "var(--mem-blue-400)",
|
| 242 |
+
500: "var(--mem-blue-500)",
|
| 243 |
+
600: "var(--mem-blue-600)",
|
| 244 |
+
700: "var(--mem-blue-700)",
|
| 245 |
+
800: "var(--mem-blue-800)",
|
| 246 |
+
900: "var(--mem-blue-900)",
|
| 247 |
+
950: "var(--mem-blue-950)",
|
| 248 |
+
},
|
| 249 |
+
memGreen: {
|
| 250 |
+
50: "var(--mem-green-50)",
|
| 251 |
+
100: "var(--mem-green-100)",
|
| 252 |
+
200: "var(--mem-green-200)",
|
| 253 |
+
300: "var(--mem-green-300)",
|
| 254 |
+
400: "var(--mem-green-400)",
|
| 255 |
+
500: "var(--mem-green-500)",
|
| 256 |
+
600: "var(--mem-green-600)",
|
| 257 |
+
700: "var(--mem-green-700)",
|
| 258 |
+
800: "var(--mem-green-800)",
|
| 259 |
+
900: "var(--mem-green-900)",
|
| 260 |
+
950: "var(--mem-green-950)",
|
| 261 |
+
},
|
| 262 |
+
memRed: {
|
| 263 |
+
50: "var(--mem-red-50)",
|
| 264 |
+
100: "var(--mem-red-100)",
|
| 265 |
+
200: "var(--mem-red-200)",
|
| 266 |
+
300: "var(--mem-red-300)",
|
| 267 |
+
400: "var(--mem-red-400)",
|
| 268 |
+
500: "var(--mem-red-500)",
|
| 269 |
+
600: "var(--mem-red-600)",
|
| 270 |
+
700: "var(--mem-red-700)",
|
| 271 |
+
800: "var(--mem-red-800)",
|
| 272 |
+
900: "var(--mem-red-900)",
|
| 273 |
+
950: "var(--mem-red-950)",
|
| 274 |
+
},
|
| 275 |
+
memBorder: {
|
| 276 |
+
primary: "var(--mem-border-primary)",
|
| 277 |
+
secondary: "var(--mem-border-secondary)",
|
| 278 |
+
},
|
| 279 |
+
},
|
| 280 |
+
borderRadius: {
|
| 281 |
+
lg: "var(--radius)",
|
| 282 |
+
md: "calc(var(--radius) - 2px)",
|
| 283 |
+
sm: "calc(var(--radius) - 4px)",
|
| 284 |
+
},
|
| 285 |
+
boxShadow: {
|
| 286 |
+
custom: "0px 3px 10px 0px rgba(0, 0, 0, 0.08)",
|
| 287 |
+
},
|
| 288 |
+
keyframes: {
|
| 289 |
+
"accordion-down": {
|
| 290 |
+
from: { height: "0" },
|
| 291 |
+
to: { height: "var(--radix-accordion-content-height)" },
|
| 292 |
+
},
|
| 293 |
+
"accordion-up": {
|
| 294 |
+
from: { height: "var(--radix-accordion-content-height)" },
|
| 295 |
+
to: { height: "0" },
|
| 296 |
+
},
|
| 297 |
+
"fade-in": {
|
| 298 |
+
"0%": { opacity: "0" },
|
| 299 |
+
"100%": { opacity: "1" },
|
| 300 |
+
},
|
| 301 |
+
"fade-in-right": {
|
| 302 |
+
"0%": { opacity: "0", transform: "translateX(-5%)" },
|
| 303 |
+
"100%": { opacity: "1", transform: "translateX(0)" },
|
| 304 |
+
},
|
| 305 |
+
shimmer: {
|
| 306 |
+
"0%": { transform: "translateX(-100%)" },
|
| 307 |
+
"100%": { transform: "translateX(100%)" },
|
| 308 |
+
},
|
| 309 |
+
"shimmer-subtle": {
|
| 310 |
+
"0%": { backgroundPosition: "-100% 0" },
|
| 311 |
+
"100%": { backgroundPosition: "100% 0" },
|
| 312 |
+
},
|
| 313 |
+
},
|
| 314 |
+
animation: {
|
| 315 |
+
"accordion-down": "accordion-down 0.2s ease-out",
|
| 316 |
+
"accordion-up": "accordion-up 0.2s ease-out",
|
| 317 |
+
"fade-in": "fade-in 0.3s ease-in-out",
|
| 318 |
+
"fade-in-right": "fade-in-right 0.5s ease-out",
|
| 319 |
+
shimmer: "shimmer 2s ease-in-out infinite",
|
| 320 |
+
"shimmer-subtle": "shimmer-subtle 1.5s linear infinite",
|
| 321 |
+
},
|
| 322 |
+
},
|
| 323 |
+
},
|
| 324 |
+
plugins: [require("tailwindcss-animate"), require("@tailwindcss/typography")],
|
| 325 |
+
} satisfies Config;
|
| 326 |
+
|
| 327 |
+
export default config;
|
server/dashboard/tsconfig.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"compilerOptions": {
|
| 3 |
+
"lib": ["dom", "dom.iterable", "esnext"],
|
| 4 |
+
"allowJs": true,
|
| 5 |
+
"skipLibCheck": true,
|
| 6 |
+
"strict": true,
|
| 7 |
+
"noEmit": true,
|
| 8 |
+
"esModuleInterop": true,
|
| 9 |
+
"module": "esnext",
|
| 10 |
+
"moduleResolution": "bundler",
|
| 11 |
+
"resolveJsonModule": true,
|
| 12 |
+
"isolatedModules": true,
|
| 13 |
+
"jsx": "preserve",
|
| 14 |
+
"incremental": true,
|
| 15 |
+
"baseUrl": ".",
|
| 16 |
+
"plugins": [{ "name": "next" }],
|
| 17 |
+
"paths": {
|
| 18 |
+
"@/*": ["./src/*"]
|
| 19 |
+
},
|
| 20 |
+
"target": "ES2017"
|
| 21 |
+
},
|
| 22 |
+
"include": [
|
| 23 |
+
"next-env.d.ts",
|
| 24 |
+
"**/*.ts",
|
| 25 |
+
"**/*.tsx",
|
| 26 |
+
".next/types/**/*.ts",
|
| 27 |
+
"src/types"
|
| 28 |
+
],
|
| 29 |
+
"exclude": ["node_modules"]
|
| 30 |
+
}
|
server/db.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from sqlalchemy import create_engine
|
| 4 |
+
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _build_database_url() -> str:
|
| 8 |
+
host = os.environ.get("POSTGRES_HOST", "localhost")
|
| 9 |
+
port = os.environ.get("POSTGRES_PORT", "5432")
|
| 10 |
+
user = os.environ.get("POSTGRES_USER", "mem0")
|
| 11 |
+
password = os.environ.get("POSTGRES_PASSWORD", "postgres")
|
| 12 |
+
db = os.environ.get("APP_DB_NAME", "mem0_app")
|
| 13 |
+
return f"postgresql+psycopg://{user}:{password}@{host}:{port}/{db}"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
engine = create_engine(_build_database_url(), pool_pre_ping=True)
|
| 17 |
+
|
| 18 |
+
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Base(DeclarativeBase):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_db():
|
| 26 |
+
"""FastAPI dependency that yields a SQLAlchemy session."""
|
| 27 |
+
db: Session = SessionLocal()
|
| 28 |
+
try:
|
| 29 |
+
yield db
|
| 30 |
+
finally:
|
| 31 |
+
db.close()
|
server/errors.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import sys
|
| 3 |
+
import uuid
|
| 4 |
+
from contextvars import ContextVar
|
| 5 |
+
|
| 6 |
+
from fastapi import HTTPException, Request
|
| 7 |
+
from fastapi.responses import JSONResponse
|
| 8 |
+
|
| 9 |
+
request_id_var: ContextVar[str] = ContextVar("request_id", default="-")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class UpstreamError(HTTPException):
|
| 13 |
+
def __init__(self, code: str, detail: str, request_id: str) -> None:
|
| 14 |
+
super().__init__(status_code=502, detail=detail)
|
| 15 |
+
self.code = code
|
| 16 |
+
self.request_id = request_id
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_AUTH_NAMES = {"AuthenticationError", "PermissionDeniedError"}
|
| 20 |
+
_RATE_NAMES = {"RateLimitError"}
|
| 21 |
+
_TIMEOUT_NAMES = {"APITimeoutError"}
|
| 22 |
+
_CONN_NAMES = {"APIConnectionError", "ConnectionError"}
|
| 23 |
+
_BAD_REQUEST_NAMES = {"BadRequestError", "UnprocessableEntityError"}
|
| 24 |
+
_DB_NAMES = {"OperationalError", "DBAPIError", "DisconnectionError"}
|
| 25 |
+
_VECTOR_NAMES = {"UnexpectedResponse", "ResponseHandlingException"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _classify_one(exc: BaseException) -> tuple[str, str]:
|
| 29 |
+
name = type(exc).__name__
|
| 30 |
+
module = getattr(type(exc), "__module__", "") or ""
|
| 31 |
+
status = getattr(exc, "status_code", None)
|
| 32 |
+
|
| 33 |
+
if name in _AUTH_NAMES or status in (401, 403):
|
| 34 |
+
return (
|
| 35 |
+
"provider_auth_failed",
|
| 36 |
+
"Provider rejected the request (authentication). Check your LLM provider API key on the Configuration page.",
|
| 37 |
+
)
|
| 38 |
+
if name in _RATE_NAMES or status == 429:
|
| 39 |
+
return ("provider_rate_limited", "Provider rate limit hit. Retry shortly.")
|
| 40 |
+
if name in _TIMEOUT_NAMES or isinstance(exc, TimeoutError):
|
| 41 |
+
return ("provider_timeout", "Provider timed out. Retry shortly.")
|
| 42 |
+
if name in _CONN_NAMES or (isinstance(status, int) and status >= 500):
|
| 43 |
+
return ("provider_unavailable", "Provider is unreachable or returned a server error.")
|
| 44 |
+
if name in _BAD_REQUEST_NAMES or status in (400, 422):
|
| 45 |
+
return ("provider_bad_request", "Provider rejected the request as malformed.")
|
| 46 |
+
if name in _DB_NAMES:
|
| 47 |
+
return ("datastore_unavailable", "The memory database is unreachable.")
|
| 48 |
+
if name in _VECTOR_NAMES or module.startswith("qdrant_client"):
|
| 49 |
+
return ("vector_store_unavailable", "The vector store is unreachable or returned an error.")
|
| 50 |
+
return ("unknown", "Upstream provider error.")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _classify(exc: BaseException | None) -> tuple[str, str]:
|
| 54 |
+
# Walk the cause/context chain so wrapped provider errors still classify correctly.
|
| 55 |
+
seen: set[int] = set()
|
| 56 |
+
current = exc
|
| 57 |
+
while current is not None and id(current) not in seen:
|
| 58 |
+
seen.add(id(current))
|
| 59 |
+
result = _classify_one(current)
|
| 60 |
+
if result[0] != "unknown":
|
| 61 |
+
return result
|
| 62 |
+
current = current.__cause__ or current.__context__
|
| 63 |
+
return ("unknown", "Upstream provider error.")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def new_request_id() -> str:
|
| 67 |
+
return uuid.uuid4().hex[:8]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def upstream_error() -> UpstreamError:
|
| 71 |
+
exc = sys.exc_info()[1]
|
| 72 |
+
code, message = _classify(exc)
|
| 73 |
+
rid = request_id_var.get()
|
| 74 |
+
logging.exception("Upstream provider error (code=%s)", code)
|
| 75 |
+
return UpstreamError(code=code, detail=message, request_id=rid)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
async def upstream_error_handler(_: Request, exc: UpstreamError) -> JSONResponse:
|
| 79 |
+
return JSONResponse(
|
| 80 |
+
status_code=exc.status_code,
|
| 81 |
+
content={"detail": exc.detail, "code": exc.code, "request_id": exc.request_id},
|
| 82 |
+
headers={"X-Request-ID": exc.request_id},
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def install_request_id_logging() -> None:
|
| 87 |
+
old_factory = logging.getLogRecordFactory()
|
| 88 |
+
|
| 89 |
+
def factory(*args, **kwargs):
|
| 90 |
+
record = old_factory(*args, **kwargs)
|
| 91 |
+
record.request_id = request_id_var.get()
|
| 92 |
+
return record
|
| 93 |
+
|
| 94 |
+
logging.setLogRecordFactory(factory)
|
server/main.py
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from typing import Any, Dict, List, Optional
|
| 6 |
+
|
| 7 |
+
import telemetry
|
| 8 |
+
from auth import ADMIN_API_KEY, AUTH_DISABLED, JWT_SECRET, require_admin, verify_auth
|
| 9 |
+
from db import SessionLocal
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
from errors import (
|
| 12 |
+
UpstreamError,
|
| 13 |
+
install_request_id_logging,
|
| 14 |
+
new_request_id,
|
| 15 |
+
request_id_var,
|
| 16 |
+
upstream_error,
|
| 17 |
+
upstream_error_handler,
|
| 18 |
+
)
|
| 19 |
+
from fastapi import Depends, FastAPI, HTTPException, Query, Request
|
| 20 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 21 |
+
from fastapi.responses import JSONResponse, RedirectResponse
|
| 22 |
+
from models import RequestLog, User
|
| 23 |
+
from pydantic import BaseModel, Field
|
| 24 |
+
from rate_limit import limiter
|
| 25 |
+
from routers import api_keys as api_keys_router
|
| 26 |
+
from routers import auth as auth_router
|
| 27 |
+
from routers import entities as entities_router
|
| 28 |
+
from routers import requests as requests_router
|
| 29 |
+
from schemas import MessageResponse
|
| 30 |
+
from server_state import (
|
| 31 |
+
get_current_config,
|
| 32 |
+
get_memory_instance,
|
| 33 |
+
initialize_state,
|
| 34 |
+
set_session_factory,
|
| 35 |
+
update_config,
|
| 36 |
+
)
|
| 37 |
+
from slowapi import _rate_limit_exceeded_handler
|
| 38 |
+
from slowapi.errors import RateLimitExceeded
|
| 39 |
+
from sqlalchemy import func, select
|
| 40 |
+
|
| 41 |
+
from mem0.exceptions import ValidationError as Mem0ValidationError
|
| 42 |
+
|
| 43 |
+
load_dotenv()
|
| 44 |
+
|
| 45 |
+
install_request_id_logging()
|
| 46 |
+
logging.basicConfig(
|
| 47 |
+
level=logging.INFO,
|
| 48 |
+
format="%(asctime)s - %(levelname)s - [%(request_id)s] %(message)s",
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
MIN_KEY_LENGTH = 16
|
| 52 |
+
SENSITIVE_CONFIG_KEYS = {
|
| 53 |
+
"admin_api_key",
|
| 54 |
+
"api_key",
|
| 55 |
+
"authorization",
|
| 56 |
+
"jwt_secret",
|
| 57 |
+
"password",
|
| 58 |
+
"password_hash",
|
| 59 |
+
"secret",
|
| 60 |
+
"token",
|
| 61 |
+
}
|
| 62 |
+
SKIPPED_REQUEST_LOG_PATHS = {"/api/health", "/docs", "/redoc", "/openapi.json"}
|
| 63 |
+
SKIPPED_REQUEST_LOG_PREFIXES = ("/requests",)
|
| 64 |
+
|
| 65 |
+
BUNDLED_LLM_PROVIDERS = ("openai", "anthropic", "gemini")
|
| 66 |
+
BUNDLED_EMBEDDER_PROVIDERS = ("openai", "gemini")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _warn_if_unconfigured() -> None:
|
| 70 |
+
"""Pre-auth deployments upgrading into this build will 401 everywhere until
|
| 71 |
+
an admin key or admin user exists. Surface the fix before the support tickets."""
|
| 72 |
+
try:
|
| 73 |
+
with SessionLocal() as session:
|
| 74 |
+
if session.scalar(select(func.count(User.id))) > 0:
|
| 75 |
+
return
|
| 76 |
+
except Exception:
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
logging.warning(
|
| 80 |
+
"\n%s\n"
|
| 81 |
+
" Auth is enabled by default and this server has no admin configured.\n"
|
| 82 |
+
" Protected endpoints will return 401 until you either:\n"
|
| 83 |
+
" 1. Set ADMIN_API_KEY=<long-random-value> (fastest, no client changes)\n"
|
| 84 |
+
" 2. Register an admin at http://<host>:3000/setup\n"
|
| 85 |
+
" 3. Set AUTH_DISABLED=true (local development only)\n"
|
| 86 |
+
" Docs: https://docs.mem0.ai/open-source/features/rest-api#authentication\n"
|
| 87 |
+
"%s",
|
| 88 |
+
"=" * 72,
|
| 89 |
+
"=" * 72,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if not AUTH_DISABLED and not JWT_SECRET:
|
| 94 |
+
raise RuntimeError(
|
| 95 |
+
"JWT_SECRET is required. Set it in .env (generate with `openssl rand -base64 48`) "
|
| 96 |
+
"or set AUTH_DISABLED=true for local development only."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
if AUTH_DISABLED:
|
| 100 |
+
logging.warning("AUTH_DISABLED is enabled. Protected endpoints are open for local development only.")
|
| 101 |
+
elif ADMIN_API_KEY and len(ADMIN_API_KEY) < MIN_KEY_LENGTH:
|
| 102 |
+
logging.warning(
|
| 103 |
+
"ADMIN_API_KEY is shorter than %d characters - consider using a longer key for production.",
|
| 104 |
+
MIN_KEY_LENGTH,
|
| 105 |
+
)
|
| 106 |
+
elif not ADMIN_API_KEY:
|
| 107 |
+
_warn_if_unconfigured()
|
| 108 |
+
|
| 109 |
+
telemetry.log_status()
|
| 110 |
+
|
| 111 |
+
POSTGRES_HOST = os.environ.get("POSTGRES_HOST", "localhost")
|
| 112 |
+
POSTGRES_PORT = os.environ.get("POSTGRES_PORT", "5432")
|
| 113 |
+
POSTGRES_DB = os.environ.get("POSTGRES_DB", "postgres")
|
| 114 |
+
POSTGRES_USER = os.environ.get("POSTGRES_USER", "mem0")
|
| 115 |
+
POSTGRES_PASSWORD = os.environ.get("POSTGRES_PASSWORD", "postgres")
|
| 116 |
+
POSTGRES_COLLECTION_NAME = os.environ.get("POSTGRES_COLLECTION_NAME", "memories")
|
| 117 |
+
|
| 118 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 119 |
+
HISTORY_DB_PATH = os.environ.get("HISTORY_DB_PATH", "/opt/data/history/history.db")
|
| 120 |
+
DEFAULT_LLM_MODEL = os.environ.get("MEM0_DEFAULT_LLM_MODEL", "gpt-5-mini")
|
| 121 |
+
DEFAULT_EMBEDDER_MODEL = os.environ.get("MEM0_DEFAULT_EMBEDDER_MODEL", "text-embedding-3-small")
|
| 122 |
+
|
| 123 |
+
DEFAULT_CONFIG = {
|
| 124 |
+
"version": "v1.1",
|
| 125 |
+
"vector_store": {
|
| 126 |
+
"provider": "pgvector",
|
| 127 |
+
"config": {
|
| 128 |
+
"host": POSTGRES_HOST,
|
| 129 |
+
"port": int(POSTGRES_PORT),
|
| 130 |
+
"dbname": POSTGRES_DB,
|
| 131 |
+
"user": POSTGRES_USER,
|
| 132 |
+
"password": POSTGRES_PASSWORD,
|
| 133 |
+
"collection_name": POSTGRES_COLLECTION_NAME,
|
| 134 |
+
},
|
| 135 |
+
},
|
| 136 |
+
"llm": {
|
| 137 |
+
"provider": "openai",
|
| 138 |
+
"config": {"api_key": OPENAI_API_KEY, "temperature": 0.2, "model": DEFAULT_LLM_MODEL},
|
| 139 |
+
},
|
| 140 |
+
"embedder": {"provider": "openai", "config": {"api_key": OPENAI_API_KEY, "model": DEFAULT_EMBEDDER_MODEL}},
|
| 141 |
+
"history_db_path": HISTORY_DB_PATH,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
set_session_factory(SessionLocal)
|
| 145 |
+
initialize_state(DEFAULT_CONFIG)
|
| 146 |
+
|
| 147 |
+
app = FastAPI(
|
| 148 |
+
title="Mem0 REST APIs",
|
| 149 |
+
description=(
|
| 150 |
+
"A REST API for managing and searching memories for your AI Agents and Apps.\n\n"
|
| 151 |
+
"## Authentication\n"
|
| 152 |
+
"Supports Bearer JWT tokens, per-user API keys via `X-API-Key` header, "
|
| 153 |
+
"or the legacy `ADMIN_API_KEY` environment variable. Set `AUTH_DISABLED=true` for local development only."
|
| 154 |
+
),
|
| 155 |
+
version="1.0.0",
|
| 156 |
+
redirect_slashes=False,
|
| 157 |
+
)
|
| 158 |
+
app.state.limiter = limiter
|
| 159 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 160 |
+
app.add_exception_handler(UpstreamError, upstream_error_handler)
|
| 161 |
+
|
| 162 |
+
DASHBOARD_URL = os.environ.get("DASHBOARD_URL", "http://localhost:7860")
|
| 163 |
+
app.add_middleware(
|
| 164 |
+
CORSMiddleware,
|
| 165 |
+
allow_origins=[DASHBOARD_URL],
|
| 166 |
+
allow_credentials=True,
|
| 167 |
+
allow_methods=["*"],
|
| 168 |
+
allow_headers=["*"],
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
app.include_router(auth_router.router)
|
| 172 |
+
app.include_router(api_keys_router.router)
|
| 173 |
+
app.include_router(entities_router.router)
|
| 174 |
+
app.include_router(requests_router.router)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class Message(BaseModel):
|
| 178 |
+
role: str = Field(..., description="Role of the message (user or assistant).")
|
| 179 |
+
content: str = Field(..., description="Message content.")
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class MemoryCreate(BaseModel):
|
| 183 |
+
messages: List[Message] = Field(..., description="List of messages to store.")
|
| 184 |
+
user_id: Optional[str] = None
|
| 185 |
+
agent_id: Optional[str] = None
|
| 186 |
+
run_id: Optional[str] = None
|
| 187 |
+
metadata: Optional[Dict[str, Any]] = None
|
| 188 |
+
expiration_date: Optional[str] = Field(None, description="Expiration date in YYYY-MM-DD format.")
|
| 189 |
+
infer: Optional[bool] = Field(None, description="Whether to extract facts from messages. Defaults to True.")
|
| 190 |
+
memory_type: Optional[str] = Field(None, description="Type of memory to store (e.g. 'core').")
|
| 191 |
+
prompt: Optional[str] = Field(None, description="Custom prompt to use for fact extraction.")
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class MemoryUpdate(BaseModel):
|
| 195 |
+
text: Optional[str] = Field(None, description="New content to update the memory with.")
|
| 196 |
+
metadata: Optional[Dict[str, Any]] = Field(None, description="Metadata to update.")
|
| 197 |
+
expiration_date: Optional[str] = Field(None, description="Expiration date in YYYY-MM-DD format, or null to clear.")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class SearchRequest(BaseModel):
|
| 201 |
+
query: str = Field(..., description="Search query.")
|
| 202 |
+
user_id: Optional[str] = Field(None, description="Deprecated: pass inside `filters` instead.", deprecated=True)
|
| 203 |
+
run_id: Optional[str] = Field(None, description="Deprecated: pass inside `filters` instead.", deprecated=True)
|
| 204 |
+
agent_id: Optional[str] = Field(None, description="Deprecated: pass inside `filters` instead.", deprecated=True)
|
| 205 |
+
filters: Optional[Dict[str, Any]] = None
|
| 206 |
+
top_k: Optional[int] = Field(None, description="Maximum number of results to return.")
|
| 207 |
+
threshold: Optional[float] = Field(None, description="Minimum similarity score for results.")
|
| 208 |
+
explain: Optional[bool] = Field(None, description="Include score details for each search result.")
|
| 209 |
+
show_expired: Optional[bool] = Field(None, description="Include expired memories.")
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class GenerateInstructionsRequest(BaseModel):
|
| 213 |
+
use_case: str = Field(..., description="Description of what the user will use Mem0 for.")
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _client_error(exc: Exception) -> HTTPException:
|
| 217 |
+
"""Map core validation / not-found errors to 4xx so clients can tell a bad
|
| 218 |
+
request from an upstream outage. 'not found' is a 404, everything else a 400."""
|
| 219 |
+
detail = str(exc)
|
| 220 |
+
status_code = 404 if isinstance(exc, ValueError) and "not found" in detail.lower() else 400
|
| 221 |
+
return HTTPException(status_code=status_code, detail=detail)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _redact_config(value: Any, key: str | None = None) -> Any:
|
| 225 |
+
if isinstance(value, dict):
|
| 226 |
+
return {item_key: _redact_config(item_value, item_key) for item_key, item_value in value.items()}
|
| 227 |
+
if isinstance(value, list):
|
| 228 |
+
return [_redact_config(item_value, key) for item_value in value]
|
| 229 |
+
if key is not None and key.lower() in SENSITIVE_CONFIG_KEYS:
|
| 230 |
+
return "[redacted]" if value else value
|
| 231 |
+
return value
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _validate_bundled_providers(config: Dict[str, Any]) -> None:
|
| 235 |
+
llm = config.get("llm")
|
| 236 |
+
if isinstance(llm, dict) and (provider := llm.get("provider")) and provider not in BUNDLED_LLM_PROVIDERS:
|
| 237 |
+
raise HTTPException(
|
| 238 |
+
status_code=400,
|
| 239 |
+
detail=(
|
| 240 |
+
f"LLM provider '{provider}' is not bundled in this image. "
|
| 241 |
+
f"Bundled providers: {', '.join(BUNDLED_LLM_PROVIDERS)}. "
|
| 242 |
+
"To use another provider, install its Python package, rebuild the container, "
|
| 243 |
+
"and extend BUNDLED_LLM_PROVIDERS in server/main.py."
|
| 244 |
+
),
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
embedder = config.get("embedder")
|
| 248 |
+
if isinstance(embedder, dict) and (provider := embedder.get("provider")) and provider not in BUNDLED_EMBEDDER_PROVIDERS:
|
| 249 |
+
raise HTTPException(
|
| 250 |
+
status_code=400,
|
| 251 |
+
detail=(
|
| 252 |
+
f"Embedder provider '{provider}' is not bundled in this image. "
|
| 253 |
+
f"Bundled providers: {', '.join(BUNDLED_EMBEDDER_PROVIDERS)}. "
|
| 254 |
+
"To use another provider, install its Python package, rebuild the container, "
|
| 255 |
+
"and extend BUNDLED_EMBEDDER_PROVIDERS in server/main.py."
|
| 256 |
+
),
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _should_log_request(request: Request) -> bool:
|
| 261 |
+
if request.method == "OPTIONS":
|
| 262 |
+
return False
|
| 263 |
+
path = request.url.path
|
| 264 |
+
if path in SKIPPED_REQUEST_LOG_PATHS:
|
| 265 |
+
return False
|
| 266 |
+
return not path.startswith(SKIPPED_REQUEST_LOG_PREFIXES)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _persist_request_log(method: str, path: str, status_code: int, latency_ms: float, auth_type: str) -> None:
|
| 270 |
+
session = SessionLocal()
|
| 271 |
+
try:
|
| 272 |
+
session.add(
|
| 273 |
+
RequestLog(
|
| 274 |
+
method=method,
|
| 275 |
+
path=path,
|
| 276 |
+
status_code=status_code,
|
| 277 |
+
latency_ms=latency_ms,
|
| 278 |
+
auth_type=auth_type,
|
| 279 |
+
)
|
| 280 |
+
)
|
| 281 |
+
session.commit()
|
| 282 |
+
except Exception:
|
| 283 |
+
session.rollback()
|
| 284 |
+
logging.exception("Failed to persist request log")
|
| 285 |
+
finally:
|
| 286 |
+
session.close()
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
@app.middleware("http")
|
| 290 |
+
async def log_requests(request: Request, call_next):
|
| 291 |
+
request.state.auth_type = getattr(request.state, "auth_type", "none")
|
| 292 |
+
rid = new_request_id()
|
| 293 |
+
token = request_id_var.set(rid)
|
| 294 |
+
start = time.perf_counter()
|
| 295 |
+
status_code = 500
|
| 296 |
+
|
| 297 |
+
try:
|
| 298 |
+
response = await call_next(request)
|
| 299 |
+
status_code = response.status_code
|
| 300 |
+
response.headers["X-Request-ID"] = rid
|
| 301 |
+
return response
|
| 302 |
+
except Exception:
|
| 303 |
+
status_code = 500
|
| 304 |
+
raise
|
| 305 |
+
finally:
|
| 306 |
+
request_id_var.reset(token)
|
| 307 |
+
if _should_log_request(request):
|
| 308 |
+
asyncio.get_running_loop().run_in_executor(
|
| 309 |
+
None,
|
| 310 |
+
_persist_request_log,
|
| 311 |
+
request.method,
|
| 312 |
+
request.url.path,
|
| 313 |
+
status_code,
|
| 314 |
+
round((time.perf_counter() - start) * 1000, 2),
|
| 315 |
+
getattr(request.state, "auth_type", "none"),
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@app.get("/configure", summary="Get current Mem0 configuration")
|
| 320 |
+
def get_config(_auth=Depends(verify_auth)):
|
| 321 |
+
return _redact_config(get_current_config())
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@app.get("/configure/providers", summary="List bundled LLM and embedder providers")
|
| 325 |
+
def list_bundled_providers(_auth=Depends(verify_auth)):
|
| 326 |
+
return {"llm": list(BUNDLED_LLM_PROVIDERS), "embedder": list(BUNDLED_EMBEDDER_PROVIDERS)}
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@app.post("/configure", summary="Configure Mem0")
|
| 330 |
+
def set_config(config: Dict[str, Any], _auth=Depends(require_admin)):
|
| 331 |
+
"""Set memory configuration. Requires admin role."""
|
| 332 |
+
_validate_bundled_providers(config)
|
| 333 |
+
update_config(config)
|
| 334 |
+
return {"message": "Configuration set successfully"}
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
@app.post("/generate-instructions", summary="Generate custom instructions from a use case")
|
| 338 |
+
def generate_instructions(req: GenerateInstructionsRequest, _auth=Depends(verify_auth)):
|
| 339 |
+
"""Generate custom instructions and a contextual test message tailored to a use case."""
|
| 340 |
+
try:
|
| 341 |
+
llm = get_memory_instance().llm
|
| 342 |
+
prompt = (
|
| 343 |
+
"You are configuring a memory system. Given the use case below, produce two things:\n"
|
| 344 |
+
"1. INSTRUCTIONS: A short paragraph of custom instructions telling the memory extraction system "
|
| 345 |
+
"what kinds of facts, preferences, and context to prioritize. Be specific to the use case.\n"
|
| 346 |
+
"2. TEST_MESSAGE: A single realistic sentence a user in this use case would say, suitable for "
|
| 347 |
+
"testing that the memory system works.\n\n"
|
| 348 |
+
"Respond in exactly this format (no markdown, no extra text):\n"
|
| 349 |
+
"INSTRUCTIONS: <your instructions>\n"
|
| 350 |
+
f"TEST_MESSAGE: <your test message>\n\nUse case: {req.use_case}"
|
| 351 |
+
)
|
| 352 |
+
response = llm.generate_response([{"role": "user", "content": prompt}])
|
| 353 |
+
instructions = response
|
| 354 |
+
test_message = "I like to hike on weekends."
|
| 355 |
+
if "INSTRUCTIONS:" in response and "TEST_MESSAGE:" in response:
|
| 356 |
+
parts = response.split("TEST_MESSAGE:")
|
| 357 |
+
instructions = parts[0].replace("INSTRUCTIONS:", "").strip()
|
| 358 |
+
test_message = parts[1].strip()
|
| 359 |
+
return {"custom_instructions": instructions, "test_message": test_message}
|
| 360 |
+
except Exception:
|
| 361 |
+
raise upstream_error()
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
@app.post("/memories", summary="Create memories")
|
| 365 |
+
def add_memory(memory_create: MemoryCreate, _auth=Depends(verify_auth)):
|
| 366 |
+
"""Store new memories."""
|
| 367 |
+
if not any([memory_create.user_id, memory_create.agent_id, memory_create.run_id]):
|
| 368 |
+
raise HTTPException(status_code=400, detail="At least one identifier (user_id, agent_id, run_id) is required.")
|
| 369 |
+
|
| 370 |
+
params = {k: v for k, v in memory_create.model_dump().items() if v is not None and k != "messages"}
|
| 371 |
+
try:
|
| 372 |
+
response = get_memory_instance().add(messages=[m.model_dump() for m in memory_create.messages], **params)
|
| 373 |
+
if response.get("results"):
|
| 374 |
+
telemetry.log_dashboard_nudge_once(DASHBOARD_URL)
|
| 375 |
+
return JSONResponse(content=response)
|
| 376 |
+
except (ValueError, Mem0ValidationError) as e:
|
| 377 |
+
raise _client_error(e)
|
| 378 |
+
except Exception:
|
| 379 |
+
raise upstream_error()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
ALL_MEMORIES_LIMIT = 1000
|
| 383 |
+
_RESERVED_PAYLOAD_KEYS = {"data", "user_id", "agent_id", "run_id", "hash", "created_at", "updated_at", "expiration_date"}
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def _serialize_memory(row: Any) -> Dict[str, Any]:
|
| 387 |
+
payload = getattr(row, "payload", None) or {}
|
| 388 |
+
return {
|
| 389 |
+
"id": getattr(row, "id", None),
|
| 390 |
+
"memory": payload.get("data"),
|
| 391 |
+
"user_id": payload.get("user_id"),
|
| 392 |
+
"agent_id": payload.get("agent_id"),
|
| 393 |
+
"run_id": payload.get("run_id"),
|
| 394 |
+
"hash": payload.get("hash"),
|
| 395 |
+
"expiration_date": payload.get("expiration_date"),
|
| 396 |
+
"metadata": {k: v for k, v in payload.items() if k not in _RESERVED_PAYLOAD_KEYS},
|
| 397 |
+
"created_at": payload.get("created_at"),
|
| 398 |
+
"updated_at": payload.get("updated_at"),
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def _list_all_memories(limit: int = ALL_MEMORIES_LIMIT) -> Dict[str, Any]:
|
| 403 |
+
results = get_memory_instance().vector_store.list(top_k=limit)
|
| 404 |
+
rows = results[0] if results and isinstance(results, list) and isinstance(results[0], list) else results or []
|
| 405 |
+
return {"results": [_serialize_memory(row) for row in rows]}
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@app.get("/memories", summary="Get memories")
|
| 409 |
+
def get_all_memories(
|
| 410 |
+
request: Request,
|
| 411 |
+
user_id: Optional[str] = None,
|
| 412 |
+
run_id: Optional[str] = None,
|
| 413 |
+
agent_id: Optional[str] = None,
|
| 414 |
+
top_k: Optional[int] = Query(None, ge=0, le=ALL_MEMORIES_LIMIT),
|
| 415 |
+
show_expired: bool = Query(False),
|
| 416 |
+
_auth=Depends(verify_auth),
|
| 417 |
+
):
|
| 418 |
+
"""Retrieve stored memories. Lists all memories when no identifier is provided (admin only)."""
|
| 419 |
+
try:
|
| 420 |
+
if not any([user_id, run_id, agent_id]):
|
| 421 |
+
auth_type = getattr(request.state, "auth_type", "none")
|
| 422 |
+
if _auth is not None and _auth.role != "admin" and auth_type not in {"admin_api_key", "disabled"}:
|
| 423 |
+
raise HTTPException(status_code=403, detail="Admin role required to list all memories.")
|
| 424 |
+
# Admin all-memory listing is intentionally raw; scoped get_all below applies expiry visibility.
|
| 425 |
+
return _list_all_memories(limit=top_k if top_k is not None else ALL_MEMORIES_LIMIT)
|
| 426 |
+
filters = {k: v for k, v in {"user_id": user_id, "run_id": run_id, "agent_id": agent_id}.items() if v}
|
| 427 |
+
params = {"filters": filters}
|
| 428 |
+
if top_k is not None:
|
| 429 |
+
params["top_k"] = top_k
|
| 430 |
+
params["show_expired"] = show_expired
|
| 431 |
+
return get_memory_instance().get_all(**params)
|
| 432 |
+
except HTTPException:
|
| 433 |
+
raise
|
| 434 |
+
except Exception:
|
| 435 |
+
raise upstream_error()
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
@app.get("/memories/{memory_id}", summary="Get a memory")
|
| 439 |
+
def get_memory(memory_id: str, _auth=Depends(verify_auth)):
|
| 440 |
+
"""Retrieve a specific memory by ID."""
|
| 441 |
+
try:
|
| 442 |
+
return get_memory_instance().get(memory_id)
|
| 443 |
+
except Exception:
|
| 444 |
+
raise upstream_error()
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
@app.post("/search", summary="Search memories")
|
| 448 |
+
def search_memories(search_req: SearchRequest, _auth=Depends(verify_auth)):
|
| 449 |
+
"""Search for memories based on a query."""
|
| 450 |
+
try:
|
| 451 |
+
filters = search_req.filters or {}
|
| 452 |
+
deprecated_keys = []
|
| 453 |
+
for entity_key in ("user_id", "agent_id", "run_id"):
|
| 454 |
+
entity_val = getattr(search_req, entity_key, None)
|
| 455 |
+
if entity_val:
|
| 456 |
+
filters[entity_key] = entity_val
|
| 457 |
+
deprecated_keys.append(entity_key)
|
| 458 |
+
if deprecated_keys:
|
| 459 |
+
logging.warning(
|
| 460 |
+
"Top-level %s in /search is deprecated. Use filters={%s} instead.",
|
| 461 |
+
", ".join(deprecated_keys),
|
| 462 |
+
", ".join(f'"{k}: "..."' for k in deprecated_keys),
|
| 463 |
+
)
|
| 464 |
+
params = {}
|
| 465 |
+
if search_req.top_k is not None:
|
| 466 |
+
params["top_k"] = search_req.top_k
|
| 467 |
+
if search_req.threshold is not None:
|
| 468 |
+
params["threshold"] = search_req.threshold
|
| 469 |
+
if search_req.explain is not None:
|
| 470 |
+
params["explain"] = search_req.explain
|
| 471 |
+
if search_req.show_expired is not None:
|
| 472 |
+
params["show_expired"] = search_req.show_expired
|
| 473 |
+
return get_memory_instance().search(query=search_req.query, filters=filters, **params)
|
| 474 |
+
except ValueError as e:
|
| 475 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 476 |
+
except HTTPException:
|
| 477 |
+
raise
|
| 478 |
+
except Exception:
|
| 479 |
+
raise upstream_error()
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
@app.put("/memories/{memory_id}", summary="Update a memory")
|
| 483 |
+
def update_memory(memory_id: str, updated_memory: MemoryUpdate, _auth=Depends(verify_auth)):
|
| 484 |
+
"""Update an existing memory."""
|
| 485 |
+
try:
|
| 486 |
+
fields_set = getattr(updated_memory, "model_fields_set", getattr(updated_memory, "__fields_set__", set()))
|
| 487 |
+
params = {"memory_id": memory_id}
|
| 488 |
+
if "text" in fields_set:
|
| 489 |
+
params["data"] = updated_memory.text
|
| 490 |
+
if "metadata" in fields_set:
|
| 491 |
+
params["metadata"] = updated_memory.metadata
|
| 492 |
+
if "expiration_date" in fields_set:
|
| 493 |
+
params["expiration_date"] = updated_memory.expiration_date
|
| 494 |
+
return get_memory_instance().update(**params)
|
| 495 |
+
except (ValueError, Mem0ValidationError) as e:
|
| 496 |
+
raise _client_error(e)
|
| 497 |
+
except Exception:
|
| 498 |
+
raise upstream_error()
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
@app.get("/memories/{memory_id}/history", summary="Get memory history")
|
| 502 |
+
def memory_history(memory_id: str, _auth=Depends(verify_auth)):
|
| 503 |
+
"""Retrieve memory history."""
|
| 504 |
+
try:
|
| 505 |
+
return get_memory_instance().history(memory_id=memory_id)
|
| 506 |
+
except Exception:
|
| 507 |
+
raise upstream_error()
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
@app.delete("/memories/{memory_id}", summary="Delete a memory", response_model=MessageResponse)
|
| 511 |
+
def delete_memory(memory_id: str, _auth=Depends(verify_auth)):
|
| 512 |
+
"""Delete a specific memory by ID."""
|
| 513 |
+
try:
|
| 514 |
+
get_memory_instance().delete(memory_id=memory_id)
|
| 515 |
+
return MessageResponse(message="Memory deleted successfully")
|
| 516 |
+
except (ValueError, Mem0ValidationError) as e:
|
| 517 |
+
raise _client_error(e)
|
| 518 |
+
except Exception:
|
| 519 |
+
raise upstream_error()
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
@app.delete("/memories", summary="Delete all memories", response_model=MessageResponse)
|
| 523 |
+
def delete_all_memories(
|
| 524 |
+
user_id: Optional[str] = None,
|
| 525 |
+
run_id: Optional[str] = None,
|
| 526 |
+
agent_id: Optional[str] = None,
|
| 527 |
+
_auth=Depends(require_admin),
|
| 528 |
+
):
|
| 529 |
+
"""Delete all memories for a given identifier. Requires admin role."""
|
| 530 |
+
if not any([user_id, run_id, agent_id]):
|
| 531 |
+
raise HTTPException(status_code=400, detail="At least one identifier is required.")
|
| 532 |
+
try:
|
| 533 |
+
params = {k: v for k, v in {"user_id": user_id, "run_id": run_id, "agent_id": agent_id}.items() if v}
|
| 534 |
+
get_memory_instance().delete_all(**params)
|
| 535 |
+
return MessageResponse(message="All relevant memories deleted")
|
| 536 |
+
except Exception:
|
| 537 |
+
raise upstream_error()
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
@app.post("/reset", summary="Reset all memories")
|
| 541 |
+
def reset_memory(_auth=Depends(require_admin)):
|
| 542 |
+
"""Completely reset stored memories. Requires admin role."""
|
| 543 |
+
try:
|
| 544 |
+
get_memory_instance().reset()
|
| 545 |
+
return {"message": "All memories reset"}
|
| 546 |
+
except Exception:
|
| 547 |
+
raise upstream_error()
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
@app.get("/", summary="Redirect to the OpenAPI documentation", include_in_schema=False)
|
| 551 |
+
def home():
|
| 552 |
+
"""Redirect to the OpenAPI documentation."""
|
| 553 |
+
return RedirectResponse(url="/docs")
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
@app.get("/health", summary="Health check", include_in_schema=False)
|
| 557 |
+
def health():
|
| 558 |
+
"""Health check endpoint."""
|
| 559 |
+
return {"status": "healthy"}
|
server/models.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import datetime, timezone
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import DateTime, Float, ForeignKey, Integer, String, Text
|
| 5 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 6 |
+
|
| 7 |
+
from db import Base
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _utcnow() -> datetime:
|
| 11 |
+
return datetime.now(timezone.utc)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _new_uuid() -> uuid.UUID:
|
| 15 |
+
return uuid.uuid4()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class User(Base):
|
| 19 |
+
__tablename__ = "users"
|
| 20 |
+
|
| 21 |
+
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=_new_uuid)
|
| 22 |
+
name: Mapped[str] = mapped_column(String(255))
|
| 23 |
+
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
|
| 24 |
+
password_hash: Mapped[str] = mapped_column(Text)
|
| 25 |
+
role: Mapped[str] = mapped_column(String(20), default="admin")
|
| 26 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
| 27 |
+
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class APIKey(Base):
|
| 31 |
+
__tablename__ = "api_keys"
|
| 32 |
+
|
| 33 |
+
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=_new_uuid)
|
| 34 |
+
key_prefix: Mapped[str] = mapped_column(String(12))
|
| 35 |
+
key_hash: Mapped[str] = mapped_column(Text)
|
| 36 |
+
label: Mapped[str] = mapped_column(String(255))
|
| 37 |
+
created_by: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
| 38 |
+
last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 39 |
+
revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 40 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class RequestLog(Base):
|
| 44 |
+
__tablename__ = "request_logs"
|
| 45 |
+
|
| 46 |
+
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=_new_uuid)
|
| 47 |
+
method: Mapped[str] = mapped_column(String(16))
|
| 48 |
+
path: Mapped[str] = mapped_column(String(512))
|
| 49 |
+
status_code: Mapped[int] = mapped_column(Integer)
|
| 50 |
+
latency_ms: Mapped[float] = mapped_column(Float)
|
| 51 |
+
auth_type: Mapped[str] = mapped_column(String(32), default="none")
|
| 52 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class RefreshTokenJti(Base):
|
| 56 |
+
__tablename__ = "refresh_token_jtis"
|
| 57 |
+
|
| 58 |
+
jti: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=_new_uuid)
|
| 59 |
+
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
| 60 |
+
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
| 61 |
+
used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 62 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Settings(Base):
|
| 66 |
+
__tablename__ = "settings"
|
| 67 |
+
|
| 68 |
+
key: Mapped[str] = mapped_column(String(255), primary_key=True)
|
| 69 |
+
value: Mapped[str] = mapped_column(Text)
|
| 70 |
+
updated_at: Mapped[datetime] = mapped_column(
|
| 71 |
+
DateTime(timezone=True),
|
| 72 |
+
default=_utcnow,
|
| 73 |
+
onupdate=_utcnow,
|
| 74 |
+
)
|
server/rate_limit.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from slowapi import Limiter
|
| 2 |
+
from slowapi.util import get_remote_address
|
| 3 |
+
|
| 4 |
+
limiter = Limiter(key_func=get_remote_address)
|
server/routers/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Router package
|
server/routers/api_keys.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import datetime, timezone
|
| 3 |
+
|
| 4 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from sqlalchemy import select
|
| 7 |
+
from sqlalchemy.orm import Session
|
| 8 |
+
|
| 9 |
+
from auth import generate_api_key, require_auth
|
| 10 |
+
from db import get_db
|
| 11 |
+
from models import APIKey, User
|
| 12 |
+
from schemas import MessageResponse
|
| 13 |
+
|
| 14 |
+
router = APIRouter(prefix="/api-keys", tags=["api-keys"])
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class CreateKeyRequest(BaseModel):
|
| 18 |
+
label: str
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class CreateKeyResponse(BaseModel):
|
| 22 |
+
id: str
|
| 23 |
+
key: str
|
| 24 |
+
label: str
|
| 25 |
+
key_prefix: str
|
| 26 |
+
created_at: datetime
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class KeyListItem(BaseModel):
|
| 30 |
+
id: str
|
| 31 |
+
label: str
|
| 32 |
+
key_prefix: str
|
| 33 |
+
created_at: datetime
|
| 34 |
+
last_used_at: datetime | None
|
| 35 |
+
|
| 36 |
+
model_config = {"from_attributes": True}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@router.get("", response_model=list[KeyListItem])
|
| 40 |
+
def list_keys(user: User = Depends(require_auth), db: Session = Depends(get_db)):
|
| 41 |
+
keys = (
|
| 42 |
+
db.execute(
|
| 43 |
+
select(APIKey)
|
| 44 |
+
.where(APIKey.created_by == user.id, APIKey.revoked_at.is_(None))
|
| 45 |
+
.order_by(APIKey.created_at.desc())
|
| 46 |
+
)
|
| 47 |
+
.scalars()
|
| 48 |
+
.all()
|
| 49 |
+
)
|
| 50 |
+
return [
|
| 51 |
+
KeyListItem(
|
| 52 |
+
id=str(k.id),
|
| 53 |
+
label=k.label,
|
| 54 |
+
key_prefix=k.key_prefix,
|
| 55 |
+
created_at=k.created_at,
|
| 56 |
+
last_used_at=k.last_used_at,
|
| 57 |
+
)
|
| 58 |
+
for k in keys
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@router.post("", response_model=CreateKeyResponse, status_code=201)
|
| 63 |
+
def create_key(body: CreateKeyRequest, user: User = Depends(require_auth), db: Session = Depends(get_db)):
|
| 64 |
+
full_key, prefix, key_hash = generate_api_key()
|
| 65 |
+
api_key = APIKey(key_prefix=prefix, key_hash=key_hash, label=body.label, created_by=user.id)
|
| 66 |
+
db.add(api_key)
|
| 67 |
+
db.commit()
|
| 68 |
+
db.refresh(api_key)
|
| 69 |
+
|
| 70 |
+
return CreateKeyResponse(
|
| 71 |
+
id=str(api_key.id),
|
| 72 |
+
key=full_key,
|
| 73 |
+
label=api_key.label,
|
| 74 |
+
key_prefix=prefix,
|
| 75 |
+
created_at=api_key.created_at,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@router.delete("/{key_id}", response_model=MessageResponse)
|
| 80 |
+
def revoke_key(key_id: str, user: User = Depends(require_auth), db: Session = Depends(get_db)):
|
| 81 |
+
try:
|
| 82 |
+
key_uuid = uuid.UUID(key_id)
|
| 83 |
+
except (TypeError, ValueError):
|
| 84 |
+
raise HTTPException(status_code=404, detail="API key not found.")
|
| 85 |
+
api_key = db.get(APIKey, key_uuid)
|
| 86 |
+
if api_key is None or api_key.created_by != user.id:
|
| 87 |
+
raise HTTPException(status_code=404, detail="API key not found.")
|
| 88 |
+
if api_key.revoked_at is not None:
|
| 89 |
+
raise HTTPException(status_code=400, detail="API key is already revoked.")
|
| 90 |
+
|
| 91 |
+
api_key.revoked_at = datetime.now(timezone.utc)
|
| 92 |
+
db.commit()
|
| 93 |
+
return MessageResponse(message="API key revoked.")
|
server/routers/auth.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import datetime, timezone
|
| 3 |
+
|
| 4 |
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
| 5 |
+
from pydantic import BaseModel, EmailStr
|
| 6 |
+
from sqlalchemy import func, select
|
| 7 |
+
from sqlalchemy.exc import IntegrityError
|
| 8 |
+
from sqlalchemy.orm import Session
|
| 9 |
+
|
| 10 |
+
from auth import (
|
| 11 |
+
consume_refresh_jti,
|
| 12 |
+
create_access_token,
|
| 13 |
+
create_refresh_token,
|
| 14 |
+
decode_token,
|
| 15 |
+
dummy_verify_password,
|
| 16 |
+
hash_password,
|
| 17 |
+
require_auth,
|
| 18 |
+
verify_password,
|
| 19 |
+
)
|
| 20 |
+
from db import get_db
|
| 21 |
+
from models import User
|
| 22 |
+
from rate_limit import limiter
|
| 23 |
+
from schemas import MessageResponse
|
| 24 |
+
from telemetry import capture_admin_registered, capture_onboarding_completed
|
| 25 |
+
|
| 26 |
+
router = APIRouter(prefix="/auth", tags=["auth"])
|
| 27 |
+
|
| 28 |
+
MIN_PASSWORD_LENGTH = 8
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _require_password_length(password: str) -> None:
|
| 32 |
+
if len(password) < MIN_PASSWORD_LENGTH:
|
| 33 |
+
raise HTTPException(
|
| 34 |
+
status_code=400,
|
| 35 |
+
detail=f"Password must be at least {MIN_PASSWORD_LENGTH} characters.",
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class RegisterRequest(BaseModel):
|
| 40 |
+
name: str
|
| 41 |
+
email: EmailStr
|
| 42 |
+
password: str
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class OnboardingCompleteRequest(BaseModel):
|
| 46 |
+
use_case: str
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class LoginRequest(BaseModel):
|
| 50 |
+
email: EmailStr
|
| 51 |
+
password: str
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class RefreshRequest(BaseModel):
|
| 55 |
+
refresh_token: str
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class UpdateProfileRequest(BaseModel):
|
| 59 |
+
name: str | None = None
|
| 60 |
+
email: EmailStr | None = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class ChangePasswordRequest(BaseModel):
|
| 64 |
+
current_password: str
|
| 65 |
+
new_password: str
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class TokenResponse(BaseModel):
|
| 69 |
+
access_token: str
|
| 70 |
+
refresh_token: str
|
| 71 |
+
token_type: str = "bearer"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class UserResponse(BaseModel):
|
| 75 |
+
id: uuid.UUID
|
| 76 |
+
name: str
|
| 77 |
+
email: str
|
| 78 |
+
role: str
|
| 79 |
+
created_at: datetime
|
| 80 |
+
|
| 81 |
+
model_config = {"from_attributes": True}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class SetupStatusResponse(BaseModel):
|
| 85 |
+
needsSetup: bool
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@router.get("/setup-status", response_model=SetupStatusResponse)
|
| 89 |
+
def setup_status(db: Session = Depends(get_db)):
|
| 90 |
+
count = db.scalar(select(func.count(User.id)))
|
| 91 |
+
return SetupStatusResponse(needsSetup=count == 0)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@router.post("/register", response_model=TokenResponse)
|
| 95 |
+
@limiter.limit("5/minute")
|
| 96 |
+
def register(request: Request, body: RegisterRequest, db: Session = Depends(get_db)):
|
| 97 |
+
"""Create the first admin account. Blocked once any user exists."""
|
| 98 |
+
_require_password_length(body.password)
|
| 99 |
+
|
| 100 |
+
if db.scalar(select(func.count(User.id))) > 0:
|
| 101 |
+
raise HTTPException(status_code=403, detail="Registration is closed. An admin account already exists.")
|
| 102 |
+
|
| 103 |
+
user = User(
|
| 104 |
+
name=body.name,
|
| 105 |
+
email=body.email,
|
| 106 |
+
password_hash=hash_password(body.password),
|
| 107 |
+
role="admin",
|
| 108 |
+
)
|
| 109 |
+
db.add(user)
|
| 110 |
+
try:
|
| 111 |
+
db.commit()
|
| 112 |
+
except IntegrityError:
|
| 113 |
+
db.rollback()
|
| 114 |
+
raise HTTPException(status_code=403, detail="Registration is closed. An admin account already exists.")
|
| 115 |
+
db.refresh(user)
|
| 116 |
+
|
| 117 |
+
capture_admin_registered(email=body.email)
|
| 118 |
+
|
| 119 |
+
return TokenResponse(
|
| 120 |
+
access_token=create_access_token(str(user.id), user.role),
|
| 121 |
+
refresh_token=create_refresh_token(str(user.id), db),
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@router.post("/login", response_model=TokenResponse)
|
| 126 |
+
@limiter.limit("10/minute")
|
| 127 |
+
def login(request: Request, body: LoginRequest, db: Session = Depends(get_db)):
|
| 128 |
+
user = db.scalar(select(User).where(User.email == body.email))
|
| 129 |
+
if user is None:
|
| 130 |
+
dummy_verify_password()
|
| 131 |
+
raise HTTPException(status_code=401, detail="Invalid email or password.")
|
| 132 |
+
if not verify_password(body.password, user.password_hash):
|
| 133 |
+
raise HTTPException(status_code=401, detail="Invalid email or password.")
|
| 134 |
+
|
| 135 |
+
user.last_login_at = datetime.now(timezone.utc)
|
| 136 |
+
db.commit()
|
| 137 |
+
|
| 138 |
+
return TokenResponse(
|
| 139 |
+
access_token=create_access_token(str(user.id), user.role),
|
| 140 |
+
refresh_token=create_refresh_token(str(user.id), db),
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@router.post("/refresh", response_model=TokenResponse)
|
| 145 |
+
@limiter.limit("20/minute")
|
| 146 |
+
def refresh(request: Request, body: RefreshRequest, db: Session = Depends(get_db)):
|
| 147 |
+
payload = decode_token(body.refresh_token)
|
| 148 |
+
if payload.get("type") != "refresh":
|
| 149 |
+
raise HTTPException(status_code=401, detail="Invalid token type.")
|
| 150 |
+
|
| 151 |
+
jti = payload.get("jti")
|
| 152 |
+
if not jti:
|
| 153 |
+
raise HTTPException(status_code=401, detail="Refresh token is no longer valid.")
|
| 154 |
+
|
| 155 |
+
user = db.get(User, payload["sub"])
|
| 156 |
+
if user is None:
|
| 157 |
+
raise HTTPException(status_code=401, detail="User not found.")
|
| 158 |
+
|
| 159 |
+
consume_refresh_jti(jti, db)
|
| 160 |
+
|
| 161 |
+
return TokenResponse(
|
| 162 |
+
access_token=create_access_token(str(user.id), user.role),
|
| 163 |
+
refresh_token=create_refresh_token(str(user.id), db),
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@router.get("/me", response_model=UserResponse)
|
| 168 |
+
def me(user: User = Depends(require_auth)):
|
| 169 |
+
return user
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@router.patch("/me", response_model=UserResponse)
|
| 173 |
+
def update_me(
|
| 174 |
+
body: UpdateProfileRequest,
|
| 175 |
+
user: User = Depends(require_auth),
|
| 176 |
+
db: Session = Depends(get_db),
|
| 177 |
+
):
|
| 178 |
+
# require_auth resolves the user in its own short-lived session, so `user`
|
| 179 |
+
# is detached from this request's `db`. Load a session-managed copy to mutate.
|
| 180 |
+
db_user = db.get(User, user.id)
|
| 181 |
+
if db_user is None:
|
| 182 |
+
raise HTTPException(status_code=404, detail="User not found.")
|
| 183 |
+
|
| 184 |
+
if body.name is not None and body.name.strip():
|
| 185 |
+
db_user.name = body.name.strip()
|
| 186 |
+
|
| 187 |
+
if body.email is not None and body.email != db_user.email:
|
| 188 |
+
collision = db.scalar(select(User).where(User.email == body.email, User.id != db_user.id))
|
| 189 |
+
if collision is not None:
|
| 190 |
+
raise HTTPException(status_code=409, detail="Email is already in use.")
|
| 191 |
+
db_user.email = body.email
|
| 192 |
+
|
| 193 |
+
db.commit()
|
| 194 |
+
db.refresh(db_user)
|
| 195 |
+
return db_user
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@router.post("/change-password", response_model=MessageResponse)
|
| 199 |
+
def change_password(
|
| 200 |
+
body: ChangePasswordRequest,
|
| 201 |
+
user: User = Depends(require_auth),
|
| 202 |
+
db: Session = Depends(get_db),
|
| 203 |
+
):
|
| 204 |
+
# require_auth resolves the user in its own short-lived session, so `user`
|
| 205 |
+
# is detached from this request's `db`. Load a session-managed copy to mutate.
|
| 206 |
+
db_user = db.get(User, user.id)
|
| 207 |
+
if db_user is None or not verify_password(body.current_password, db_user.password_hash):
|
| 208 |
+
raise HTTPException(status_code=401, detail="Current password is incorrect.")
|
| 209 |
+
|
| 210 |
+
_require_password_length(body.new_password)
|
| 211 |
+
|
| 212 |
+
db_user.password_hash = hash_password(body.new_password)
|
| 213 |
+
db.commit()
|
| 214 |
+
return MessageResponse(message="Password updated.")
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@router.post("/onboarding-complete", response_model=MessageResponse)
|
| 218 |
+
def onboarding_complete(body: OnboardingCompleteRequest, user: User = Depends(require_auth)):
|
| 219 |
+
"""Fire the one-shot telemetry event after the setup wizard reaches its success state."""
|
| 220 |
+
capture_onboarding_completed(email=user.email, use_case=body.use_case)
|
| 221 |
+
return MessageResponse(message="Onboarding completed.")
|
server/routers/entities.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Any, Literal, Optional
|
| 4 |
+
|
| 5 |
+
from auth import require_admin, verify_auth
|
| 6 |
+
from errors import upstream_error
|
| 7 |
+
from fastapi import APIRouter, Depends
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
from schemas import MessageResponse
|
| 10 |
+
from server_state import get_memory_instance
|
| 11 |
+
|
| 12 |
+
router = APIRouter(prefix="/entities", tags=["entities"])
|
| 13 |
+
|
| 14 |
+
SCAN_LIMIT = 10_000
|
| 15 |
+
|
| 16 |
+
EntityType = Literal["user", "agent", "run"]
|
| 17 |
+
TYPE_TO_FIELD: dict[EntityType, str] = {"user": "user_id", "agent": "agent_id", "run": "run_id"}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Entity(BaseModel):
|
| 21 |
+
id: str
|
| 22 |
+
type: EntityType
|
| 23 |
+
total_memories: int
|
| 24 |
+
created_at: Optional[datetime] = None
|
| 25 |
+
updated_at: Optional[datetime] = None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _iter_payloads() -> list[dict[str, Any]]:
|
| 29 |
+
results = get_memory_instance().vector_store.list(top_k=SCAN_LIMIT)
|
| 30 |
+
rows = results[0] if results and isinstance(results, list) and isinstance(results[0], list) else results or []
|
| 31 |
+
return [getattr(row, "payload", None) or {} for row in rows]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _parse_timestamp(value: Any) -> Optional[datetime]:
|
| 35 |
+
if not value:
|
| 36 |
+
return None
|
| 37 |
+
try:
|
| 38 |
+
return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
| 39 |
+
except ValueError:
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@router.get("", response_model=list[Entity])
|
| 44 |
+
def list_entities(_auth=Depends(verify_auth)):
|
| 45 |
+
buckets: dict[tuple[EntityType, str], dict[str, Any]] = defaultdict(
|
| 46 |
+
lambda: {"total_memories": 0, "created_at": None, "updated_at": None}
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
for payload in _iter_payloads():
|
| 50 |
+
created = _parse_timestamp(payload.get("created_at"))
|
| 51 |
+
updated = _parse_timestamp(payload.get("updated_at")) or created
|
| 52 |
+
|
| 53 |
+
for entity_type, field in TYPE_TO_FIELD.items():
|
| 54 |
+
value = payload.get(field)
|
| 55 |
+
if not value:
|
| 56 |
+
continue
|
| 57 |
+
bucket = buckets[(entity_type, str(value))]
|
| 58 |
+
bucket["total_memories"] += 1
|
| 59 |
+
|
| 60 |
+
if created and (bucket["created_at"] is None or created < bucket["created_at"]):
|
| 61 |
+
bucket["created_at"] = created
|
| 62 |
+
if updated and (bucket["updated_at"] is None or updated > bucket["updated_at"]):
|
| 63 |
+
bucket["updated_at"] = updated
|
| 64 |
+
|
| 65 |
+
return [
|
| 66 |
+
Entity(id=entity_id, type=entity_type, **data)
|
| 67 |
+
for (entity_type, entity_id), data in sorted(buckets.items(), key=lambda item: (item[0][0], item[0][1]))
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@router.delete("/{entity_type}/{entity_id}", response_model=MessageResponse)
|
| 72 |
+
def delete_entity(entity_type: EntityType, entity_id: str, _auth=Depends(require_admin)):
|
| 73 |
+
try:
|
| 74 |
+
get_memory_instance().delete_all(**{TYPE_TO_FIELD[entity_type]: entity_id})
|
| 75 |
+
except Exception:
|
| 76 |
+
raise upstream_error()
|
| 77 |
+
return MessageResponse(message="Entity deleted")
|
server/routers/requests.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
from auth import require_admin
|
| 5 |
+
from db import get_db
|
| 6 |
+
from fastapi import APIRouter, Depends, Query
|
| 7 |
+
from models import RequestLog
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
from sqlalchemy import select
|
| 10 |
+
from sqlalchemy.orm import Session
|
| 11 |
+
|
| 12 |
+
router = APIRouter(prefix="/requests", tags=["requests"])
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class RequestLogItem(BaseModel):
|
| 16 |
+
id: uuid.UUID
|
| 17 |
+
method: str
|
| 18 |
+
path: str
|
| 19 |
+
status_code: int
|
| 20 |
+
latency_ms: float
|
| 21 |
+
auth_type: str
|
| 22 |
+
created_at: datetime
|
| 23 |
+
|
| 24 |
+
model_config = {"from_attributes": True}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
API_KEY_AUTH_TYPES = ("api_key", "admin_api_key")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@router.get("", response_model=list[RequestLogItem])
|
| 31 |
+
def list_requests(
|
| 32 |
+
_auth=Depends(require_admin),
|
| 33 |
+
db: Session = Depends(get_db),
|
| 34 |
+
limit: int = Query(default=50, ge=1, le=200),
|
| 35 |
+
):
|
| 36 |
+
logs = (
|
| 37 |
+
db.execute(
|
| 38 |
+
select(RequestLog)
|
| 39 |
+
.where(RequestLog.auth_type.in_(API_KEY_AUTH_TYPES))
|
| 40 |
+
.order_by(RequestLog.created_at.desc())
|
| 41 |
+
.limit(limit)
|
| 42 |
+
)
|
| 43 |
+
.scalars()
|
| 44 |
+
.all()
|
| 45 |
+
)
|
| 46 |
+
return logs
|
server/schemas.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class MessageResponse(BaseModel):
|
| 5 |
+
message: str
|
server/server_state.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import threading
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
from typing import Any, Callable, Dict
|
| 6 |
+
|
| 7 |
+
from mem0 import Memory
|
| 8 |
+
|
| 9 |
+
_state_lock = threading.RLock()
|
| 10 |
+
_current_config: Dict[str, Any] = {}
|
| 11 |
+
_memory_instance: Memory | None = None
|
| 12 |
+
_session_factory: Callable | None = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def set_session_factory(factory: Callable) -> None:
|
| 16 |
+
global _session_factory
|
| 17 |
+
_session_factory = factory
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _load_overrides() -> Dict[str, Any]:
|
| 21 |
+
try:
|
| 22 |
+
if _session_factory is None:
|
| 23 |
+
return {}
|
| 24 |
+
from models import Settings
|
| 25 |
+
|
| 26 |
+
session = _session_factory()
|
| 27 |
+
try:
|
| 28 |
+
row = session.get(Settings, "config_overrides")
|
| 29 |
+
if row is None:
|
| 30 |
+
return {}
|
| 31 |
+
return json.loads(row.value)
|
| 32 |
+
finally:
|
| 33 |
+
session.close()
|
| 34 |
+
except Exception:
|
| 35 |
+
return {}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _save_overrides(overrides: Dict[str, Any]) -> None:
|
| 39 |
+
try:
|
| 40 |
+
if _session_factory is None:
|
| 41 |
+
return
|
| 42 |
+
from models import Settings
|
| 43 |
+
from sqlalchemy.dialects.postgresql import insert
|
| 44 |
+
|
| 45 |
+
session = _session_factory()
|
| 46 |
+
try:
|
| 47 |
+
serialized = json.dumps(overrides)
|
| 48 |
+
stmt = (
|
| 49 |
+
insert(Settings)
|
| 50 |
+
.values(key="config_overrides", value=serialized)
|
| 51 |
+
.on_conflict_do_update(index_elements=[Settings.key], set_={"value": serialized})
|
| 52 |
+
)
|
| 53 |
+
session.execute(stmt)
|
| 54 |
+
session.commit()
|
| 55 |
+
finally:
|
| 56 |
+
session.close()
|
| 57 |
+
except Exception:
|
| 58 |
+
logging.warning("Failed to persist config overrides to database", exc_info=True)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _merge_config(base: Dict[str, Any], updates: Dict[str, Any]) -> Dict[str, Any]:
|
| 62 |
+
merged = deepcopy(base)
|
| 63 |
+
|
| 64 |
+
for key, value in updates.items():
|
| 65 |
+
if isinstance(value, dict) and isinstance(merged.get(key), dict):
|
| 66 |
+
merged[key] = _merge_config(merged[key], value)
|
| 67 |
+
else:
|
| 68 |
+
merged[key] = value
|
| 69 |
+
|
| 70 |
+
return merged
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def initialize_state(default_config: Dict[str, Any]) -> None:
|
| 74 |
+
global _current_config, _memory_instance
|
| 75 |
+
with _state_lock:
|
| 76 |
+
_current_config = deepcopy(default_config)
|
| 77 |
+
overrides = _load_overrides()
|
| 78 |
+
if overrides:
|
| 79 |
+
_current_config = _merge_config(_current_config, overrides)
|
| 80 |
+
_memory_instance = Memory.from_config(_current_config)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def update_config(updates: Dict[str, Any]) -> Dict[str, Any]:
|
| 84 |
+
global _current_config, _memory_instance
|
| 85 |
+
with _state_lock:
|
| 86 |
+
next_config = _merge_config(_current_config, updates)
|
| 87 |
+
_current_config = next_config
|
| 88 |
+
_memory_instance = Memory.from_config(next_config)
|
| 89 |
+
overrides = _load_overrides()
|
| 90 |
+
overrides = _merge_config(overrides, updates)
|
| 91 |
+
_save_overrides(overrides)
|
| 92 |
+
return deepcopy(_current_config)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def get_current_config() -> Dict[str, Any]:
|
| 96 |
+
with _state_lock:
|
| 97 |
+
return deepcopy(_current_config)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def get_memory_instance() -> Memory:
|
| 101 |
+
with _state_lock:
|
| 102 |
+
if _memory_instance is None:
|
| 103 |
+
raise RuntimeError("Mem0 runtime has not been initialized.")
|
| 104 |
+
return _memory_instance
|
server/telemetry.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Anonymous telemetry. Sends at most two events per install:
|
| 2 |
+
|
| 3 |
+
- `admin_registered` — fires when the first admin account is created (wizard or API).
|
| 4 |
+
- `onboarding_completed` — fires when the setup wizard reaches its final success state
|
| 5 |
+
(so dashboard installs emit both; API-only installs emit only the first).
|
| 6 |
+
|
| 7 |
+
Enabled by default (matching the mem0 OSS library). Opt out with `MEM0_TELEMETRY=false`.
|
| 8 |
+
Fires to the same PostHog project the library uses. Shared properties: email domain,
|
| 9 |
+
server version, and a randomly generated install UUID.
|
| 10 |
+
`onboarding_completed` also carries the operator's freeform use-case string.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import logging
|
| 15 |
+
import os
|
| 16 |
+
import uuid
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from threading import Lock
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import mem0
|
| 23 |
+
|
| 24 |
+
PROJECT_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
|
| 25 |
+
HOST = "https://us.i.posthog.com"
|
| 26 |
+
|
| 27 |
+
ENABLED = os.environ.get("MEM0_TELEMETRY", "true").lower() not in {"0", "false", "no", "off"}
|
| 28 |
+
STATE_PATH = Path(os.environ.get("MEM0_TELEMETRY_STATE_PATH", "/opt/data/history/telemetry.json"))
|
| 29 |
+
|
| 30 |
+
_lock = Lock()
|
| 31 |
+
_client: Any = None
|
| 32 |
+
_dashboard_nudge_logged = False
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _load_state() -> dict[str, Any]:
|
| 36 |
+
if not STATE_PATH.exists():
|
| 37 |
+
return {}
|
| 38 |
+
try:
|
| 39 |
+
return json.loads(STATE_PATH.read_text())
|
| 40 |
+
except (OSError, json.JSONDecodeError):
|
| 41 |
+
return {}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _save_state(state: dict[str, Any]) -> None:
|
| 45 |
+
try:
|
| 46 |
+
STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 47 |
+
STATE_PATH.write_text(json.dumps(state))
|
| 48 |
+
except OSError:
|
| 49 |
+
logging.exception("telemetry: failed to persist state")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _install_id(state: dict[str, Any]) -> str:
|
| 53 |
+
install_id = state.get("install_id")
|
| 54 |
+
if not install_id:
|
| 55 |
+
install_id = str(uuid.uuid4())
|
| 56 |
+
state["install_id"] = install_id
|
| 57 |
+
_save_state(state)
|
| 58 |
+
return install_id
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _get_client():
|
| 62 |
+
global _client
|
| 63 |
+
if _client is not None:
|
| 64 |
+
return _client
|
| 65 |
+
try:
|
| 66 |
+
from posthog import Posthog
|
| 67 |
+
except ImportError:
|
| 68 |
+
logging.warning("telemetry: posthog package not installed; disabling")
|
| 69 |
+
return None
|
| 70 |
+
_client = Posthog(project_api_key=PROJECT_API_KEY, host=HOST, disable_geoip=True)
|
| 71 |
+
return _client
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def log_status() -> None:
|
| 75 |
+
if ENABLED:
|
| 76 |
+
logging.info("telemetry: anonymous telemetry is enabled. Set MEM0_TELEMETRY=false to disable.")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _capture_once(email: str, event: str, state_key: str, extra: dict[str, Any] | None = None) -> None:
|
| 80 |
+
if not ENABLED:
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
with _lock:
|
| 84 |
+
state = _load_state()
|
| 85 |
+
if state.get(state_key):
|
| 86 |
+
return
|
| 87 |
+
|
| 88 |
+
client = _get_client()
|
| 89 |
+
if client is None:
|
| 90 |
+
return
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
client.capture(
|
| 94 |
+
distinct_id=_install_id(state),
|
| 95 |
+
event=event,
|
| 96 |
+
properties={
|
| 97 |
+
"email_domain": email.rsplit("@", 1)[-1].lower() if "@" in email else "unknown",
|
| 98 |
+
"server_version": mem0.__version__,
|
| 99 |
+
**(extra or {}),
|
| 100 |
+
},
|
| 101 |
+
)
|
| 102 |
+
state[state_key] = datetime.now(timezone.utc).isoformat()
|
| 103 |
+
_save_state(state)
|
| 104 |
+
except Exception:
|
| 105 |
+
logging.exception("telemetry: failed to send %s event", event)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def capture_admin_registered(email: str) -> None:
|
| 109 |
+
_capture_once(email, "admin_registered", "admin_registered_sent_at")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def capture_onboarding_completed(email: str, use_case: str) -> None:
|
| 113 |
+
_capture_once(email, "onboarding_completed", "onboarding_sent_at", {"use_case": use_case})
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def log_dashboard_nudge_once(dashboard_url: str) -> None:
|
| 117 |
+
"""Log a hint pointing the operator to the web dashboard the first time a memory
|
| 118 |
+
is stored. Fires at most once per process (so a restart may re-log it on the next
|
| 119 |
+
add — harmless for a discovery nudge). LOCAL console log only — sends nothing
|
| 120 |
+
off-box, so it is intentionally NOT gated by MEM0_TELEMETRY.
|
| 121 |
+
"""
|
| 122 |
+
global _dashboard_nudge_logged
|
| 123 |
+
if _dashboard_nudge_logged:
|
| 124 |
+
return
|
| 125 |
+
_dashboard_nudge_logged = True
|
| 126 |
+
logging.info(
|
| 127 |
+
"First memory stored. Open the dashboard at %s to view and manage your memories.",
|
| 128 |
+
dashboard_url,
|
| 129 |
+
)
|
supervisord.conf
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[supervisord]
|
| 2 |
+
nodaemon=true
|
| 3 |
+
user=mem0
|
| 4 |
+
logfile=/var/log/supervisor/supervisord.log
|
| 5 |
+
logfile_maxbytes=50MB
|
| 6 |
+
logfile_backups=10
|
| 7 |
+
loglevel=info
|
| 8 |
+
pidfile=/var/log/supervisor/supervisord.pid
|
| 9 |
+
childlogdir=/var/log/supervisor
|
| 10 |
+
|
| 11 |
+
[program:postgresql]
|
| 12 |
+
command=/usr/lib/postgresql/15/bin/postgres -D /opt/data/pgdata -c config_file=/opt/data/pgdata/postgresql.conf
|
| 13 |
+
user=mem0
|
| 14 |
+
autostart=true
|
| 15 |
+
autorestart=true
|
| 16 |
+
startsecs=10
|
| 17 |
+
startretries=3
|
| 18 |
+
stdout_logfile=/var/log/supervisor/postgresql.log
|
| 19 |
+
stdout_logfile_maxbytes=10MB
|
| 20 |
+
stdout_logfile_backups=5
|
| 21 |
+
stderr_logfile=/var/log/supervisor/postgresql.err.log
|
| 22 |
+
stderr_logfile_maxbytes=10MB
|
| 23 |
+
stderr_logfile_backups=5
|
| 24 |
+
environment=PGDATA="/opt/data/pgdata",PGPORT="5432"
|
| 25 |
+
|
| 26 |
+
[program:mem0-api]
|
| 27 |
+
command=/usr/local/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 1
|
| 28 |
+
directory=/opt/mem0/api
|
| 29 |
+
user=mem0
|
| 30 |
+
autostart=true
|
| 31 |
+
autorestart=true
|
| 32 |
+
startsecs=15
|
| 33 |
+
startretries=3
|
| 34 |
+
stdout_logfile=/var/log/supervisor/mem0-api.log
|
| 35 |
+
stdout_logfile_maxbytes=10MB
|
| 36 |
+
stdout_logfile_backups=5
|
| 37 |
+
stderr_logfile=/var/log/supervisor/mem0-api.err.log
|
| 38 |
+
stderr_logfile_maxbytes=10MB
|
| 39 |
+
stderr_logfile_backups=5
|
| 40 |
+
environment=PYTHONPATH="/opt/mem0/api",PYTHONUNBUFFERED="1"
|
| 41 |
+
depends_on=postgresql
|
| 42 |
+
|
| 43 |
+
[program:mem0-dashboard]
|
| 44 |
+
command=/app/entrypoint.sh node server.js
|
| 45 |
+
directory=/app
|
| 46 |
+
user=mem0
|
| 47 |
+
autostart=true
|
| 48 |
+
autorestart=true
|
| 49 |
+
startsecs=10
|
| 50 |
+
startretries=3
|
| 51 |
+
stdout_logfile=/var/log/supervisor/mem0-dashboard.log
|
| 52 |
+
stdout_logfile_maxbytes=10MB
|
| 53 |
+
stdout_logfile_backups=5
|
| 54 |
+
stderr_logfile=/var/log/supervisor/mem0-dashboard.err.log
|
| 55 |
+
stderr_logfile_maxbytes=10MB
|
| 56 |
+
stderr_logfile_backups=5
|
| 57 |
+
environment=NODE_ENV="production",PORT="3000",HOSTNAME="0.0.0.0",NEXT_PUBLIC_API_URL="http://localhost:7860/api",NEXT_PUBLIC_INSTANCE_NAME="Mem0"
|
| 58 |
+
depends_on=mem0-api
|
| 59 |
+
|
| 60 |
+
[program:nginx]
|
| 61 |
+
command=/usr/sbin/nginx -g "daemon off;"
|
| 62 |
+
user=mem0
|
| 63 |
+
autostart=true
|
| 64 |
+
autorestart=true
|
| 65 |
+
startsecs=5
|
| 66 |
+
startretries=3
|
| 67 |
+
stdout_logfile=/var/log/supervisor/nginx.log
|
| 68 |
+
stdout_logfile_maxbytes=10MB
|
| 69 |
+
stdout_logfile_backups=5
|
| 70 |
+
stderr_logfile=/var/log/supervisor/nginx.err.log
|
| 71 |
+
stderr_logfile_maxbytes=10MB
|
| 72 |
+
stderr_logfile_backups=5
|
| 73 |
+
depends_on=mem0-api,mem0-dashboard
|