commit 9b3dd46ab40972e78036191838b3a8fbd61e0786 Author: reform Date: Fri Oct 23 20:04:00 2026 +0300 recovered snapshot from suspended aaronjaworski710 (history unavailable) diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e0fdd9f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,66 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +*.egg-info/ +dist/ +build/ + +# Virtual Environment +.venv/ +venv/ +ENV/ +env/ + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# Environment & Secrets +.env +.env.* +accounts.json + +# Data & Database +data/ +*.db +*.db-shm +*.db-wal + +# Logs +logs/ +*.log + +# Git +.git/ +.gitignore + +# Documentation +docs/ +*.md + +# Testing +.pytest_cache/ +.coverage +htmlcov/ + +# Deployment configs (already in container context) +Dockerfile +docker-compose.yml +.dockerignore + +# Scripts (not needed in container) +scripts/ + +# Debug data +response/ +AI-note/ + +# OS +.DS_Store +Thumbs.db diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..af222a0 --- /dev/null +++ b/.env.example @@ -0,0 +1,11 @@ +NOTION_ACCOUNTS= +API_KEY= +HOST= +ALLOWED_ORIGINS= +PORT= +APP_MODE= +HOST_PORT= +DB_PATH= +SILICONFLOW_API_KEY= +LOG_LEVEL= +TZ= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bd9e4ac --- /dev/null +++ b/.gitignore @@ -0,0 +1,76 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +*.egg-info/ +dist/ +build/ +.venv/ +venv/ + +# Environment variables (SECURITY RISK) +.env +.env.* +accounts.json + +# Data & Database +data/ +*.db +*.db-shm +*.db-wal + +# Logs +logs/ +*.log + +# IDEs +.vscode/ +.idea/ +*.swp +.DS_Store + +# AI Development Notes & Tools (SECURITY: Do not commit internal notes) +AI-note/ +GEMINI.md +CODEX.md +CLAUDE.md +ref/ +*.md.bak +docs/PR_REVIEW_23_24_16.md + +# Backup and temporary files +*.bak +*backup* +*.backup +*-backup.* +debug_*.log +tmp_*.log +*.tmp +*.old + +# Test files (all tests directory) +tests/ +test_*.py +*_test.py +debug_*.py + +# Claude Code local settings +.claude/settings.local.json + +# Docker (Optional to ignore if you want to keep configs in git, usually we keep them) +# But we definitely ignore local-specific overrides +docker-compose.override.yml + +# Local cleanup folder +0311_cleanup/ + + +# Response debug data (contains sensitive tokens) +response/ + +data/ +*.log +farm_accounts.jsonl +state_*.json diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..13db3c1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +# Python 3.11 slim как база +FROM python:3.11-slim + +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 TZ=Europe/Moscow + +RUN apt-get update && apt-get install -y --no-install-recommends tzdata && rm -rf /var/lib/apt/lists/* && groupadd -r appuser && useradd -r -g appuser appuser + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . +RUN mkdir -p /app/data && chown -R appuser:appuser /app +USER appuser + +EXPOSE 8000 +CMD ["uvicorn", "app.server:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..4d9b7fe --- /dev/null +++ b/README.md @@ -0,0 +1,124 @@ +# Notion2API-RU + +> Notion AI → OpenAI-совместимый API + авторег аккаунтов + +Реверс веб-интерфейса Notion AI, обёрнутый в стандартный `/v1/chat/completions`. Работает с Cherry Studio, Zotero, LobeChat и любым OpenAI-совместимым клиентом. + +**Главная фишка этой сборки — встроенный авторег:** не нужно руками регистрировать аккаунты и дёргать токены из F12. `tools/farm.py` сам регистрирует новые аккаунты Notion через временные почты (voidash/mail.tm), проходит онбординг, выбирает модель и складывает готовые креды в пул. + +## Возможности + +- **OpenAI-совместимость** — `/v1/chat/completions`, стриминг (SSE) и обычные ответы +- **23 модели** — Claude (включая Opus 5), GPT-6 Astra, GPT-5.x, Gemini, Kimi, Grok, DeepSeek, GLM, Fable +- **Панель Thinking** — показывает рассуждения модели +- **Панель Search** — поисковые запросы и источники +- **Пул аккаунтов** — Round-Robin балансировка, cooldown при сбоях +- **Авторег** — ферма аккаунтов через временные почты, без капчи +- **Web UI** — встроенная панель, тёмная тема, анимации +- **Docker** — деплой одной командой + +## Быстрый старт + +### Вариант 1 — Авторег (рекомендую) + +```bash +# ставим зависимости +pip install -r requirements.txt +pip install playwright httpx +playwright install chromium + +# регистрируем 5 аккаунтов с Opus 5.5 +python tools/farm.py 5 Opus +``` + +Ферма сама: +1. Создаёт временный ящик (voidash.bond или mail.tm) +2. Регистрирует аккаунт Notion, ловит код подтверждения из письма +3. Проходит онбординг (без карты, триал не нужен — модели доступны сразу) +4. Заходит в AI-чат, выбирает модель (Opus 5.5 / GPT-6.1 Sol / Kimi K3 / GPT-6 Luna) +5. Отправляет тестовое сообщение и проверяет ответ +6. Сохраняет креды в `farm_accounts.jsonl` + state-файл сессии + +```bash +# конвертируем пул фермы в accounts.json для сервера +python tools/farm.py --export +``` + +### Вариант 2 — Ручные креды + +```bash +python login.py # откроет браузер, ждёт логина, сам вытащит token_v2 и всё остальное +``` + +Или руками через F12: Application → Cookies → `token_v2`, потом скрипт `scripts/extract_notion_info.js` в консоли — он выдаст все поля для `accounts.json`. + +### Запуск сервера + +```bash +pip install -r requirements.txt +uvicorn app.server:app --host 0.0.0.0 --port 8000 +``` + +Или Docker: + +```bash +docker-compose build --no-cache && docker-compose up -d +``` + +## Использование API + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:8000/v1", api_key="any") + +r = client.chat.completions.create( + model="claude-opus5", + messages=[{"role": "user", "content": "Привет"}], + stream=True, +) +for chunk in r: + print(chunk.choices[0].delta.content or "", end="") +``` + +| Эндпоинт | Метод | Описание | +|---|---|---| +| `/v1/chat/completions` | POST | Основной | +| `/v1/models` | GET | Список моделей | +| `/health` | GET | Статус пула аккаунтов | +| `/` | GET | Web UI | + +## Режимы + +| | Lite | Standard | Heavy | +|---|---|---|---| +| Память | нет | клиент | сервер | +| База | нет | нет | SQLite | +| Thinking/Search | нет | да | да | +| RPS | 30/мин | 25/мин | 20/мин | + +`APP_MODE=standard` в `.env` — рекомендуемый. + +## Модели + +`claude-opus5`, `claude-sonnet4.6`, `claude-sonnet5`, `gpt-6-astra`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gemini-3.1pro`, `kimi-2.7`, `grok-4.3`, `deepseek-v4pro`, `glm-5.2`, `fable-5` и другие. Полный список: `GET /v1/models`. + +## Переменные окружения + +| Переменная | Описание | По умолчанию | +|---|---|---| +| `NOTION_ACCOUNTS` | JSON-массив кредов Notion | обязателен | +| `APP_MODE` | `lite` / `standard` / `heavy` | `heavy` | +| `API_KEY` | Bearer для клиентов | нет | +| `PORT` | Порт | 8000 | +| `SILICONFLOW_API_KEY` | Для сжатия контекста в Heavy | нет | + +## Заметки + +- Лимиты Notion: 5-часовой квоты тратятся быстро, месячной — медленно. Пул аккаунтов распределяет нагрузку. +- При 429 — добавить аккаунтов (`python tools/farm.py 5`). +- Ключи и `accounts.json` в `.gitignore` — не коммитить. + +## Лицензия + +MIT diff --git a/README_EG.md b/README_EG.md new file mode 100644 index 0000000..3d15c1b --- /dev/null +++ b/README_EG.md @@ -0,0 +1,309 @@ +# Notion2API + +> Notion AI → OpenAI-Compatible API + +🌐 English | [中文](./README.md) + +Notion2API reverse-engineers the Notion AI web interface and exposes it as a standard `/v1/chat/completions` endpoint, making it directly usable with Cherry Studio, Zotero, and any other OpenAI-compatible client. + +--- + +## Features + +- **OpenAI Compatible** — Standard `/v1/chat/completions` endpoint, streaming (SSE) and non-streaming +- **Three Operation Modes** — Lite / Standard / Heavy to fit different use cases +- **23 AI Models** — Claude (incl. Opus 5), GPT-6 Astra, GPT-5.x, Gemini, Kimi, Grok, DeepSeek, GLM, Fable +- **Thinking Panel** — Reasoning process display for all models +- **Search Panel** — Web search queries and source links +- **Multi-Account Pool** — Round-Robin load balancing with cooldown failover +- **Built-in Web UI** — Minimalist design, ambient animations, dark mode +- **Docker Ready** — One-command deployment + +--- + +## Mode Comparison + +| Feature | Lite | Standard | Heavy | +|---------|------|----------|-------| +| **Memory** | ❌ None | ✅ Client-managed | ✅ Server-managed | +| **Database** | ❌ | ❌ | ✅ SQLite | +| **Thinking Panel** | ❌ | ✅ | ✅ | +| **Search Panel** | ❌ | ✅ | ✅ | +| **Rate Limit** | 30/min | 25/min | 20/min | +| **Use Case** | Simple Q&A | Short–mid conversations | Long-term conversations | + +> **Recommended**: `standard` — full context, no database required. +> Switch by setting `APP_MODE` in `.env`. + +--- + +## Quick Start + +### 1. Get Notion Credentials + +Choose the method that fits your situation: + +#### Method A — F12 (if you already have a Notion web session) + +1. Open https://www.notion.so/ai and log in +2. Press `F12` → **Application** tab → **Storage → Cookies → https://www.notion.so** +3. Find `token_v2` and copy its Value +4. Switch to the **Console** tab, paste and run `scripts/extract_notion_info.js` +5. The script outputs all required fields — paste the result into `accounts.json` + +#### Method B — Browser-Assisted Login (no existing web session needed) + +```bash +python login.py +``` + +This launches a temporary Chrome/Edge window, waits for you to sign in to Notion, then automatically extracts all credentials and writes them to `accounts.json` and `.env`. + +```bash +python login.py --check # verify a saved profile +python login.py --list # list all saved profiles +python login.py --manual # paste token_v2 manually if Chrome is unavailable +python login.py --profile work # save under a named profile +``` + +Both methods write to `accounts.json`. Multiple accounts are supported — add more entries to the array to enable load balancing. + +> ⚠️ `accounts.json` and `.env` contain credentials. Both are git-ignored — keep them private. + +--- + +### 2. Configure `.env` + +```bash +cp .env.example .env +``` + +At minimum, set: + +```env +APP_MODE=standard # lite / standard / heavy +``` + +If using **Heavy mode**, also add: + +```env +SILICONFLOW_API_KEY=your_key_here +``` + +> Heavy mode uses SiliconFlow's LLM to compress long conversations. Register free at https://siliconflow.cn. + +--- + +### 3. Start the Service + +#### Docker (Recommended) + +```bash +docker-compose build --no-cache && docker-compose up -d +``` + +`accounts.json` is mounted as a volume — update accounts without rebuilding: + +```bash +# After editing accounts.json: +docker-compose restart +``` + +#### Local Run + +```bash +pip install -r requirements.txt +uvicorn app.server:app --host 0.0.0.0 --port 8000 +``` + +Access the Web UI at `http://localhost:8000`. + +--- + +## Supported Models + +| Model Name | Description | +|---|---| +| `claude-sonnet4.6` | Best balance of speed and quality — **most recommended** | +| `claude-sonnet5` | Sonnet 5 | +| `claude-opus4.6` | Stronger reasoning, use sparingly | +| `claude-opus4.7` | Stronger reasoning | +| `claude-opus4.8` | Strong reasoning Claude | +| `claude-opus5` | Newest Claude Opus, strongest reasoning | +| `claude-haiku4.5` | Haiku 4.5 | +| `gpt-6-astra` | GPT-6 Astra | +| `gpt-5.6-sol` | GPT-5.6 Sol | +| `gpt-5.6-terra` | GPT-5.6 Terra | +| `gpt-5.6-luna` | GPT-5.6 Luna | +| `gpt-5.5` | GPT-5.5 | +| `gpt-5.4` | OpenAI model | +| `gemini-3.5flash` | Gemini 3.5 Flash | +| `gemini-3.1pro` | Google's strongest reasoning model | +| `gemini-3flash` | Gemini 3 Flash | +| `kimi-2.7` | Kimi K2.7 Code | +| `grok-4.3` | xAI Grok 4.3 | +| `spacexai-4.5` | SpaceXAI 4.5 | +| `grok-build0.1` | xAI Grok Build 0.1 | +| `deepseek-v4pro` | DeepSeek V4 Pro | +| `glm-5.2` | GLM 5.2 | +| `fable-5` | Fable 5 | + +Full list via API: `GET http://localhost:8000/v1/models` + +To add or sync a Notion AI model, see [`docs/ADD_MODEL.md`](./docs/ADD_MODEL.md) (checklist of files to update — no need to search the whole repo). + +--- + +## API Usage + +This project accepts any string as the API key (no format requirement). + +### Python Example + +```python +from openai import OpenAI + +client = OpenAI( + base_url="http://localhost:8000/v1", + api_key="any-string" +) + +response = client.chat.completions.create( + model="claude-sonnet4.6", + messages=[{"role": "user", "content": "Hello"}], + stream=True +) + +for chunk in response: + print(chunk.choices[0].delta.content or "", end="") +``` + +### Endpoints + +| Endpoint | Method | Description | +|---|---|---| +| `/v1/chat/completions` | POST | Chat completions (core) | +| `/v1/models` | GET | List available models | +| `/health` | GET | Health check (account pool status, uptime) | +| `/` | GET | Built-in Web UI | + +--- + +## Web UI + +Access `http://localhost:8000` for the built-in **Notion AI Studio** interface: + +- **Conversation Management** — Create, rename, delete, star/bookmark +- **Model Selector** — Grouped by provider (Anthropic / OpenAI / Google / Moonshot / xAI / DeepSeek) +- **Thinking Panel** — Collapsible reasoning display with elapsed timer +- **Search Panel** — Collapsible web search queries and source links +- **Ambient Animations** — Weather effects: default / snow / rain / sunny / night +- **Theme** — Light / dark mode toggle +- **Responsive** — Mobile-friendly sidebar + +> Thinking and Search panels require `standard` or `heavy` mode. + +--- + +## Environment Variables + +| Variable | Description | Default | +|---|---|---| +| `NOTION_ACCOUNTS` | Notion credentials JSON array | **Required** | +| `APP_MODE` | `lite` / `standard` / `heavy` | `heavy` | +| `API_KEY` | Bearer token for client auth | *(none)* | +| `DB_PATH` | SQLite database path | `./data/conversations.db` | +| `HOST` | Bind address | `0.0.0.0` | +| `PORT` | Service port | `8000` | +| `HOST_PORT` | Docker host port | `8000` | +| `ALLOWED_ORIGINS` | CORS allowed origins | `*` | +| `SILICONFLOW_API_KEY` | Required for Heavy mode compression | *(none)* | +| `DISABLE_RATE_LIMIT` | Disable per-IP rate limiting | `false` | +| `NOTION_CLIENT_VERSION` | Override Notion client version header | `23.13.20260228.0625` | +| `NOTION_URL` | Notion site base URL (mirror/proxy) | `https://www.notion.so` | +| `NOTION_DOMAIN` | Cookie domain for login.py | `www.notion.so` | +| `LOG_LEVEL` | Logging level | `INFO` | +| `TZ` | Timezone | `Asia/Shanghai` | + +--- + +## Docker Reference + +```bash +# Start +docker-compose up -d + +# View logs +docker-compose logs -f --tail=50 + +# Restart (e.g. after updating accounts.json) +docker-compose restart + +# Update code and redeploy +git pull && docker-compose down && docker-compose build --no-cache && docker-compose up -d + +# Stop +docker-compose down +``` + +### Nginx Reverse Proxy (optional) + +```nginx +location / { + proxy_pass http://127.0.0.1:8000; + proxy_set_header Host $host; + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; +} +``` + +--- + +## FAQ + +**Thinking panel not showing?** +Use `APP_MODE=standard` or `heavy`. Lite mode does not support Thinking or Search panels. + +**How do I switch modes?** +Edit `APP_MODE` in `.env`, then restart: `docker-compose restart` + +**How do I add multiple accounts?** +Edit `accounts.json` as an array — accounts are load-balanced automatically: +```json +[ + {"token_v2": "token1", "space_id": "...", "user_id": "...", "space_view_id": "...", "user_name": "...", "user_email": "..."}, + {"token_v2": "token2", "space_id": "...", "user_id": "...", "space_view_id": "...", "user_name": "...", "user_email": "..."} +] +``` + +**Getting 429 or Notion AI suspended?** +Notion may throttle workspaces with unusual request patterns. Adding multiple accounts helps distribute load. Business Trial workspaces are especially prone to this. + +**Token expired?** +Re-run `python login.py` or repeat the F12 steps to refresh credentials. + +--- + +## Compatibility + +> Due to Notion's own AI latency, expect ~3 seconds from request to first token. + +| Client | Status | Notes | +|---|---|---| +| Cherry Studio | ✅ Full support | Recommended | +| Zotero Translation | ✅ Full support | Slightly slow; sonnet model most accurate | +| Immersive Translate | ⚠️ Not recommended | High latency | +| Claude Code | ❌ Not supported | Uses Anthropic native API format | + +--- + +## License + +MIT License + +--- + +If this project helps you, please give it a Star ⭐ + +*Built with assistance from Claude Code.* diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/account_pool.py b/app/account_pool.py new file mode 100644 index 0000000..354193c --- /dev/null +++ b/app/account_pool.py @@ -0,0 +1,114 @@ +import time +import threading +from typing import Dict, List + +from app.logger import logger +from app.notion_client import NotionOpusAPI + +class AccountPool: + def __init__(self, accounts: List[dict]): + """ + 从配置列表初始化,每个 dict 对应一组凭据。 + 同时初始化客户端实例和它们的状态。 + """ + if not accounts: + raise ValueError("账号池初始化失败:未提供任何账号配置。") + + self.clients = [NotionOpusAPI(acc) for acc in accounts] + # 记录每个客户端的冷却释放时间戳(0 表示可用) + self.cooldown_until = [0.0 for _ in self.clients] + + # 轮询索引 + self._current_index = 0 + self._lock = threading.Lock() + + def get_client(self, wait_if_cooling: bool = True) -> NotionOpusAPI: + """ + 轮询(Round-Robin)返回下一个可用客户端。 + 过滤掉正处于冷却期中的客户端。 + + 如果 wait_if_cooling=True(默认),当所有账号都在冷却时, + 会等待最近的冷却结束后返回,而不是抛异常。 + """ + now = time.time() + with self._lock: + start_index = self._current_index + + while True: + idx = self._current_index + # 如果过了冷却时间,视为可用 + if self.cooldown_until[idx] <= now: + # 轮询步进 + self._current_index = (self._current_index + 1) % len(self.clients) + return self.clients[idx] + + # 不可用则顺延 + self._current_index = (self._current_index + 1) % len(self.clients) + + # 如果转了一圈都没找到可用的 + if self._current_index == start_index: + next_available = min(self.cooldown_until) + wait_seconds = max(0.5, next_available - now) + + if wait_if_cooling and wait_seconds <= 15: + # 等待冷却结束后重新尝试 + logger.info( + f"All accounts cooling, waiting {wait_seconds:.1f}s", + extra={ + "request_info": { + "event": "account_pool_wait_cooling", + "wait_seconds": round(wait_seconds, 1), + } + }, + ) + # 释放锁再 sleep,避免阻塞其他线程 + self._lock.release() + try: + time.sleep(wait_seconds) + finally: + self._lock.acquire() + # 更新时间后重新扫描 + now = time.time() + continue + + raise RuntimeError( + f"所有账号冷却中,请在 {max(1, int(wait_seconds))} 秒后重试。" + ) + + def get_status_summary(self) -> Dict[str, int]: + """返回账号池简要状态,供健康检查和日志使用。""" + now = time.time() + with self._lock: + active = sum(1 for ts in self.cooldown_until if ts <= now) + cooling = len(self.cooldown_until) - active + return { + "total": len(self.clients), + "active": active, + "cooling": cooling, + } + + def mark_failed(self, client: NotionOpusAPI, cooldown_seconds: int = 3): + """ + 标记某个客户端为临时不可用(默认冷却 3 秒后恢复)。 + """ + with self._lock: + try: + idx = self.clients.index(client) + # 记录未来的冷却解封时间 + self.cooldown_until[idx] = time.time() + cooldown_seconds + logger.warning( + "Account marked as failed", + extra={ + "request_info": { + "event": "account_failed", + "account": client.account_key, + "space_id": client.space_id, + "cooldown_seconds": cooldown_seconds, + } + }, + ) + except ValueError: + logger.warning( + "Attempted to mark unknown account as failed", + extra={"request_info": {"event": "account_failed_unknown"}}, + ) diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/chat.py b/app/api/chat.py new file mode 100644 index 0000000..93e88b3 --- /dev/null +++ b/app/api/chat.py @@ -0,0 +1,1943 @@ +import asyncio +import json +import re +import time +import uuid +from difflib import SequenceMatcher +from typing import Any, Dict, Generator, Iterable, List, Tuple + +from fastapi import APIRouter, BackgroundTasks, HTTPException, Request, Response +from fastapi.responses import JSONResponse, StreamingResponse + +from app.config import is_lite_mode +from app.conversation import ( + build_lite_transcript, + compress_round_if_needed, + compress_sliding_window_round, +) +from app.logger import logger +from app.model_registry import is_supported_model, list_available_models +from app.notion_client import NotionUpstreamError +from app.schemas import ( + ChatCompletionRequest, + ChatCompletionResponse, + ChatMessage, + ChatMessageResponseChoice, +) + +router = APIRouter() + + +# ─── 结构化错误响应 ───────────────────────────────────────────── +def _classify_upstream_error(exc: NotionUpstreamError) -> dict[str, Any]: + """将 NotionUpstreamError 分类为结构化错误信息,前端可直接展示。""" + sc = exc.status_code + + if sc == 401: + return { + "code": "NOTION_401", + "type": "upstream_auth_error", + "message": "Notion 认证失败 (HTTP 401),token 可能已过期", + "suggestion": "请重新获取 token_v2 并更新配置", + } + if sc == 403: + return { + "code": "NOTION_403", + "type": "upstream_forbidden", + "message": "Notion 拒绝访问 (HTTP 403),可能被 Cloudflare 拦截或账号受限", + "suggestion": "检查服务器网络环境,或稍后重试", + } + if sc == 429: + return { + "code": "NOTION_429", + "type": "upstream_rate_limit", + "message": "Notion 请求频率过高 (HTTP 429)", + "suggestion": "等待几秒后重试,或配置多个账号分散请求", + } + if sc and sc >= 500: + return { + "code": f"NOTION_{sc}", + "type": "upstream_server_error", + "message": f"Notion 服务暂时不可用 (HTTP {sc})", + "suggestion": "Notion 服务端故障,请稍后重试", + } + if "timed out" in str(exc).lower(): + return { + "code": "NETWORK_TIMEOUT", + "type": "network_timeout", + "message": "连接 Notion 超时", + "suggestion": "检查服务器到 notion.so 的网络连通性", + } + if "failed" in str(exc).lower() and not sc: + return { + "code": "NETWORK_ERROR", + "type": "network_error", + "message": "无法连接 Notion 服务", + "suggestion": "检查服务器网络和 DNS 配置", + } + if "empty" in str(exc).lower(): + return { + "code": "NOTION_EMPTY", + "type": "upstream_empty_response", + "message": "Notion 返回了空内容", + "suggestion": "请重新发送消息", + } + # 兜底 + return { + "code": "UPSTREAM_UNKNOWN", + "type": "upstream_error", + "message": str(exc), + "suggestion": "请稍后重试", + } + + +def _build_error_response( + status_code: int, + *, + code: str, + message: str, + error_type: str = "server_error", + suggestion: str = "", + detail: str = "", +) -> JSONResponse: + """构建统一格式的错误 JSON 响应,前端可解析展示。""" + content: dict[str, Any] = { + "error": { + "message": message, + "type": error_type, + "code": code, + } + } + if suggestion: + content["error"]["suggestion"] = suggestion + if detail: + content["error"]["detail"] = detail + return JSONResponse(status_code=status_code, content=content) + + +def _upstream_error_response(exc: NotionUpstreamError) -> JSONResponse: + """将 NotionUpstreamError 转为统一的 503 JSON 响应。""" + info = _classify_upstream_error(exc) + return _build_error_response( + 503, + code=info["code"], + message=info["message"], + error_type=info["type"], + suggestion=info.get("suggestion", ""), + detail=exc.response_excerpt or "", + ) + + +RECALL_INTENT_KEYWORDS = [ + "之前", + "上次", + "以前", + "你还记得", + "我们之前", + "earlier", + "before", + "recall", + "remember", + "之前说过", + "历史记录", + "找一下", + "搜索记忆", +] + + +def _build_stream_chunk( + response_id: str, + model: str, + *, + content: str = "", + thinking: str = "", + role: str = "", + finish_reason=None, +) -> str: + delta: Dict[str, Any] = {} + if role: + delta["role"] = role + if content: + delta["content"] = content + if thinking: + delta["reasoning_content"] = thinking + + payload = { + "id": response_id, + "object": "chat.completion.chunk", + "created": int(time.time()), + "model": model, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}], + } + return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" + + +def _build_local_ui_chunk( + response_id: str, + model: str, + event_type: str, + **payload_fields: Any, +) -> str: + payload: Dict[str, Any] = { + "id": response_id, + "object": "chat.completion.chunk", + "created": int(time.time()), + "model": model, + "choices": [{"index": 0, "delta": {}, "finish_reason": None}], + "type": event_type, + } + payload.update(payload_fields) + return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" + + +def _format_search_results_md(search_data: dict[str, Any]) -> str: + """将搜索数据格式化为 Markdown 引用块,以便标准客户端显示。""" + lines = [] + queries = search_data.get("queries", []) + if queries: + lines.append(f"> 🔍 **已搜索:** {', '.join(queries)}") + + sources = search_data.get("sources", []) + if sources: + lines.append("> 🌐 **来源:**") + for i, src in enumerate(sources[:5], 1): # 最多显示5个来源,避免刷屏 + title = src.get("title") or src.get("url") or "未知来源" + url = src.get("url") + if url: + lines.append(f"> {i}. [{title}]({url})") + else: + lines.append(f"> {i}. {title}") + + if lines: + return "\n".join(lines) + "\n\n" + return "" + + +def _normalize_stream_item(item: Any) -> dict[str, Any]: + if isinstance(item, str): + return {"type": "content", "text": item} + + if isinstance(item, dict): + item_type = str(item.get("type", "") or "").lower() + if item_type == "content": + return {"type": "content", "text": str(item.get("text", "") or "")} + if item_type == "search": + payload = item.get("data") + return { + "type": "search", + "data": payload if isinstance(payload, dict) else {}, + } + if item_type == "thinking": + return {"type": "thinking", "text": str(item.get("text", "") or "")} + if item_type == "final_content": + return { + "type": "final_content", + "text": str(item.get("text", "") or ""), + "source_type": str(item.get("source_type", "") or ""), + "source_length": item.get("source_length"), + } + + return {"type": "unknown"} + + +def _iter_stream_items( + first_item: Any, stream_gen: Iterable[Any] +) -> Generator[Any, None, None]: + if first_item is not None: + yield first_item + for item in stream_gen: + yield item + + +def _compute_missing_suffix(current_text: str, final_text: str) -> str: + if not final_text: + return "" + if not current_text: + return final_text + if final_text.startswith(current_text): + return final_text[len(current_text) :] + return "" + + +def _select_best_final_reply( + streamed_text: str, + final_text: str, + final_source_type: str, +) -> tuple[str, str]: + streamed = streamed_text or "" + final = final_text or "" + streamed_stripped = streamed.strip() + final_stripped = final.strip() + source = (final_source_type or "").strip().lower() + + if not final_stripped: + return streamed, "streamed_only" + if not streamed_stripped: + return final, "final_only" + if final.startswith(streamed): + return final, "final_extends_streamed" + if streamed.startswith(final): + if source == "title" or len(final_stripped) <= max( + 32, int(len(streamed_stripped) * 0.35) + ): + return streamed, "streamed_beats_short_final" + return final, "final_prefix_of_streamed" + + # Diverged content: usually prefer richer non-title final content. + if source == "title" and len(final_stripped) < max( + 48, int(len(streamed_stripped) * 0.6) + ): + return streamed, "streamed_beats_title" + if len(final_stripped) >= max(48, int(len(streamed_stripped) * 0.6)): + return final, "final_diverged_preferred" + return streamed, "streamed_diverged_preferred" + + +def _normalize_overlap_text(text: str) -> str: + normalized = str(text or "").strip().lower() + if not normalized: + return "" + normalized = re.sub(r"```.*?```", " ", normalized, flags=re.DOTALL) + normalized = re.sub(r"\s+", "", normalized) + return normalized + + +def _trim_redundant_thinking( + thinking_text: str, final_reply: str +) -> tuple[str, str, float]: + thinking = str(thinking_text or "").strip() + final = str(final_reply or "").strip() + if not thinking or not final: + return thinking, "missing_text", 0.0 + + normalized_thinking = _normalize_overlap_text(thinking) + normalized_final = _normalize_overlap_text(final) + if not normalized_thinking or not normalized_final: + return thinking, "missing_normalized_text", 0.0 + + overlap_ratio = SequenceMatcher(None, normalized_thinking, normalized_final).ratio() + if normalized_thinking == normalized_final: + return "", "identical", overlap_ratio + + if thinking.endswith(final): + prefix = thinking[: -len(final)].rstrip() + if len(_normalize_overlap_text(prefix)) >= 10: + return prefix, "suffix_trimmed", overlap_ratio + return "", "suffix_cleared", overlap_ratio + + if overlap_ratio >= 0.92 and ( + normalized_thinking in normalized_final + or normalized_final in normalized_thinking + ): + return "", "high_overlap_cleared", overlap_ratio + + return thinking, "kept", overlap_ratio + + +def _build_thinking_replacement( + streamed_content_text: str, + thinking_text: str, + final_reply: str, + final_source_type: str, +) -> dict[str, Any] | None: + source = str(final_source_type or "").strip().lower() + + # Relax constraint: Allow replacement for more source types to fix Sonnet thinking leakage + # But still require minimal validation for non-inference sources + if source not in ("agent-inference", "text", "markdown-chat", ""): + # Only skip for clearly non-thinking source types + return None + + normalized_final = _normalize_overlap_text(final_reply) + normalized_streamed = _normalize_overlap_text(streamed_content_text) + + # Require at least some thinking content to process + if not _normalize_overlap_text(thinking_text): + return None + + # For non-agent-inference sources, be more conservative but still check for obvious duplication + if source != "agent-inference": + # Only process if there's clear overlap or thinking is redundant + if not normalized_final: + return None + + # Check for obvious duplication (thinking appears in final reply) + if thinking_text.strip() in final_reply or final_reply in thinking_text: + # Clear case of duplication - trim it + replacement, decision, overlap_ratio = _trim_redundant_thinking( + thinking_text, final_reply + ) + if replacement != str(thinking_text or "").strip(): + logger.debug( + "Non-agent-inference thinking replacement applied", + extra={ + "request_info": { + "event": "thinking_replacement_non_agent", + "source_type": source, + "overlap_ratio": round(overlap_ratio, 4), + "decision": f"{decision}_non_agent_inference", + } + }, + ) + return { + "thinking": replacement, + "decision": f"{decision}_non_agent_inference", + "overlap_ratio": round(overlap_ratio, 4), + "source_type": source, + } + return None + + # Original agent-inference logic continues + if not normalized_final: + return None + + # 只在几乎没有真实正文增量时做裁决,避免误伤复杂推理场景。 + if normalized_streamed and len(normalized_streamed) >= max( + 10, int(len(normalized_final) * 0.35) + ): + return None + + replacement, decision, overlap_ratio = _trim_redundant_thinking( + thinking_text, final_reply + ) + if replacement == str(thinking_text or "").strip(): + return None + + return { + "thinking": replacement, + "decision": decision, + "overlap_ratio": round(overlap_ratio, 4), + "source_type": source, + } + + +def _contains_recall_intent(text: str) -> bool: + lowered = text.lower() + for keyword in RECALL_INTENT_KEYWORDS: + if keyword.isascii(): + if keyword.lower() in lowered: + return True + continue + if keyword in text: + return True + return False + + +def _extract_recall_query(text: str) -> str: + cleaned = text + for keyword in RECALL_INTENT_KEYWORDS: + if keyword.isascii(): + cleaned = re.sub( + rf"\b{re.escape(keyword)}\b", " ", cleaned, flags=re.IGNORECASE + ) + else: + cleaned = cleaned.replace(keyword, " ") + cleaned = re.sub(r"[\s,。!?、,.!?;::]+", " ", cleaned).strip() + return cleaned or text.strip() + + +def _prepare_messages( + req_body: ChatCompletionRequest, +) -> Tuple[str, List[Tuple[str, str, str]], str]: + system_messages = [] + dialogue_messages = [] + + for msg in req_body.messages: + if msg.role == "system": + if msg.content.strip(): + system_messages.append(msg.content.strip()) + continue + dialogue_messages.append((msg.role, msg.content, msg.thinking or "")) + + if not dialogue_messages: + raise HTTPException( + status_code=400, + detail="The messages list must contain at least one user message.", + ) + + last_role, user_prompt, _ = dialogue_messages[-1] + raw_user_prompt = user_prompt + history_messages = dialogue_messages[:-1] + + if last_role != "user": + raise HTTPException( + status_code=400, detail="The last message must be from role 'user'." + ) + if not user_prompt.strip(): + raise HTTPException( + status_code=400, detail="The last user message cannot be empty." + ) + + if system_messages: + from app.conversation import reframe_system_prompt_for_notion + + merged_system_prompt = "\n".join(system_messages) + reframed = reframe_system_prompt_for_notion(merged_system_prompt) + if reframed: + user_prompt = f"{reframed}\n\n{user_prompt}" + + return user_prompt, history_messages, raw_user_prompt + + +def _prepare_messages_lite(req_body: ChatCompletionRequest) -> str: + """Lite 模式:只提取最后一条 user 消息,支持 system 指令合并""" + system_messages = [] + user_prompt = "" + + for msg in req_body.messages: + if msg.role == "system" and msg.content.strip(): + system_messages.append(msg.content.strip()) + elif msg.role == "user": + user_prompt = msg.content + + if not user_prompt.strip(): + raise HTTPException( + status_code=400, + detail="The messages list must contain at least one user message.", + ) + + if system_messages: + from app.conversation import reframe_system_prompt_for_notion + + reframed = reframe_system_prompt_for_notion(" ".join(system_messages)) + if reframed: + user_prompt = f"{reframed}\n\n{user_prompt}" + + return user_prompt + + +def _create_lite_stream_generator( + response_id: str, + model_name: str, + first_item: Any, + stream_gen: Iterable[Any], +) -> Generator[str, None, None]: + """Lite 模式流式生成器:只输出 content,忽略 thinking 和 search""" + streamed_content_accumulator = "" + authoritative_final_content = "" + authoritative_final_source_type = "" + assistant_started = False + + try: + for raw_item in _iter_stream_items(first_item, stream_gen): + item = _normalize_stream_item(raw_item) + item_type = item.get("type") + + if item_type == "final_content": + final_text = str(item.get("text", "") or "").strip() + if final_text: + authoritative_final_content = final_text + authoritative_final_source_type = str( + item.get("source_type", "") or "" + ) + continue + + # Lite 模式忽略 thinking 和 search + if item_type in ("thinking", "search"): + continue + + if item_type != "content": + continue + + chunk_text = item.get("text", "") + if not chunk_text: + continue + + streamed_content_accumulator += chunk_text + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=chunk_text, + ) + else: + yield _build_stream_chunk(response_id, model_name, content=chunk_text) + except asyncio.CancelledError: + logger.info( + "Lite streaming cancelled by client", + extra={"request_info": {"event": "lite_stream_cancelled"}}, + ) + raise + except BaseException as exc: + if _is_client_disconnect_error(exc): + logger.info( + "Lite streaming connection closed by client", + extra={"request_info": {"event": "lite_stream_client_disconnected"}}, + ) + return + logger.error( + "Lite streaming interrupted", + exc_info=True, + extra={"request_info": {"event": "lite_stream_interrupted"}}, + ) + error_hint = "\n\n[上游连接中断,请稍后重试。]" + streamed_content_accumulator += error_hint + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=error_hint, + ) + else: + yield _build_stream_chunk(response_id, model_name, content=error_hint) + finally: + # 选择最佳最终回复 + final_reply, _ = _select_best_final_reply( + streamed_content_accumulator, + authoritative_final_content, + authoritative_final_source_type, + ) + + # 发送缺失的后缀(如果有) + missing_suffix = _compute_missing_suffix( + streamed_content_accumulator, final_reply + ) + if missing_suffix: + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=missing_suffix, + ) + else: + yield _build_stream_chunk( + response_id, model_name, content=missing_suffix + ) + streamed_content_accumulator += missing_suffix + elif final_reply != streamed_content_accumulator: + # 处理分叉内容(使用最终内容) + if not streamed_content_accumulator and final_reply: + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=final_reply, + ) + else: + yield _build_stream_chunk( + response_id, model_name, content=final_reply + ) + streamed_content_accumulator = final_reply + + yield _build_stream_chunk(response_id, model_name, finish_reason="stop") + yield "data: [DONE]\n\n" + + +def _create_standard_stream_generator( + response_id: str, + model_name: str, + first_item: Any, + stream_gen: Iterable[Any], + client_type: str = "", +) -> Generator[str, None, None]: + """ + Standard 模式流式生成器:使用前端定义的 SSE 事件类型 + + 前端协议: + - thinking_chunk: 流式思考片段 + - thinking_replace: 完整思考替换 + - search_metadata: 搜索结果 + - choices[0].delta.content: 正文内容 + + 对非 web 客户端(如 opencode 等严格 OpenAI 兼容客户端),thinking 使用 + delta.reasoning_content;search 以 markdown 注入 content(对齐 Heavy), + 避免自定义 SSE 字段触发 strict validation,同时不丢搜索结果。 + """ + streamed_content_accumulator = "" + streamed_thinking_accumulator = "" + collected_search_sources = [] + collected_search_queries = [] + authoritative_final_content = "" + authoritative_final_source_type = "" + assistant_started = False + is_web_client = client_type == "web" + + try: + for raw_item in _iter_stream_items(first_item, stream_gen): + item = _normalize_stream_item(raw_item) + item_type = item.get("type") + + if item_type == "final_content": + final_text = str(item.get("text", "") or "").strip() + if final_text: + authoritative_final_content = final_text + authoritative_final_source_type = str( + item.get("source_type", "") or "" + ) + continue + + # Standard 模式:处理 thinking + if item_type == "thinking": + thinking_text = item.get("text", "") + if thinking_text: + streamed_thinking_accumulator += thinking_text + if is_web_client: + # Web UI: 前端协议 thinking_chunk + yield f"data: {json.dumps({'type': 'thinking_chunk', 'text': thinking_text}, ensure_ascii=False)}\n\n" + else: + # 严格 OpenAI 客户端:reasoning_content;首包带 role + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + thinking=thinking_text, + ) + else: + yield _build_stream_chunk( + response_id, model_name, thinking=thinking_text + ) + continue + + # Standard 模式:处理 search(收集起来,最后输出) + if item_type == "search": + search_data = item.get("data", {}) + if isinstance(search_data, dict): + # 提取 queries 和 sources + queries = search_data.get("queries", []) + sources = search_data.get("sources", []) + + if queries: + collected_search_queries.extend(queries) + if sources: + collected_search_sources.extend(sources) + continue + + if item_type != "content": + continue + + chunk_text = item.get("text", "") + if not chunk_text: + continue + + streamed_content_accumulator += chunk_text + + # 输出标准 OpenAI 格式的 delta + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=chunk_text, + ) + else: + yield _build_stream_chunk(response_id, model_name, content=chunk_text) + except asyncio.CancelledError: + logger.info( + "Standard streaming cancelled by client", + extra={"request_info": {"event": "standard_stream_cancelled"}}, + ) + raise + except BaseException as exc: + if _is_client_disconnect_error(exc): + logger.info( + "Standard streaming connection closed by client", + extra={ + "request_info": {"event": "standard_stream_client_disconnected"} + }, + ) + return + logger.error( + "Standard streaming interrupted", + exc_info=True, + extra={"request_info": {"event": "standard_stream_interrupted"}}, + ) + error_hint = "\n\n[上游连接中断,请稍后重试。]" + streamed_content_accumulator += error_hint + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=error_hint, + ) + else: + yield _build_stream_chunk(response_id, model_name, content=error_hint) + finally: + # 选择最佳最终回复 + final_reply, _ = _select_best_final_reply( + streamed_content_accumulator, + authoritative_final_content, + authoritative_final_source_type, + ) + + # 发送缺失的后缀(如果有) + missing_suffix = _compute_missing_suffix( + streamed_content_accumulator, final_reply + ) + if missing_suffix: + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=missing_suffix, + ) + else: + yield _build_stream_chunk( + response_id, model_name, content=missing_suffix + ) + streamed_content_accumulator += missing_suffix + elif final_reply != streamed_content_accumulator: + # 处理分叉内容(使用最终内容) + if not streamed_content_accumulator and final_reply: + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=final_reply, + ) + else: + yield _build_stream_chunk( + response_id, model_name, content=final_reply + ) + streamed_content_accumulator = final_reply + + # 输出搜索结果 + if collected_search_sources or collected_search_queries: + search_payload = { + "queries": collected_search_queries, + "sources": collected_search_sources, + } + if is_web_client: + # Web UI:扩展 search_metadata(带 OpenAI chunk 外壳) + yield _build_local_ui_chunk( + response_id, + model_name, + "search_metadata", + searches=search_payload, + ) + else: + # 严格客户端:markdown 注入 content,不丢结果 + search_md = _format_search_results_md(search_payload) + if search_md: + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + model_name, + role="assistant", + content=search_md, + ) + else: + yield _build_stream_chunk( + response_id, model_name, content=search_md + ) + + yield _build_stream_chunk(response_id, model_name, finish_reason="stop") + yield "data: [DONE]\n\n" + + +def _persist_round( + manager, + background_tasks: BackgroundTasks, + conversation_id: str, + user_prompt: str, + assistant_reply: str, + assistant_thinking: str = "", +) -> None: + """ + 持久化一轮对话并触发异步预压缩。 + + 预压缩逻辑: + - 当 round >= WINDOW_ROUNDS//2 时,提前压缩滑出窗口的轮次 + - 使用 BackgroundTasks 确保不阻塞当前对话 + """ + round_index = manager.persist_round( + conversation_id, + user_prompt, + assistant_reply, + assistant_thinking=assistant_thinking, + ) + + # 异步预压缩:当窗口快满时提前压缩 + WINDOW_ROUNDS = 8 # 与 conversation.py 保持一致 + PRECOMPRESS_THRESHOLD = WINDOW_ROUNDS // 2 # 在第 4 轮时开始预压缩 + + if round_index >= PRECOMPRESS_THRESHOLD: + # 计算需要压缩的轮次(滑出窗口的轮次) + round_to_compress = round_index - WINDOW_ROUNDS + 1 + if round_to_compress >= 0: + background_tasks.add_task( + compress_sliding_window_round, + manager=manager, + conversation_id=conversation_id, + round_number=round_to_compress, + ) + logger.info( + "Triggered async pre-compression", + extra={ + "request_info": { + "event": "async_precompress_triggered", + "conversation_id": conversation_id, + "current_round": round_index, + "compress_round": round_to_compress, + } + }, + ) + + # 保留原有的压缩逻辑作为兜底 + background_tasks.add_task( + compress_round_if_needed, + manager=manager, + conversation_id=conversation_id, + ) + + +def _persist_history_messages( + manager, conversation_id: str, history_messages: List[Tuple[str, str, str]] +) -> None: + for role, content, thinking in history_messages: + manager.add_message(conversation_id, role, content, thinking) + + +def _is_client_disconnect_error(exc: BaseException) -> bool: + if isinstance(exc, asyncio.CancelledError): + return True + if isinstance(exc, (BrokenPipeError, ConnectionResetError)): + return True + if isinstance(exc, OSError): + return exc.errno in {32, 54, 104, 10053, 10054} + return False + + +async def _handle_lite_request( + request: Request, + req_body: ChatCompletionRequest, + response: Response, +) -> JSONResponse | StreamingResponse | ChatCompletionResponse: + """处理 Lite 模式请求(无记忆,单轮问答)""" + pool = request.app.state.account_pool + + # 提取用户问题 + user_prompt = _prepare_messages_lite(req_body) + + # 验证模型 + if not is_supported_model(req_body.model): + available_models = list_available_models() + raise HTTPException( + status_code=400, + detail=f"Unsupported model '{req_body.model}'. Available models: {', '.join(available_models)}", + ) + + response_id = f"chatcmpl-{uuid.uuid4().hex}" + max_retries = max(3, len(pool.clients)) + + for attempt in range(1, max_retries + 1): + client = None + try: + client = pool.get_client() + + # 构建 Lite transcript(无历史记忆) + transcript = build_lite_transcript(user_prompt, req_body.model) + + # 调用 Notion API(不使用 thread_id) + stream_gen = client.stream_response(transcript, thread_id=None) + first_item = next(stream_gen, None) + + if first_item is None: + raise NotionUpstreamError( + "Notion upstream returned empty content.", retriable=True + ) + + # 流式响应 + if req_body.stream: + stream_headers = { + "Cache-Control": "no-cache", + "Connection": "keep-alive", + "X-Accel-Buffering": "no", + } + return StreamingResponse( + _create_lite_stream_generator( + response_id, + req_body.model, + first_item, + stream_gen, + ), + media_type="text/event-stream", + headers=stream_headers, + ) + + # 非流式响应 + content_parts: list[str] = [] + authoritative_final_content = "" + authoritative_final_source_type = "" + + for raw_item in _iter_stream_items(first_item, stream_gen): + item = _normalize_stream_item(raw_item) + item_type = item.get("type") + + if item_type == "final_content": + final_text = str(item.get("text", "") or "").strip() + if final_text: + authoritative_final_content = final_text + authoritative_final_source_type = str( + item.get("source_type", "") or "" + ) + continue + + # Lite 模式忽略 thinking 和 search + if item_type in ("thinking", "search"): + continue + + if item_type != "content": + continue + + chunk_text = item.get("text", "") + if chunk_text: + content_parts.append(chunk_text) + + full_text, _ = _select_best_final_reply( + "".join(content_parts), + authoritative_final_content, + authoritative_final_source_type, + ) + + if not full_text.strip(): + raise NotionUpstreamError( + "Notion upstream returned empty content.", retriable=True + ) + + response_text = ( + full_text if full_text.strip() else "[assistant_no_visible_content]" + ) + return ChatCompletionResponse( + id=response_id, + model=req_body.model, + choices=[ + ChatMessageResponseChoice( + message=ChatMessage(role="assistant", content=response_text) + ) + ], + ) + + except NotionUpstreamError as exc: + if client is not None and exc.retriable: + pool.mark_failed(client) + logger.warning( + "Lite mode: Notion upstream failed", + extra={ + "request_info": { + "event": "lite_notion_upstream_failed", + "attempt": attempt, + "max_retries": max_retries, + "status_code": exc.status_code, + "retriable": exc.retriable, + "response_excerpt": exc.response_excerpt, + } + }, + ) + if attempt == max_retries or not exc.retriable: + return _upstream_error_response(exc) + except RuntimeError as exc: + logger.error( + "Lite mode: No available client in account pool", + extra={ + "request_info": { + "event": "lite_account_pool_unavailable", + "detail": str(exc), + } + }, + ) + return _build_error_response( + 503, + code="POOL_COOLING", + message=str(exc), + error_type="account_pool_cooling", + suggestion="所有账号暂时冷却中,请等待几秒后重试", + ) + except HTTPException: + raise + except Exception: + if client is not None: + pool.mark_failed(client) + logger.error( + "Lite mode: Unhandled error", + exc_info=True, + extra={ + "request_info": { + "event": "lite_unhandled_exception", + "attempt": attempt, + } + }, + ) + if attempt == max_retries: + return _build_error_response( + 500, + code="INTERNAL_ERROR", + message="服务内部异常", + error_type="internal_error", + suggestion="请稍后重试,如持续出现请联系管理员", + ) + + return _build_error_response( + 503, + code="RETRIES_EXHAUSTED", + message="所有重试均已失败", + error_type="upstream_error", + suggestion="Notion 上游服务暂时不可用,请稍后重试", + ) + + +async def _handle_standard_request( + request: Request, + req_body: ChatCompletionRequest, + response: Response, +) -> JSONResponse | StreamingResponse | ChatCompletionResponse: + """ + 处理 Standard 模式请求(完整上下文,支持 thinking 和搜索) + + 类似 Lite 模式,但: + 1. 发送完整 messages 历史 + 2. 保留 thinking 输出 + 3. 保留搜索结果输出 + """ + from app.conversation import build_standard_transcript + + pool = request.app.state.account_pool + + # 验证模型 + if not is_supported_model(req_body.model): + available_models = list_available_models() + raise HTTPException( + status_code=400, + detail=f"Unsupported model '{req_body.model}'. Available models: {', '.join(available_models)}", + ) + + response_id = f"chatcmpl-{uuid.uuid4().hex}" + max_retries = max(3, len(pool.clients)) + + for attempt in range(1, max_retries + 1): + client = None + try: + client = pool.get_client() + + # 构建 Standard transcript(完整上下文) + # 从 client 提取账号信息 + account = { + "user_id": client.user_id, + "space_id": client.space_id, + } + messages = [msg.dict() for msg in req_body.messages] + transcript = build_standard_transcript(messages, req_body.model, account) + + # 调用 Notion API(不使用 thread_id,让 Notion ��动处理) + stream_gen = client.stream_response(transcript, thread_id=None) + first_item = next(stream_gen, None) + + if first_item is None: + raise NotionUpstreamError( + "Notion upstream returned empty content.", retriable=True + ) + + # 流式响应 + if req_body.stream: + stream_headers = { + "Cache-Control": "no-cache", + "Connection": "keep-alive", + "X-Accel-Buffering": "no", + } + client_type = request.headers.get("X-Client-Type", "").lower() + return StreamingResponse( + _create_standard_stream_generator( + response_id, + req_body.model, + first_item, + stream_gen, + client_type=client_type, + ), + media_type="text/event-stream", + headers=stream_headers, + ) + + # 非流式响应 + content_parts: list[str] = [] + thinking_parts: list[str] = [] + search_results: list[dict] = [] + authoritative_final_content = "" + authoritative_final_source_type = "" + + for raw_item in _iter_stream_items(first_item, stream_gen): + item = _normalize_stream_item(raw_item) + item_type = item.get("type") + + if item_type == "final_content": + final_text = str(item.get("text", "") or "").strip() + if final_text: + authoritative_final_content = final_text + authoritative_final_source_type = str( + item.get("source_type", "") or "" + ) + continue + + # Standard 模式:处理 thinking + if item_type == "thinking": + thinking_text = item.get("text", "") + if thinking_text: + thinking_parts.append(thinking_text) + continue + + # Standard 模式:处理 search + if item_type == "search": + search_data = item.get("data", {}) + if search_data: + search_results.append(search_data) + continue + + if item_type != "content": + continue + + chunk_text = item.get("text", "") + if chunk_text: + content_parts.append(chunk_text) + + full_text, _ = _select_best_final_reply( + "".join(content_parts), + authoritative_final_content, + authoritative_final_source_type, + ) + + if not full_text.strip(): + raise NotionUpstreamError( + "Notion upstream returned empty content.", retriable=True + ) + + response_text = ( + full_text if full_text.strip() else "[assistant_no_visible_content]" + ) + + # 构建响应 + response_message = ChatMessage(role="assistant", content=response_text) + + # 如果有 thinking,添加到扩展字段(前端会读取) + if thinking_parts: + response_message.thinking = "".join(thinking_parts) + + # 构建响应 + response_obj = ChatCompletionResponse( + id=response_id, + model=req_body.model, + choices=[ChatMessageResponseChoice(message=response_message)], + ) + + # 如果有搜索结果,添加到扩展字段(前端会读取) + if search_results: + # 提取 queries 和 sources + all_queries = [] + all_sources = [] + for result in search_results: + if isinstance(result, dict): + all_queries.extend(result.get("queries", [])) + all_sources.extend(result.get("sources", [])) + + if all_queries or all_sources: + # 添加到自定义字段 + response_obj.search_metadata = { + "queries": all_queries, + "sources": all_sources, + } + + return response_obj + + except NotionUpstreamError as exc: + if client is not None and exc.retriable: + pool.mark_failed(client) + logger.warning( + "Standard mode: Notion upstream failed", + extra={ + "request_info": { + "event": "standard_notion_upstream_failed", + "attempt": attempt, + "max_retries": max_retries, + "status_code": exc.status_code, + "retriable": exc.retriable, + "response_excerpt": exc.response_excerpt, + } + }, + ) + if attempt == max_retries or not exc.retriable: + return _upstream_error_response(exc) + except RuntimeError as exc: + logger.error( + "Standard mode: No available client in account pool", + extra={ + "request_info": { + "event": "standard_account_pool_unavailable", + "detail": str(exc), + } + }, + ) + return _build_error_response( + 503, + code="POOL_COOLING", + message=str(exc), + error_type="account_pool_cooling", + suggestion="所有账号暂时冷却中,请等待几秒后重试", + ) + except HTTPException: + raise + except Exception: + if client is not None: + pool.mark_failed(client) + logger.error( + "Standard mode: Unhandled error", + exc_info=True, + extra={ + "request_info": { + "event": "standard_unhandled_exception", + "attempt": attempt, + } + }, + ) + if attempt == max_retries: + return _build_error_response( + 500, + code="INTERNAL_ERROR", + message="服务内部异常", + error_type="internal_error", + suggestion="请稍后重试,如持续出现请联系管理员", + ) + + return _build_error_response( + 503, + code="RETRIES_EXHAUSTED", + message="所有重试均已失败", + error_type="upstream_error", + suggestion="Notion 上游服务暂时不可用,请稍后重试", + ) + + +@router.post("/chat/completions", tags=["chat"]) +async def create_chat_completion( + request: Request, + req_body: ChatCompletionRequest, + background_tasks: BackgroundTasks, + response: Response, +): + """ + 创建聊天请求,严格兼容 OpenAI API。 + + 速率限制: + - Lite 模式:30/分钟(适合单轮问答) + - Standard 模式:25/分钟(完整上下文,支持 thinking 和搜索) + - Heavy 模式:20/分钟(包含会话管理) + """ + from app.config import is_standard_mode + + # Lite 模式:单轮问答,无记忆 + if is_lite_mode(): + return await _handle_lite_request(request, req_body, response) + + # Standard 模式:完整上下文,支持 thinking 和搜索 + if is_standard_mode(): + return await _handle_standard_request(request, req_body, response) + + # Heavy 模式:完整会话管理 + pool = request.app.state.account_pool + manager = request.app.state.conversation_manager + + user_prompt, history_messages, raw_user_prompt = _prepare_messages(req_body) + recall_query = ( + _extract_recall_query(raw_user_prompt) + if _contains_recall_intent(raw_user_prompt) + else None + ) + + if not is_supported_model(req_body.model): + available_models = list_available_models() + raise HTTPException( + status_code=400, + detail=f"Unsupported model '{req_body.model}'. Available models: {', '.join(available_models)}", + ) + + conversation_id = ( + req_body.conversation_id.strip() if req_body.conversation_id else "" + ) + restore_history = False + if not conversation_id: + conversation_id = manager.new_conversation() + restore_history = True + elif not manager.conversation_exists(conversation_id): + logger.warning( + "Conversation id not found, creating a fresh conversation", + extra={ + "request_info": { + "event": "conversation_id_not_found", + "provided_conversation_id": conversation_id, + } + }, + ) + conversation_id = manager.new_conversation() + restore_history = True + + # 关键修复:总是持久化客户端发送的历史消息,避免上下文丢失 + # 即使 conversation_id 已存在,也需要同步客户端发送的完整历史 + if history_messages: + # 检查是否需要持久化(避免重复) + with manager._get_conn() as conn: + existing_count = manager._count_messages(conn, conversation_id) + history_count = len(history_messages) + + # 只有当客户端发送的历史消息多于数据库中的消息时才持久化 + # 这样可以: + # 1. 避免重复持久化相同的历史 + # 2. 确保客户端发送的完整历史被保存 + # 3. 解决"滑动窗口缺失 AI 回复"的 bug + if history_count > existing_count: + _persist_history_messages(manager, conversation_id, history_messages) + restored_user_count = sum( + 1 for role, *_ in history_messages if role == "user" + ) + restored_assistant_count = sum( + 1 for role, *_ in history_messages if role == "assistant" + ) + + logger.info( + "Restored history into conversation", + extra={ + "request_info": { + "event": "conversation_history_restored", + "conversation_id": conversation_id, + "restore_history_flag": restore_history, + "existing_count": existing_count, + "history_count": history_count, + "restored_total": len(history_messages), + "restored_user_count": restored_user_count, + "restored_assistant_count": restored_assistant_count, + } + }, + ) + + response_id = f"chatcmpl-{uuid.uuid4().hex}" + max_retries = max(3, len(pool.clients)) + + for attempt in range(1, max_retries + 1): + client = None + try: + client = pool.get_client() + transcript_payload = manager.get_transcript_payload( + notion_client=client, + conversation_id=conversation_id, + new_prompt=user_prompt, + model_name=req_body.model, + recall_query=recall_query, + ) + transcript = transcript_payload["transcript"] + memory_degraded = bool(transcript_payload.get("memory_degraded")) + memory_headers = {"X-Memory-Status": "degraded"} if memory_degraded else {} + + # 获取或创建 thread_id 以保持对话上下文 + thread_id = manager.get_conversation_thread_id(conversation_id) + + # 检测用户是否在对话中途切换了模型。Notion 的 thread 会把 config 中的 model + # 粘在服务端 thread 对象上,复用同一 thread 即使 transcript 里写了新 model, + # 上游实际仍按原始模型执行。必须丢掉旧 thread 让 Notion 按新 model 新建, + # 对话上下文由我们自己的滑动窗口 + 压缩摘要重建,不会失忆。 + if thread_id: + bound_model = manager.get_conversation_thread_model(conversation_id) + # bound_model 为 None 表示升级前的遗留对话,没记录过模型绑定, + # 无法判断 thread 当初绑的是什么模型。为避免继续踩老 bug, + # 一律当作"可能不匹配"处理,丢弃老 thread 重新开。 + if not bound_model or bound_model != req_body.model: + logger.info( + "Recreating Notion thread: model changed or legacy binding", + extra={ + "request_info": { + "event": "thread_model_switched", + "conversation_id": conversation_id, + "old_model": bound_model, + "new_model": req_body.model, + "reason": "model_mismatch" if bound_model else "legacy_no_binding", + } + }, + ) + manager.clear_conversation_thread(conversation_id) + thread_id = None + + stream_gen = client.stream_response(transcript, thread_id=thread_id) + first_item = next(stream_gen, None) + + # 保存 thread_id(如果是新对话或刚切换模型) + if not thread_id and hasattr(client, "current_thread_id"): + manager.set_conversation_thread_id( + conversation_id, + client.current_thread_id, + model_name=req_body.model, + ) + + if first_item is None: + raise NotionUpstreamError( + "Notion upstream returned empty content.", retriable=True + ) + + def openai_stream_generator() -> Generator[str, None, None]: + streamed_content_accumulator = "" + thinking_accumulator = "" + authoritative_final_content = "" + authoritative_final_source_type = "" + assistant_started = False + pending_search_md = "" + client_type = request.headers.get("X-Client-Type", "").lower() + recent_thinking_buffer: list[str] = [] + + try: + for raw_item in _iter_stream_items(first_item, stream_gen): + item = _normalize_stream_item(raw_item) + item_type = item.get("type") + + if item_type == "search": + search_data = item.get("data") + if isinstance(search_data, dict) and search_data: + pending_search_md += _format_search_results_md( + search_data + ) + if client_type == "web": + yield _build_local_ui_chunk( + response_id, + req_body.model, + "search_metadata", + searches=search_data, + ) + continue + + if item_type == "final_content": + final_text = str(item.get("text", "") or "").strip() + if final_text: + authoritative_final_content = final_text + authoritative_final_source_type = str( + item.get("source_type", "") or "" + ) + continue + + if item_type == "thinking": + thinking_text = item.get("text", "") + if thinking_text: + thinking_accumulator += thinking_text + # Track recent thinking for overlap detection + recent_thinking_buffer.append(thinking_text) + # Keep buffer manageable (max 40 recent chunks) + if len(recent_thinking_buffer) > 40: + recent_thinking_buffer.pop(0) + + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + req_body.model, + role="assistant", + thinking=thinking_text, + ) + else: + yield _build_stream_chunk( + response_id, + req_body.model, + thinking=thinking_text, + ) + continue + + if item_type != "content": + continue + + chunk_text = item.get("text", "") + if not chunk_text and not pending_search_md: + continue + + # Check if content overlaps with recent thinking (prevents thinking leakage) + if recent_thinking_buffer and chunk_text.strip(): + combined_recent_thinking = "".join(recent_thinking_buffer) + chunk_normalized = chunk_text.strip() + + # Use normalized text without spaces for robust comparison + combined_norm = re.sub(r"\s+", "", combined_recent_thinking) + chunk_norm = re.sub(r"\s+", "", chunk_normalized) + + # Check for significant overlap - skip duplicate content + # We only skip if a sufficiently long chunk matches to avoid swallowing short common characters. + if ( + chunk_norm + and len(chunk_norm) > 3 + and ( + chunk_norm in combined_norm + or ( + len(chunk_norm) > 10 + and chunk_norm[:10] in combined_norm + ) + ) + ): + # Skip this chunk as it's likely duplicated thinking content + logger.debug( + "Skipping duplicate content chunk that overlaps with thinking", + extra={ + "request_info": { + "event": "content_overlap_with_thinking", + "chunk_length": len(chunk_text), + "overlap_detected": True, + } + }, + ) + continue + + # 在第一个正文内容发出前,把积攒的搜索信息拼上去 + if pending_search_md and client_type != "web": + chunk_text = pending_search_md + chunk_text + + if pending_search_md: + pending_search_md = "" + + streamed_content_accumulator += chunk_text + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + req_body.model, + role="assistant", + content=chunk_text, + ) + else: + yield _build_stream_chunk( + response_id, req_body.model, content=chunk_text + ) + except asyncio.CancelledError: + logger.info( + "Streaming response cancelled by downstream client", + extra={ + "request_info": { + "event": "stream_cancelled_by_client", + "conversation_id": conversation_id, + "attempt": attempt, + } + }, + ) + raise + except BaseException as exc: + if _is_client_disconnect_error(exc): + logger.info( + "Streaming connection closed by downstream client", + extra={ + "request_info": { + "event": "stream_client_disconnected", + "conversation_id": conversation_id, + "attempt": attempt, + } + }, + ) + return + if ( + isinstance(exc, NotionUpstreamError) + and client is not None + and exc.retriable + ): + pool.mark_failed(client) + log_method = ( + logger.warning + if isinstance(exc, NotionUpstreamError) + else logger.error + ) + log_method( + "Streaming response interrupted", + exc_info=True, + extra={ + "request_info": { + "event": "stream_interrupted", + "conversation_id": conversation_id, + "attempt": attempt, + "is_upstream_error": isinstance( + exc, NotionUpstreamError + ), + } + }, + ) + error_hint = "\n\n[上游连接中断,请稍后重试。]" + streamed_content_accumulator += error_hint + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + req_body.model, + role="assistant", + content=error_hint, + ) + else: + yield _build_stream_chunk( + response_id, req_body.model, content=error_hint + ) + finally: + final_reply, reply_decision = _select_best_final_reply( + streamed_content_accumulator, + authoritative_final_content, + authoritative_final_source_type, + ) + + missing_suffix = _compute_missing_suffix( + streamed_content_accumulator, final_reply + ) + if missing_suffix: + suffix_to_emit = missing_suffix + if ( + pending_search_md + and client_type != "web" + and not streamed_content_accumulator + ): + suffix_to_emit = pending_search_md + suffix_to_emit + pending_search_md = "" + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + req_body.model, + role="assistant", + content=suffix_to_emit, + ) + else: + yield _build_stream_chunk( + response_id, req_body.model, content=suffix_to_emit + ) + streamed_content_accumulator += suffix_to_emit + elif final_reply != streamed_content_accumulator: + # Diverged bodies cannot be safely "patched" in plain OpenAI deltas. + # Web client supports replace event to keep rendered body aligned with persisted final reply. + if client_type == "web": + yield _build_local_ui_chunk( + response_id, + req_body.model, + "content_replace", + content=final_reply, + source_type=authoritative_final_source_type, + decision=reply_decision, + ) + streamed_content_accumulator = final_reply + elif not streamed_content_accumulator and final_reply: + # Non-web fallback when nothing has been shown yet. + emit_text = final_reply + if pending_search_md and client_type != "web": + emit_text = pending_search_md + emit_text + pending_search_md = "" + if not assistant_started: + assistant_started = True + yield _build_stream_chunk( + response_id, + req_body.model, + role="assistant", + content=emit_text, + ) + else: + yield _build_stream_chunk( + response_id, req_body.model, content=emit_text + ) + streamed_content_accumulator = final_reply + + thinking_replacement = _build_thinking_replacement( + streamed_content_accumulator, + thinking_accumulator, + final_reply, + authoritative_final_source_type, + ) + if client_type == "web" and thinking_replacement is not None: + yield _build_local_ui_chunk( + response_id, + req_body.model, + "thinking_replace", + thinking=thinking_replacement["thinking"], + decision=thinking_replacement["decision"], + overlap_ratio=thinking_replacement["overlap_ratio"], + source_type=thinking_replacement["source_type"], + reply_decision=reply_decision, + ) + + persisted_thinking = ( + str(thinking_replacement["thinking"]) + if thinking_replacement is not None + else thinking_accumulator + ) + if final_reply.strip() or persisted_thinking.strip(): + try: + _persist_round( + manager, + background_tasks, + conversation_id, + user_prompt, + final_reply, + persisted_thinking, + ) + except Exception: + logger.error( + "Failed to persist conversation round", + exc_info=True, + extra={ + "request_info": { + "event": "conversation_persist_failed", + "conversation_id": conversation_id, + } + }, + ) + yield _build_stream_chunk( + response_id, req_body.model, finish_reason="stop" + ) + yield "data: [DONE]\n\n" + + if req_body.stream: + stream_headers = { + "Cache-Control": "no-cache", + "Connection": "keep-alive", + "X-Accel-Buffering": "no", + "X-Conversation-Id": conversation_id, + **memory_headers, + } + return StreamingResponse( + openai_stream_generator(), + media_type="text/event-stream", + headers=stream_headers, + ) + + content_parts: list[str] = [] + thinking_parts: list[str] = [] + authoritative_final_content = "" + authoritative_final_source_type = "" + for raw_item in _iter_stream_items(first_item, stream_gen): + item = _normalize_stream_item(raw_item) + item_type = item.get("type") + if item_type == "final_content": + final_text = str(item.get("text", "") or "").strip() + if final_text: + authoritative_final_content = final_text + authoritative_final_source_type = str( + item.get("source_type", "") or "" + ) + continue + if item_type == "thinking": + thinking_text = str(item.get("text", "") or "") + if thinking_text: + thinking_parts.append(thinking_text) + continue + if item_type != "content": + continue + chunk_text = item.get("text", "") + if chunk_text: + content_parts.append(chunk_text) + + full_text, _ = _select_best_final_reply( + "".join(content_parts), + authoritative_final_content, + authoritative_final_source_type, + ) + merged_thinking = "".join(thinking_parts).strip() + if not full_text.strip() and not merged_thinking: + raise NotionUpstreamError( + "Notion upstream returned empty content.", retriable=True + ) + + _persist_round( + manager, + background_tasks, + conversation_id, + user_prompt, + full_text, + merged_thinking, + ) + response.headers["X-Conversation-Id"] = conversation_id + if memory_degraded: + response.headers["X-Memory-Status"] = "degraded" + + response_text = ( + full_text if full_text.strip() else "[assistant_no_visible_content]" + ) + return ChatCompletionResponse( + id=response_id, + model=req_body.model, + choices=[ + ChatMessageResponseChoice( + message=ChatMessage(role="assistant", content=response_text) + ) + ], + ) + except NotionUpstreamError as exc: + if client is not None and exc.retriable: + pool.mark_failed(client) + logger.warning( + "Notion upstream failed", + extra={ + "request_info": { + "event": "notion_upstream_failed", + "attempt": attempt, + "max_retries": max_retries, + "conversation_id": conversation_id, + "status_code": exc.status_code, + "retriable": exc.retriable, + "response_excerpt": exc.response_excerpt, + } + }, + ) + if attempt == max_retries or not exc.retriable: + return _upstream_error_response(exc) + except RuntimeError as exc: + logger.error( + "No available client in account pool", + extra={ + "request_info": { + "event": "account_pool_unavailable", + "detail": str(exc), + } + }, + ) + return _build_error_response( + 503, + code="POOL_COOLING", + message=str(exc), + error_type="account_pool_cooling", + suggestion="所有账号暂时冷却中,请等待几秒后重试", + ) + except HTTPException: + raise + except Exception: + if client is not None: + pool.mark_failed(client) + logger.error( + "Unhandled chat completion error", + exc_info=True, + extra={ + "request_info": { + "event": "chat_completion_unhandled_exception", + "attempt": attempt, + "conversation_id": conversation_id, + } + }, + ) + if attempt == max_retries: + return _build_error_response( + 500, + code="INTERNAL_ERROR", + message="服务内部异常", + error_type="internal_error", + suggestion="请稍后重试,如持续出现请联系管理员", + ) + + return _build_error_response( + 503, + code="RETRIES_EXHAUSTED", + message="所有重试均已失败", + error_type="upstream_error", + suggestion="Notion 上游服务暂时不可用,请稍后重试", + ) + + +@router.delete("/conversations/{conversation_id}", tags=["chat"]) +async def delete_conversation(conversation_id: str, request: Request): + manager = request.app.state.conversation_manager + deleted = manager.delete_conversation(conversation_id) + if not deleted: + raise HTTPException(status_code=404, detail="Conversation not found.") + return {"id": conversation_id, "deleted": True} diff --git a/app/api/models.py b/app/api/models.py new file mode 100644 index 0000000..0e21025 --- /dev/null +++ b/app/api/models.py @@ -0,0 +1,33 @@ +import time +from typing import Dict, Any + +from fastapi import APIRouter + +from app.model_registry import get_display_name, get_model_icon, list_available_models + +router = APIRouter() + + +@router.get("/models", tags=["models"]) +async def list_models() -> Dict[str, Any]: + """ + 列出可用的模型,兼容 OpenAI 格式。 + """ + created_at = int(time.time()) + return { + "object": "list", + "data": [ + { + "id": model_id, + "object": "model", + "created": created_at, + "owned_by": "notion", + "permission": [], + "root": model_id, + "parent": None, + "display_name": get_display_name(model_id), + "icon": get_model_icon(model_id), + } + for model_id in list_available_models() + ], + } diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..eb8c2eb --- /dev/null +++ b/app/config.py @@ -0,0 +1,66 @@ +import os +import json +from dotenv import load_dotenv + +# 加载 .env 文件中的环境变量(override=True 确保 .env 优先于系统环境变量) +load_dotenv(override=True) + +REQUIRED_ACCOUNT_FIELDS = {"token_v2", "space_id", "user_id"} + +def load_accounts(): + """ + 从 accounts.json 文件或环境变量 NOTION_ACCOUNTS 加载账号配置。 + 优先级:accounts.json > NOTION_ACCOUNTS 环境变量 + """ + # 优先从 accounts.json 文件读取 + accounts_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "accounts.json") + accounts_json = None + + if os.path.exists(accounts_file): + with open(accounts_file, "r", encoding="utf-8") as f: + accounts_json = f.read().strip() + + # 回退到环境变量 + if not accounts_json: + accounts_json = os.getenv("NOTION_ACCOUNTS") + + if not accounts_json: + raise ValueError("未找到账号配置:请创建 accounts.json 文件或设置 NOTION_ACCOUNTS 环境变量。") + + try: + accounts = json.loads(accounts_json) + if not isinstance(accounts, list) or len(accounts) == 0: + raise ValueError("账号配置格式不正确,应提供非空的 JSON 数组。") + for idx, account in enumerate(accounts): + if not isinstance(account, dict): + raise ValueError(f"账号配置[{idx}] 必须是对象。") + missing = sorted(field for field in REQUIRED_ACCOUNT_FIELDS if not account.get(field)) + if missing: + raise ValueError(f"账号配置[{idx}] 缺少必要字段: {', '.join(missing)}") + return accounts + except json.JSONDecodeError as e: + raise ValueError(f"解析账号配置失败: {e}") + +# 全局配置对象 +ACCOUNTS = load_accounts() + +# FastAPI 服务配置 +API_KEY = os.getenv("API_KEY", "") +SILICONFLOW_API_KEY = os.getenv("SILICONFLOW_API_KEY", "") +HOST = os.getenv("HOST", "0.0.0.0") +PORT = int(os.getenv("PORT", "8000")) +ALLOWED_ORIGINS = [origin.strip() for origin in os.getenv("ALLOWED_ORIGINS", "*").split(",") if origin.strip()] + +# APP_MODE: heavy(默认)、lite 或 standard +APP_MODE = os.getenv("APP_MODE", "heavy").lower().strip() + +def is_lite_mode() -> bool: + return APP_MODE == "lite" + +def is_standard_mode() -> bool: + """Standard 模式:发送完整上下文,支持 thinking 和搜索输出""" + return APP_MODE == "standard" + +def get_default_account(): + """获取默认账号(列表中的第一个账号)""" + return ACCOUNTS[0] diff --git a/app/conversation.py b/app/conversation.py new file mode 100644 index 0000000..fcfe876 --- /dev/null +++ b/app/conversation.py @@ -0,0 +1,2115 @@ +import datetime +import os +import re +import sqlite3 +import uuid +from typing import Any, Dict, List, Optional + +from app.logger import logger +from app.model_registry import get_thread_type, is_gemini_model + + +class ConversationManager: + """SQLite-backed conversation history manager with layered memory.""" + + WINDOW_SIZE = 16 # 16 条消息 = 8 轮对话 + WINDOW_ROUNDS = 8 # 8 轮对话 + SUMMARY_INJECT_LIMIT = 15 + RECALL_LIMIT = 5 + ASSISTANT_EMPTY_PLACEHOLDER = "[assistant_no_visible_content]" + + def __init__(self): + self.db_path = os.getenv("DB_PATH", "./data/conversations.db") + os.makedirs(os.path.dirname(os.path.abspath(self.db_path)), exist_ok=True) + self._init_db() + + def _get_conn(self) -> sqlite3.Connection: + conn = sqlite3.connect(self.db_path, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA busy_timeout = 5000") + return conn + + def _ensure_column(self, conn: sqlite3.Connection, table: str, column_sql: str) -> None: + """Ensure column exists while prioritizing SQLite IF NOT EXISTS syntax.""" + try: + conn.execute(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {column_sql}") + return + except sqlite3.OperationalError: + # Fallback for old SQLite builds without IF NOT EXISTS support. + column_name = column_sql.split()[0] + columns = {row["name"] for row in conn.execute(f"PRAGMA table_info({table})").fetchall()} + if column_name not in columns: + conn.execute(f"ALTER TABLE {table} ADD COLUMN {column_sql}") + + def _init_db(self) -> None: + with self._get_conn() as conn: + cursor = conn.cursor() + cursor.execute("PRAGMA journal_mode = WAL") + cursor.execute( + """ + CREATE TABLE IF NOT EXISTS conversations ( + id TEXT PRIMARY KEY, + title TEXT, + created_at INTEGER, + summary TEXT + ) + """ + ) + cursor.execute( + """ + CREATE TABLE IF NOT EXISTS messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + conversation_id TEXT, + role TEXT, + content TEXT, + created_at INTEGER, + FOREIGN KEY(conversation_id) REFERENCES conversations(id) ON DELETE CASCADE + ) + """ + ) + cursor.execute( + """ + CREATE TABLE IF NOT EXISTS compressed_summaries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + conversation_id TEXT NOT NULL, + round_index INTEGER NOT NULL, + user_content TEXT NOT NULL, + assistant_content TEXT NOT NULL, + summary TEXT, + compress_status TEXT DEFAULT 'pending', + created_at INTEGER NOT NULL, + FOREIGN KEY(conversation_id) REFERENCES conversations(id) ON DELETE CASCADE + ) + """ + ) + cursor.execute( + """ + CREATE TABLE IF NOT EXISTS full_archive ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + conversation_id TEXT NOT NULL, + role TEXT NOT NULL, + content TEXT NOT NULL, + round_index INTEGER NOT NULL, + created_at INTEGER NOT NULL, + FOREIGN KEY(conversation_id) REFERENCES conversations(id) ON DELETE CASCADE + ) + """ + ) + cursor.execute( + """ + CREATE UNIQUE INDEX IF NOT EXISTS idx_full_archive_unique + ON full_archive(conversation_id, round_index, role, content) + """ + ) + + # 新增:独立的滑动窗口表 + cursor.execute( + """ + CREATE TABLE IF NOT EXISTS sliding_window ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + conversation_id TEXT NOT NULL, + round_number INTEGER NOT NULL, + user_content TEXT NOT NULL, + assistant_content TEXT NOT NULL, + assistant_thinking TEXT DEFAULT '', + compress_status TEXT DEFAULT 'active', + created_at INTEGER NOT NULL, + FOREIGN KEY(conversation_id) REFERENCES conversations(id) ON DELETE CASCADE + ) + """ + ) + cursor.execute( + """ + CREATE INDEX IF NOT EXISTS idx_sliding_window_conv_round + ON sliding_window(conversation_id, round_number DESC) + """ + ) + cursor.execute( + """ + CREATE UNIQUE INDEX IF NOT EXISTS idx_sliding_window_unique + ON sliding_window(conversation_id, round_number) + """ + ) + + # Keep legacy summary for compatibility but do not write to it anymore. + self._ensure_column(conn, "conversations", "summary TEXT") + self._ensure_column(conn, "conversations", "next_round_index INTEGER DEFAULT 0") + self._ensure_column(conn, "conversations", "compress_failed_at INTEGER") + self._ensure_column(conn, "conversations", "thread_id TEXT") + # 记录当前 thread 绑定的模型。Notion 的 thread 创建后其模型是粘住的, + # 复用同一个 thread 再发不同 model 的 transcript,上游仍按 thread 原始模型执行。 + # 因此当用户在对话中途切换模型时,需要凭此列检测并重建 thread。 + self._ensure_column(conn, "conversations", "thread_model TEXT") + self._ensure_column(conn, "messages", "thinking TEXT") + + # Backfill next_round_index for pre-migration conversations that already had history. + conn.execute( + """ + UPDATE conversations + SET next_round_index = ( + SELECT CAST(COUNT(*) / 2 AS INTEGER) + FROM messages + WHERE messages.conversation_id = conversations.id + ) + WHERE COALESCE(next_round_index, 0) = 0 + AND EXISTS ( + SELECT 1 FROM messages WHERE messages.conversation_id = conversations.id + ) + """ + ) + conn.commit() + + def _count_messages(self, conn: sqlite3.Connection, conversation_id: str) -> int: + row = conn.execute( + "SELECT COUNT(1) AS cnt FROM messages WHERE conversation_id = ?", + (conversation_id,), + ).fetchone() + return int(row["cnt"]) if row else 0 + + def _fetch_recent_messages( + self, + conn: sqlite3.Connection, + conversation_id: str, + limit: int, + ) -> List[Dict[str, str]]: + rows = conn.execute( + """ + SELECT role, content, COALESCE(thinking, '') AS thinking + FROM messages + WHERE conversation_id = ? + ORDER BY created_at DESC, id DESC + LIMIT ? + """, + (conversation_id, limit), + ).fetchall() + messages = [ + { + "role": str(r["role"] or ""), + "content": str(r["content"] or ""), + "thinking": str(r["thinking"] or ""), + } + for r in rows + ] + messages.reverse() + return messages + + def _build_assistant_memory_text(self, content: str, thinking: str) -> str: + """Build a stable assistant text for memory pairing/compression.""" + content_text = str(content or "") + if content_text.strip(): + return content_text + + thinking_text = str(thinking or "").strip() + if not thinking_text: + return self.ASSISTANT_EMPTY_PLACEHOLDER + + compact = re.sub(r"\s+", " ", thinking_text) + if len(compact) > 180: + compact = compact[:180].rstrip() + "..." + return f"[assistant_thinking_only] {compact}" + + def _normalize_window_messages(self, messages: List[Dict[str, str]]) -> List[Dict[str, str]]: + """ + 规范化窗口消息,确保 user → assistant 成对出现。 + + 修复前的问题:严格检查交替顺序,如果消息顺序不匹配期望就跳过, + 导致 AI 回复被丢失。 + + 修复后的逻辑: + 1. 保留所有有效的 user/assistant 消息 + 2. 确保 user → assistant 成对(如果不成对,跳过) + 3. 移除末尾不完整的 user 消息(确保以 assistant 结束) + """ + # 第一步:收集所有有效的消息 + normalized: List[Dict[str, str]] = [] + for msg in messages: + role = msg.get("role", "") + content = str(msg.get("content", "") or "") + thinking = str(msg.get("thinking", "") or "") + if role not in {"user", "assistant"}: + continue + + if role == "user": + if not content.strip(): + continue + normalized.append({"role": role, "content": content, "thinking": ""}) + continue + + # assistant: keep pair continuity even if visible content is empty. + normalized.append( + { + "role": role, + "content": self._build_assistant_memory_text(content, thinking), + "thinking": thinking, + } + ) + + # 第二步:确保消息是成对的 user → assistant + paired: List[Dict[str, str]] = [] + i = 0 + while i < len(normalized): + # 检查当前消息和下一条消息是否构成 user → assistant 对 + if i + 1 < len(normalized): + current = normalized[i] + next_msg = normalized[i + 1] + if current["role"] == "user" and next_msg["role"] == "assistant": + paired.extend([current, next_msg]) + i += 2 + continue + + # 如果不成对,跳过当前消息 + i += 1 + + # 第三步:确保 transcript 以 assistant 消息结束(便于追加新的 user prompt) + while paired and paired[-1]["role"] != "assistant": + paired.pop() + + return paired + + def _archive_message( + self, + conn: sqlite3.Connection, + conversation_id: str, + role: str, + content: str, + round_index: int, + created_at: int, + ) -> None: + conn.execute( + """ + INSERT OR IGNORE INTO full_archive ( + conversation_id, role, content, round_index, created_at + ) VALUES (?, ?, ?, ?, ?) + """, + (conversation_id, role, content, round_index, created_at), + ) + + def _build_dialog_block( + self, + role: str, + content: str, + notion_client: Any, + *, + gemini_mode: bool = False, + ) -> Dict[str, Any]: + if role == "assistant" and gemini_mode: + return { + "id": str(uuid.uuid4()), + "type": "agent-inference", + "value": [{"type": "text", "content": content}], + } + + block: Dict[str, Any] = { + "id": str(uuid.uuid4()), + "type": role, + "value": [[content]], + } + if role == "user": + block["userId"] = notion_client.user_id + return block + + def _build_config_block(self, model_name: str, *, gemini_mode: bool = False) -> Dict[str, Any]: + thread_type = get_thread_type(model_name) + if gemini_mode: + return { + "id": str(uuid.uuid4()), + "type": "config", + "value": { + "type": thread_type, + "model": model_name, + "modelFromUser": True, + "useWebSearch": True, + "isCustomAgent": False, + "enableAgentAutomations": False, + "enableAgentIntegrations": False, + "enableBackgroundAgents": False, + "enableCodegenIntegration": False, + "enableCustomAgents": False, + "enableExperimentalIntegrations": False, + "enableLinkedDatabases": False, + "enableAgentViewVersionHistoryTool": False, + "enableDatabaseAgents": False, + "enableAgentComments": False, + "enableAgentForms": False, + "enableAgentMakesFormulas": False, + "enableUserSessionContext": False, + "searchScopes": [{"type": "everything"}], + }, + } + return { + "id": str(uuid.uuid4()), + "type": "config", + "value": { + "type": thread_type, + "model": model_name, + "modelFromUser": True, + "useWebSearch": True, + "useReadOnlyMode": False, + "writerMode": False, + "isCustomAgent": False, + "isCustomAgentBuilder": False, + "useCustomAgentDraft": False, + "use_draft_actor_pointer": False, + "enableAgentAutomations": True, + "enableAgentIntegrations": True, + "enableCustomAgents": True, + "enableAgentDiffs": True, + "enableAgentCreateDbTemplate": True, + "enableCsvAttachmentSupport": True, + "enableDatabaseAgents": False, + "enableAgentThreadTools": False, + "enableRunAgentTool": False, + "enableAgentDashboards": False, + "enableAgentCardCustomization": True, + "enableSystemPromptAsPage": False, + "enableUserSessionContext": False, + "enableCreateAndRunThread": True, + "enableAgentGenerateImage": False, + "enableSpeculativeSearch": False, + "enableUpdatePageV2Tool": True, + "enableUpdatePageAutofixer": True, + "enableUpdatePageMarkdownTree": False, + "enableUpdatePageOrderUpdates": True, + "enableAgentSupportPropertyReorder": True, + "enableAgentVerification": False, + "useServerUndo": True, + "databaseAgentConfigMode": False, + "isOnboardingAgent": False, + "availableConnectors": [], + "customConnectorNames": [], + "searchScopes": [{"type": "everything"}], + "useSearchToolV2": False, + "useRulePrioritization": False, + "enableExperimentalIntegrations": False, + "enableAgentViewNotificationsTool": False, + "enableScriptAgent": False, + "enableScriptAgentAdvanced": False, + "enableScriptAgentSlack": False, + "enableScriptAgentMcpServers": False, + "enableScriptAgentMail": False, + "enableScriptAgentCalendar": False, + "enableScriptAgentCustomAgentTools": False, + "enableScriptAgentSearchConnectorsInCustomAgent": False, + "enableScriptAgentGoogleDriveInCustomAgent": False, + "enableQueryCalendar": False, + "enableQueryMail": False, + "enableMailExplicitToolCalls": True, + }, + } + + def _build_context_block(self, notion_client: Any, *, gemini_mode: bool = False) -> Dict[str, Any]: + surface = "ai_module" if gemini_mode else "workflows" + return { + "id": str(uuid.uuid4()), + "type": "context", + "value": { + "timezone": "Asia/Shanghai", + "userName": notion_client.user_name, + "userId": notion_client.user_id, + "userEmail": notion_client.user_email, + "spaceName": "Notion", + "spaceId": notion_client.space_id, + "spaceViewId": notion_client.space_view_id, + "currentDatetime": datetime.datetime.now().astimezone().isoformat(), + "surface": surface, + "agentName": notion_client.user_name, + }, + } + + def _fetch_recent_done_summaries(self, conn: sqlite3.Connection, conversation_id: str) -> List[str]: + rows = conn.execute( + """ + SELECT summary + FROM compressed_summaries + WHERE conversation_id = ? + AND compress_status = 'done' + AND COALESCE(summary, '') <> '' + ORDER BY round_index DESC + LIMIT ? + """, + (conversation_id, self.SUMMARY_INJECT_LIMIT), + ).fetchall() + logger.info( + "Loaded done compressed summaries for transcript injection", + extra={ + "request_info": { + "event": "memory_summary_query_done", + "conversation_id": conversation_id, + "compress_status": "done", + "row_count": len(rows), + } + }, + ) + + summaries: List[str] = [] + for row in rows: + summary = str(row["summary"] or "").strip() + if summary: + summaries.append(summary) + + summaries.reverse() + logger.info( + "Prepared summary injection payload", + extra={ + "request_info": { + "event": "memory_summary_payload_ready", + "conversation_id": conversation_id, + "summary_count": len(summaries), + } + }, + ) + return summaries + + def _has_failed_compression(self, conn: sqlite3.Connection, conversation_id: str) -> bool: + row = conn.execute( + """ + SELECT 1 + FROM compressed_summaries + WHERE conversation_id = ? + AND compress_status = 'failed' + LIMIT 1 + """, + (conversation_id,), + ).fetchone() + return row is not None + + def _search_recall_round_indices( + self, + conn: sqlite3.Connection, + conversation_id: str, + query: str, + ) -> List[int]: + keyword = (query or "").strip() + if not keyword: + return [] + + like_pattern = f"%{keyword}%" + rows = conn.execute( + """ + SELECT round_index + FROM compressed_summaries + WHERE conversation_id = ? + AND ( + user_content LIKE ? + OR assistant_content LIKE ? + OR COALESCE(summary, '') LIKE ? + ) + ORDER BY + CASE + WHEN COALESCE(summary, '') LIKE ? THEN 0 + WHEN user_content LIKE ? THEN 1 + ELSE 2 + END, + round_index DESC + LIMIT ? + """, + ( + conversation_id, + like_pattern, + like_pattern, + like_pattern, + like_pattern, + like_pattern, + self.RECALL_LIMIT, + ), + ).fetchall() + + return sorted({int(row["round_index"]) for row in rows}) + + def _format_recalled_archive( + self, + conn: sqlite3.Connection, + conversation_id: str, + round_indices: List[int], + ) -> str: + if not round_indices: + return "" + + placeholders = ",".join(["?"] * len(round_indices)) + rows = conn.execute( + f""" + SELECT round_index, role, content + FROM full_archive + WHERE conversation_id = ? + AND round_index IN ({placeholders}) + ORDER BY round_index ASC, id ASC + """, + [conversation_id, *round_indices], + ).fetchall() + + if not rows: + return "" + + grouped: Dict[int, List[sqlite3.Row]] = {} + for row in rows: + grouped.setdefault(int(row["round_index"]), []).append(row) + + role_map = {"user": "用户", "assistant": "AI", "system": "系统"} + lines: List[str] = [] + for round_index in sorted(grouped.keys()): + lines.append(f"[第 {round_index + 1} 轮]") + for row in grouped[round_index]: + label = role_map.get(str(row["role"]), str(row["role"])) + lines.append(f"{label}:{row['content']}") + lines.append("") + return "\n".join(lines).strip() + + def new_conversation(self) -> str: + conv_id = str(uuid.uuid4()) + created_at = int(datetime.datetime.now().timestamp()) + with self._get_conn() as conn: + conn.execute( + """ + INSERT INTO conversations (id, title, created_at, next_round_index) + VALUES (?, ?, ?, ?) + """, + (conv_id, "New Chat", created_at, 0), + ) + conn.commit() + logger.info( + "Conversation created", + extra={"request_info": {"event": "conversation_created", "conversation_id": conv_id}}, + ) + return conv_id + + def get_conversation_thread_id(self, conversation_id: str) -> Optional[str]: + """获取对话关联的 Notion thread_id""" + with self._get_conn() as conn: + row = conn.execute( + "SELECT thread_id FROM conversations WHERE id = ?", + (conversation_id,), + ).fetchone() + return row["thread_id"] if row and row["thread_id"] else None + + def get_conversation_thread_model(self, conversation_id: str) -> Optional[str]: + """获取当前 thread 绑定的模型名(用于检测模型切换)。""" + with self._get_conn() as conn: + row = conn.execute( + "SELECT thread_model FROM conversations WHERE id = ?", + (conversation_id,), + ).fetchone() + return row["thread_model"] if row and row["thread_model"] else None + + def clear_conversation_thread(self, conversation_id: str) -> None: + """清空 thread_id 与 thread_model,下一轮请求会创建新的 Notion thread。""" + with self._get_conn() as conn: + conn.execute( + "UPDATE conversations SET thread_id = NULL, thread_model = NULL WHERE id = ?", + (conversation_id,), + ) + conn.commit() + logger.info( + "Cleared thread binding for conversation", + extra={ + "request_info": { + "event": "thread_binding_cleared", + "conversation_id": conversation_id, + } + }, + ) + + def set_conversation_thread_id( + self, + conversation_id: str, + thread_id: str, + model_name: Optional[str] = None, + ) -> None: + """保存对话关联的 Notion thread_id 以及当前绑定的模型名。""" + with self._get_conn() as conn: + if model_name is not None: + conn.execute( + "UPDATE conversations SET thread_id = ?, thread_model = ? WHERE id = ?", + (thread_id, model_name, conversation_id), + ) + else: + conn.execute( + "UPDATE conversations SET thread_id = ? WHERE id = ?", + (thread_id, conversation_id), + ) + conn.commit() + logger.info( + "Saved thread_id for conversation", + extra={ + "request_info": { + "event": "thread_id_saved", + "conversation_id": conversation_id, + "thread_id": thread_id, + "thread_model": model_name, + } + }, + ) + + def conversation_exists(self, conversation_id: str) -> bool: + if not conversation_id: + return False + with self._get_conn() as conn: + row = conn.execute( + "SELECT 1 FROM conversations WHERE id = ?", + (conversation_id,), + ).fetchone() + return row is not None + + def add_message(self, conversation_id: str, role: str, content: str, thinking: str = "") -> None: + """ + Append a single message. + + Compatibility note: + - No compression is triggered here. + - next_round_index increments only when an assistant message follows a user message. + """ + if role not in {"user", "assistant", "system"}: + raise ValueError(f"Invalid role: {role}") + + with self._get_conn() as conn: + conv_row = conn.execute( + "SELECT id, next_round_index FROM conversations WHERE id = ?", + (conversation_id,), + ).fetchone() + if not conv_row: + raise ValueError(f"Conversation ID '{conversation_id}' does not exist.") + + next_round_index = int(conv_row["next_round_index"] or 0) + round_index = next_round_index + + previous = conn.execute( + """ + SELECT role + FROM messages + WHERE conversation_id = ? + ORDER BY created_at DESC, id DESC + LIMIT 1 + """, + (conversation_id,), + ).fetchone() + previous_role = previous["role"] if previous else None + + created_at = int(datetime.datetime.now().timestamp()) + + # 关键修复:检测并避免重复插入相同的消息 + # 检查最后一条消息是否与当前消息相同(role + content) + last_message = conn.execute( + """ + SELECT role, content + FROM messages + WHERE conversation_id = ? + ORDER BY created_at DESC, id DESC + LIMIT 1 + """, + (conversation_id,), + ).fetchone() + + if last_message and str(last_message["role"]) == role and str(last_message["content"]) == content: + logger.debug( + "Duplicate message detected, skipping insertion", + extra={ + "request_info": { + "event": "conversation_duplicate_message_skipped", + "conversation_id": conversation_id, + "role": role, + "content_length": len(content), + } + }, + ) + return + + archive_text = ( + self._build_assistant_memory_text(content, thinking) + if role == "assistant" + else content + ) + conn.execute( + """ + INSERT INTO messages (conversation_id, role, content, thinking, created_at) + VALUES (?, ?, ?, ?, ?) + """, + (conversation_id, role, content, thinking, created_at), + ) + self._archive_message(conn, conversation_id, role, archive_text, round_index, created_at) + + if role == "assistant" and previous_role == "user": + conn.execute( + "UPDATE conversations SET next_round_index = ? WHERE id = ?", + (next_round_index + 1, conversation_id), + ) + + conn.commit() + + def persist_round( + self, + conversation_id: str, + user_prompt: str, + assistant_reply: str, + assistant_thinking: str = "", + ) -> int: + """ + Persist one complete user/assistant turn and advance round index. + 同时更新滑动窗口表。 + + Returns: + int: 当前轮次号(round_index) + """ + with self._get_conn() as conn: + conv_row = conn.execute( + "SELECT id, next_round_index FROM conversations WHERE id = ?", + (conversation_id,), + ).fetchone() + if not conv_row: + raise ValueError(f"Conversation ID '{conversation_id}' does not exist.") + + round_index = int(conv_row["next_round_index"] or 0) + created_at = int(datetime.datetime.now().timestamp()) + + # 保留对 messages 表的写入(兼容性) + conn.execute( + """ + INSERT INTO messages (conversation_id, role, content, thinking, created_at) + VALUES (?, 'user', ?, '', ?) + """, + (conversation_id, user_prompt, created_at), + ) + conn.execute( + """ + INSERT INTO messages (conversation_id, role, content, thinking, created_at) + VALUES (?, 'assistant', ?, ?, ?) + """, + (conversation_id, assistant_reply, assistant_thinking, created_at), + ) + + assistant_memory_text = self._build_assistant_memory_text(assistant_reply, assistant_thinking) + self._archive_message(conn, conversation_id, "user", user_prompt, round_index, created_at) + self._archive_message( + conn, + conversation_id, + "assistant", + assistant_memory_text, + round_index, + created_at, + ) + + # 更新滑动窗口表(使用 UPSERT 确保幂等性和数据完整性) + conn.execute( + """ + INSERT INTO sliding_window ( + conversation_id, round_number, user_content, + assistant_content, assistant_thinking, compress_status, created_at + ) VALUES (?, ?, ?, ?, ?, 'active', ?) + ON CONFLICT(conversation_id, round_number) DO UPDATE SET + user_content = excluded.user_content, + assistant_content = excluded.assistant_content, + assistant_thinking = excluded.assistant_thinking, + compress_status = 'active' + """, + ( + conversation_id, + round_index, + user_prompt, + assistant_reply, + assistant_thinking, + created_at, + ), + ) + + conn.execute( + "UPDATE conversations SET next_round_index = ? WHERE id = ?", + (round_index + 1, conversation_id), + ) + conn.commit() + + return round_index + + # ==================== 滑动窗口管理 ==================== + + def update_sliding_window( + self, + conversation_id: str, + round_number: int, + user_content: str, + assistant_content: str, + assistant_thinking: str = "", + ) -> None: + """ + 更新滑动窗口:将当前轮对话插入 sliding_window 表。 + 使用 UPSERT 确保幂等性和数据完整性。 + 同时归档到 full_archive(已在 persist_round 中完成)。 + """ + created_at = int(datetime.datetime.now().timestamp()) + with self._get_conn() as conn: + conn.execute( + """ + INSERT INTO sliding_window ( + conversation_id, round_number, user_content, + assistant_content, assistant_thinking, compress_status, created_at + ) VALUES (?, ?, ?, ?, ?, 'active', ?) + ON CONFLICT(conversation_id, round_number) DO UPDATE SET + user_content = excluded.user_content, + assistant_content = excluded.assistant_content, + assistant_thinking = excluded.assistant_thinking, + compress_status = 'active' + """, + ( + conversation_id, + round_number, + user_content, + assistant_content, + assistant_thinking, + created_at, + ), + ) + conn.commit() + logger.info( + "Sliding window updated", + extra={ + "request_info": { + "event": "sliding_window_updated", + "conversation_id": conversation_id, + "round_number": round_number, + } + }, + ) + + def get_sliding_window( + self, + conn: sqlite3.Connection, + conversation_id: str, + limit_rounds: Optional[int] = None, + ) -> List[Dict[str, str]]: + """ + 获取滑动窗口内容,返回最近 N 轮对话(按 round_number 降序后反转)。 + 天然成对返回 user + assistant,不再需要 _normalize_window_messages()。 + """ + if limit_rounds is None: + limit_rounds = self.WINDOW_ROUNDS + + rows = conn.execute( + """ + SELECT round_number, user_content, assistant_content, assistant_thinking, compress_status + FROM sliding_window + WHERE conversation_id = ? AND compress_status = 'active' + ORDER BY round_number DESC + LIMIT ? + """, + (conversation_id, limit_rounds), + ).fetchall() + + # 添加调试日志(使用 INFO 级别确保可见) + logger.info( + "Retrieved sliding window data", + extra={ + "request_info": { + "event": "sliding_window_query", + "conversation_id": conversation_id, + "limit_rounds": limit_rounds, + "actual_rows": len(rows), + "round_numbers": [r["round_number"] for r in rows] if rows else [], + } + }, + ) + + if not rows: + return [] + + # 反转顺序(从旧到新),并转换为消息列表格式 + rows_list = list(rows) + rows_list.reverse() + + messages: List[Dict[str, str]] = [] + for row in rows_list: + # 添加 user 消息 + messages.append({ + "role": "user", + "content": str(row["user_content"] or ""), + "thinking": "", + }) + # 添加 assistant 消息 + assistant_text = self._build_assistant_memory_text( + str(row["assistant_content"] or ""), + str(row["assistant_thinking"] or ""), + ) + messages.append({ + "role": "assistant", + "content": assistant_text, + "thinking": str(row["assistant_thinking"] or ""), + }) + + return messages + + def cleanup_old_sliding_window( + self, + conn: sqlite3.Connection, + conversation_id: str, + keep_rounds: Optional[int] = None, + ) -> int: + """ + 清理滑动窗口中的旧数据。 + 只删除 compress_status='compressed' 的记录,确保压缩完成后才清理。 + 返回删除的记录数。 + """ + if keep_rounds is None: + keep_rounds = self.WINDOW_ROUNDS + + # 获取当前最大轮次 + max_round_row = conn.execute( + """ + SELECT MAX(round_number) AS max_round + FROM sliding_window + WHERE conversation_id = ? + """, + (conversation_id,), + ).fetchone() + max_round = int(max_round_row["max_round"] or 0) if max_round_row else 0 + + # 计算需要保留的最小轮次 + min_keep_round = max(0, max_round - keep_rounds + 1) + + # 只删除已压缩的旧数据 + result = conn.execute( + """ + DELETE FROM sliding_window + WHERE conversation_id = ? + AND round_number < ? + AND compress_status = 'compressed' + """, + (conversation_id, min_keep_round), + ) + deleted_count = result.rowcount + + if deleted_count > 0: + logger.info( + "Cleaned up old sliding window records", + extra={ + "request_info": { + "event": "sliding_window_cleanup", + "conversation_id": conversation_id, + "deleted_count": deleted_count, + "min_keep_round": min_keep_round, + } + }, + ) + + return deleted_count + + def get_sliding_window_round_count( + self, + conn: sqlite3.Connection, + conversation_id: str, + ) -> int: + """获取滑动窗口中的活跃轮数。""" + row = conn.execute( + """ + SELECT COUNT(DISTINCT round_number) AS round_count + FROM sliding_window + WHERE conversation_id = ? AND compress_status = 'active' + """, + (conversation_id,), + ).fetchone() + return int(row["round_count"] or 0) if row else 0 + + def migrate_messages_to_sliding_window( + self, + conversation_id: str, + batch_size: int = 100, + ) -> int: + """ + 将现有 messages 表中的数据迁移到 sliding_window 表。 + + Args: + conversation_id: 要迁移的对话 ID + batch_size: 每批处理的消息数 + + Returns: + int: 迁移的轮次数 + """ + with self._get_conn() as conn: + # 检查是否已有滑动窗口数据 + existing_rounds = self.get_sliding_window_round_count(conn, conversation_id) + if existing_rounds > 0: + logger.info( + "Sliding window already has data, skipping migration", + extra={ + "request_info": { + "event": "migration_skipped", + "conversation_id": conversation_id, + "existing_rounds": existing_rounds, + } + }, + ) + return 0 + + # 获取所有消息 + messages = conn.execute( + """ + SELECT role, content, COALESCE(thinking, '') AS thinking, created_at + FROM messages + WHERE conversation_id = ? + ORDER BY created_at ASC, id ASC + """, + (conversation_id,), + ).fetchall() + + if not messages: + return 0 + + # 配对 user + assistant 消息 + migrated_rounds = 0 + round_number = 0 + i = 0 + created_at = int(datetime.datetime.now().timestamp()) + + while i < len(messages): + # 查找 user 消息 + if messages[i]["role"] != "user": + i += 1 + continue + + user_content = str(messages[i]["content"] or "") + if not user_content.strip(): + i += 1 + continue + + # 查找对应的 assistant 消息 + if i + 1 >= len(messages) or messages[i + 1]["role"] != "assistant": + i += 1 + continue + + assistant_msg = messages[i + 1] + assistant_content = str(assistant_msg["content"] or "") + assistant_thinking = str(assistant_msg["thinking"] or "") + msg_created_at = int(assistant_msg["created_at"] or created_at) + + # 插入到 sliding_window + conn.execute( + """ + INSERT OR IGNORE INTO sliding_window ( + conversation_id, round_number, user_content, + assistant_content, assistant_thinking, compress_status, created_at + ) VALUES (?, ?, ?, ?, ?, 'active', ?) + """, + ( + conversation_id, + round_number, + user_content, + assistant_content, + assistant_thinking, + msg_created_at, + ), + ) + + migrated_rounds += 1 + round_number += 1 + i += 2 + + # 更新 next_round_index + if migrated_rounds > 0: + conn.execute( + """ + UPDATE conversations + SET next_round_index = ? + WHERE id = ? AND COALESCE(next_round_index, 0) < ? + """, + (round_number, conversation_id, round_number), + ) + + conn.commit() + + logger.info( + "Migrated messages to sliding window", + extra={ + "request_info": { + "event": "migration_completed", + "conversation_id": conversation_id, + "migrated_rounds": migrated_rounds, + "total_messages": len(messages), + } + }, + ) + + return migrated_rounds + + def migrate_all_conversations(self) -> Dict[str, int]: + """ + 迁移所有对话的 messages 到 sliding_window。 + + Returns: + Dict[str, int]: 每个对话 ID 对应的迁移轮次数 + """ + results: Dict[str, int] = {} + conversation_ids = self.list_conversations() + + for conv_id in conversation_ids: + try: + migrated = self.migrate_messages_to_sliding_window(conv_id) + if migrated > 0: + results[conv_id] = migrated + except Exception as e: + logger.error( + "Failed to migrate conversation", + exc_info=True, + extra={ + "request_info": { + "event": "migration_failed", + "conversation_id": conv_id, + "error": str(e), + } + }, + ) + + logger.info( + "Completed migration for all conversations", + extra={ + "request_info": { + "event": "migration_all_completed", + "total_conversations": len(conversation_ids), + "migrated_conversations": len(results), + "total_rounds": sum(results.values()), + } + }, + ) + + return results + + # ==================== 滑动窗口管理结束 ==================== + + def get_transcript_payload( + self, + notion_client: Any, + conversation_id: str, + new_prompt: str, + model_name: str, + recall_query: Optional[str] = None, + ) -> Dict[str, Any]: + with self._get_conn() as conn: + row = conn.execute( + "SELECT id FROM conversations WHERE id = ?", + (conversation_id,), + ).fetchone() + if not row: + raise ValueError(f"Conversation ID '{conversation_id}' does not exist.") + + # 强制使用新的滑动窗口表(单一数据源) + sliding_window_rounds = self.get_sliding_window_round_count(conn, conversation_id) + recent_messages = self.get_sliding_window(conn, conversation_id) + + logger.info( + "Using sliding window as single source of truth", + extra={ + "request_info": { + "event": "sliding_window_enforced", + "conversation_id": conversation_id, + "round_count": sliding_window_rounds, + "message_count": len(recent_messages), + } + }, + ) + + summaries = self._fetch_recent_done_summaries(conn, conversation_id) + memory_degraded = False + + recall_round_indices = self._search_recall_round_indices( + conn, + conversation_id, + recall_query or "", + ) + recalled_text = self._format_recalled_archive(conn, conversation_id, recall_round_indices) + + transcript: List[Dict[str, Any]] = [] + gemini_mode = is_gemini_model(model_name) + + transcript.append(self._build_config_block(model_name, gemini_mode=gemini_mode)) + transcript.append(self._build_context_block(notion_client, gemini_mode=gemini_mode)) + + # Summary injection must stay between context block and recent-window messages. + if summaries: + numbered = "\n".join(f"{idx + 1}. {item}" for idx, item in enumerate(summaries)) + transcript.append( + self._build_dialog_block( + "user", + f"以下是本次对话的历史摘要(从早到晚):\n{numbered}", + notion_client, + gemini_mode=gemini_mode, + ) + ) + transcript.append( + self._build_dialog_block( + "assistant", + "我已了解之前的对话背景。", + notion_client, + gemini_mode=gemini_mode, + ) + ) + logger.info( + "Injected compressed summaries into transcript", + extra={ + "request_info": { + "event": "memory_summary_injected", + "conversation_id": conversation_id, + "summary_count": len(summaries), + } + }, + ) + + # 添加调试日志(使用 INFO 级别确保可见) + logger.info( + "Adding recent_messages to transcript", + extra={ + "request_info": { + "event": "recent_messages_addition", + "conversation_id": conversation_id, + "recent_messages_count": len(recent_messages), + "recent_messages_preview": [ + {"role": msg.get("role"), "content_length": len(msg.get("content", ""))} + for msg in recent_messages + ] + } + }, + ) + + for msg in recent_messages: + transcript.append( + self._build_dialog_block( + msg["role"], + msg["content"], + notion_client, + gemini_mode=gemini_mode, + ) + ) + + logger.info( + "Final transcript size", + extra={ + "request_info": { + "event": "transcript_final_size", + "conversation_id": conversation_id, + "transcript_length": len(transcript), + "transcript_block_types": [block.get("type") for block in transcript] + } + }, + ) + + if recalled_text: + transcript.append( + self._build_dialog_block( + "user", + ( + "【系统召回的相关历史记录】\n" + f"{recalled_text}\n\n" + "请基于以上历史回答用户的问题。" + ), + notion_client, + gemini_mode=gemini_mode, + ) + ) + transcript.append( + self._build_dialog_block( + "assistant", + "我已查阅相关历史记录,将综合作答。", + notion_client, + gemini_mode=gemini_mode, + ) + ) + + transcript.append( + self._build_dialog_block( + "user", + new_prompt, + notion_client, + gemini_mode=gemini_mode, + ) + ) + return { + "transcript": transcript, + "memory_degraded": memory_degraded, + } + + def get_transcript(self, notion_client, conversation_id: str, new_prompt: str, model_name: str) -> list: + payload = self.get_transcript_payload( + notion_client=notion_client, + conversation_id=conversation_id, + new_prompt=new_prompt, + model_name=model_name, + recall_query=None, + ) + return payload["transcript"] + + def delete_conversation(self, conversation_id: str) -> bool: + with self._get_conn() as conn: + cursor = conn.execute("DELETE FROM conversations WHERE id = ?", (conversation_id,)) + conn.commit() + return cursor.rowcount > 0 + + def list_conversations(self) -> List[str]: + with self._get_conn() as conn: + cursor = conn.execute("SELECT id FROM conversations ORDER BY created_at DESC") + return [row["id"] for row in cursor.fetchall()] + + +async def compress_sliding_window_round( + manager: ConversationManager, + conversation_id: str, + round_number: int, +) -> bool: + """ + 压缩滑动窗口中指定轮次的对话。 + + 异步预压缩流程: + 1. 检查该轮次是否已压缩(幂等性) + 2. 标记为 'compressing' 防止并发 + 3. 调用 LLM 生成摘要 + 4. 写入 compressed_summaries + 5. 标记为 'compressed' + + Returns: + bool: 压缩是否成功 + """ + from app.summarizer import ( + SummarizerUnavailableError, + is_summarizer_configured, + summarize_turn, + ) + + try: + with manager._get_conn() as conn: + # 检查该轮次是否存在且需要压缩 + round_row = conn.execute( + """ + SELECT round_number, user_content, assistant_content, assistant_thinking, compress_status + FROM sliding_window + WHERE conversation_id = ? AND round_number = ? + """, + (conversation_id, round_number), + ).fetchone() + + if not round_row: + logger.debug( + "Sliding window round not found for compression", + extra={ + "request_info": { + "event": "sliding_window_round_not_found", + "conversation_id": conversation_id, + "round_number": round_number, + } + }, + ) + return False + + if round_row["compress_status"] != "active": + logger.debug( + "Sliding window round already compressed or compressing", + extra={ + "request_info": { + "event": "sliding_window_round_already_compressed", + "conversation_id": conversation_id, + "round_number": round_number, + "compress_status": round_row["compress_status"], + } + }, + ) + return True # 已压缩视为成功 + + # 标记为正在压缩 + conn.execute( + """ + UPDATE sliding_window + SET compress_status = 'compressing' + WHERE conversation_id = ? AND round_number = ? AND compress_status = 'active' + """, + (conversation_id, round_number), + ) + conn.commit() + + # 获取旧的压缩摘要 + with manager._get_conn() as conn: + old_summary_rows = conn.execute( + """ + SELECT summary + FROM compressed_summaries + WHERE conversation_id = ? + AND compress_status = 'done' + AND COALESCE(summary, '') <> '' + AND round_index < ? + ORDER BY round_index ASC + """, + (conversation_id, round_number), + ).fetchall() + old_summaries = [ + str(row["summary"] or "").strip() + for row in old_summary_rows + if str(row["summary"] or "").strip() + ] + + if not is_summarizer_configured(): + logger.warning( + "Skipping compression because summarizer is not configured", + extra={ + "request_info": { + "event": "sliding_window_compress_skipped_no_summarizer", + "conversation_id": conversation_id, + "round_number": round_number, + } + }, + ) + # 恢复状态 + with manager._get_conn() as conn: + conn.execute( + """ + UPDATE sliding_window + SET compress_status = 'active' + WHERE conversation_id = ? AND round_number = ? + """, + (conversation_id, round_number), + ) + conn.commit() + return False + + user_content = str(round_row["user_content"] or "") + assistant_content = manager._build_assistant_memory_text( + str(round_row["assistant_content"] or ""), + str(round_row["assistant_thinking"] or ""), + ) + + try: + summary_text = await summarize_turn( + old_summaries=old_summaries, + user_msg=user_content, + assistant_msg=assistant_content, + ) + except SummarizerUnavailableError: + logger.warning( + "Compression summary unavailable", + extra={ + "request_info": { + "event": "sliding_window_compress_summary_unavailable", + "conversation_id": conversation_id, + "round_number": round_number, + } + }, + ) + # 恢复状态以便下次重试 + with manager._get_conn() as conn: + conn.execute( + """ + UPDATE sliding_window + SET compress_status = 'active' + WHERE conversation_id = ? AND round_number = ? + """, + (conversation_id, round_number), + ) + conn.commit() + return False + except Exception: + logger.error( + "Failed to summarize sliding window round", + exc_info=True, + extra={ + "request_info": { + "event": "sliding_window_compress_summary_failed", + "conversation_id": conversation_id, + "round_number": round_number, + } + }, + ) + # 恢复状态以便下次重试 + with manager._get_conn() as conn: + conn.execute( + """ + UPDATE sliding_window + SET compress_status = 'active' + WHERE conversation_id = ? AND round_number = ? + """, + (conversation_id, round_number), + ) + conn.commit() + return False + + summary_text = summary_text.strip() + if not summary_text: + logger.warning( + "Compression summary was empty", + extra={ + "request_info": { + "event": "sliding_window_compress_summary_empty", + "conversation_id": conversation_id, + "round_number": round_number, + } + }, + ) + # 恢复状态以便下次重试 + with manager._get_conn() as conn: + conn.execute( + """ + UPDATE sliding_window + SET compress_status = 'active' + WHERE conversation_id = ? AND round_number = ? + """, + (conversation_id, round_number), + ) + conn.commit() + return False + + # 写入压缩摘要并更新状态 + created_at = int(datetime.datetime.now().timestamp()) + with manager._get_conn() as conn: + conn.execute( + """ + INSERT INTO compressed_summaries ( + conversation_id, round_index, user_content, + assistant_content, summary, compress_status, created_at + ) VALUES (?, ?, ?, ?, ?, 'done', ?) + """, + ( + conversation_id, + round_number, + user_content, + assistant_content, + summary_text, + created_at, + ), + ) + conn.execute( + """ + UPDATE sliding_window + SET compress_status = 'compressed' + WHERE conversation_id = ? AND round_number = ? + """, + (conversation_id, round_number), + ) + conn.commit() + + logger.info( + "Sliding window round compressed successfully", + extra={ + "request_info": { + "event": "sliding_window_round_compressed", + "conversation_id": conversation_id, + "round_number": round_number, + "summary_length": len(summary_text), + } + }, + ) + return True + + except Exception: + logger.error( + "compress_sliding_window_round crashed", + exc_info=True, + extra={ + "request_info": { + "event": "sliding_window_compress_crashed", + "conversation_id": conversation_id, + "round_number": round_number, + } + }, + ) + # 尝试恢复状态 + try: + with manager._get_conn() as conn: + conn.execute( + """ + UPDATE sliding_window + SET compress_status = 'active' + WHERE conversation_id = ? AND round_number = ? + """, + (conversation_id, round_number), + ) + conn.commit() + except Exception: + pass + return False + + +async def compress_round_if_needed(manager: ConversationManager, conversation_id: str) -> None: + """ + Move old turns out of sliding window, archive raw text, and summarize with LLM. + + 优先处理新的 sliding_window 表,兼容旧的 messages 表。 + + Any failure is logged only and never raised to request path. + """ + from app.summarizer import ( + SummarizerUnavailableError, + is_summarizer_configured, + summarize_turn, + ) + + try: + # 优先处理新的滑动窗口表 + with manager._get_conn() as conn: + sliding_round_count = manager.get_sliding_window_round_count(conn, conversation_id) + if sliding_round_count > manager.WINDOW_ROUNDS: + # 找到需要压缩的轮次 + max_round_row = conn.execute( + """ + SELECT MAX(round_number) AS max_round + FROM sliding_window + WHERE conversation_id = ? AND compress_status = 'active' + """, + (conversation_id,), + ).fetchone() + max_round = int(max_round_row["max_round"] or 0) if max_round_row else 0 + + # 计算需要压缩的最小轮次 + min_compress_round = max(0, max_round - manager.WINDOW_ROUNDS + 1) + + # 获取需要压缩的轮次 + rounds_to_compress = conn.execute( + """ + SELECT round_number + FROM sliding_window + WHERE conversation_id = ? + AND compress_status = 'active' + AND round_number < ? + ORDER BY round_number ASC + """, + (conversation_id, min_compress_round), + ).fetchall() + + for row in rounds_to_compress: + round_number = int(row["round_number"]) + await compress_sliding_window_round(manager, conversation_id, round_number) + + # 清理已压缩的旧数据 + manager.cleanup_old_sliding_window(conn, conversation_id) + return + + # 兼容旧的 messages 表(如果滑动窗口为空) + while True: + with manager._get_conn() as conn: + conv_row = conn.execute( + """ + SELECT id, next_round_index + FROM conversations + WHERE id = ? + """, + (conversation_id,), + ).fetchone() + if not conv_row: + return + + message_count = manager._count_messages(conn, conversation_id) + if message_count <= manager.WINDOW_SIZE: + return + + oldest_rows = conn.execute( + """ + SELECT id, role, content, COALESCE(thinking, '') AS thinking, created_at + FROM messages + WHERE conversation_id = ? + ORDER BY created_at ASC, id ASC + LIMIT 2 + """, + (conversation_id,), + ).fetchall() + if len(oldest_rows) < 2: + return + + oldest_user = oldest_rows[0] + oldest_assistant = oldest_rows[1] + if oldest_user["role"] != "user" or oldest_assistant["role"] != "assistant": + logger.warning( + "Skip compression due to non user/assistant oldest pair", + extra={ + "request_info": { + "event": "conversation_compress_skipped", + "conversation_id": conversation_id, + "roles": [oldest_user["role"], oldest_assistant["role"]], + } + }, + ) + return + + next_round_index = int(conv_row["next_round_index"] or 0) + rounds_in_messages = max(message_count // 2, 1) + round_index = max(next_round_index - rounds_in_messages, 0) + created_at = int(datetime.datetime.now().timestamp()) + + old_summary_rows = conn.execute( + """ + SELECT summary + FROM compressed_summaries + WHERE conversation_id = ? + AND compress_status = 'done' + AND COALESCE(summary, '') <> '' + AND round_index < ? + ORDER BY round_index ASC + """, + (conversation_id, round_index), + ).fetchall() + old_summaries = [str(row["summary"] or "").strip() for row in old_summary_rows if str(row["summary"] or "").strip()] + logger.info( + "Prepared cumulative old summaries for turn compression", + extra={ + "request_info": { + "event": "memory_cumulative_summaries_ready", + "conversation_id": conversation_id, + "current_round_index": round_index, + "old_summary_count": len(old_summaries), + } + }, + ) + + candidate = { + "user_id": int(oldest_user["id"]), + "assistant_id": int(oldest_assistant["id"]), + "user_content": str(oldest_user["content"]), + "assistant_content": manager._build_assistant_memory_text( + str(oldest_assistant["content"]), + str(oldest_assistant["thinking"]), + ), + "user_created_at": int(oldest_user["created_at"] or created_at), + "assistant_created_at": int(oldest_assistant["created_at"] or created_at), + "round_index": round_index, + "created_at": created_at, + } + + if not is_summarizer_configured(): + logger.warning( + "Skipping compression because summarizer is not configured", + extra={ + "request_info": { + "event": "conversation_compress_skipped_no_summarizer", + "conversation_id": conversation_id, + "message_count": message_count, + } + }, + ) + return + + try: + summary_text = await summarize_turn( + old_summaries=old_summaries, + user_msg=candidate["user_content"], + assistant_msg=candidate["assistant_content"], + ) + except SummarizerUnavailableError: + logger.warning( + "Compression summary unavailable; active messages retained", + extra={ + "request_info": { + "event": "conversation_compress_summary_unavailable", + "conversation_id": conversation_id, + "round_index": candidate["round_index"], + } + }, + ) + return + except Exception: + logger.error( + "Failed to summarize compressed round", + exc_info=True, + extra={ + "request_info": { + "event": "conversation_compress_summary_failed", + "conversation_id": conversation_id, + "round_index": candidate["round_index"], + } + }, + ) + return + else: + summary_text = summary_text.strip() + if not summary_text: + logger.warning( + "Compression summary was empty; active messages retained", + extra={ + "request_info": { + "event": "conversation_compress_summary_empty", + "conversation_id": conversation_id, + "round_index": candidate["round_index"], + } + }, + ) + return + + with manager._get_conn() as conn: + current_message_count = manager._count_messages(conn, conversation_id) + if current_message_count <= manager.WINDOW_SIZE: + return + + current_pair = conn.execute( + """ + SELECT id, role + FROM messages + WHERE id IN (?, ?) + ORDER BY created_at ASC, id ASC + """, + (candidate["user_id"], candidate["assistant_id"]), + ).fetchall() + if ( + len(current_pair) != 2 + or int(current_pair[0]["id"]) != candidate["user_id"] + or int(current_pair[1]["id"]) != candidate["assistant_id"] + or current_pair[0]["role"] != "user" + or current_pair[1]["role"] != "assistant" + ): + logger.info( + "Compression candidate changed before commit; retrying with fresh snapshot", + extra={ + "request_info": { + "event": "conversation_compress_candidate_stale", + "conversation_id": conversation_id, + "round_index": candidate["round_index"], + } + }, + ) + continue + + conn.execute( + "DELETE FROM messages WHERE id IN (?, ?)", + (candidate["user_id"], candidate["assistant_id"]), + ) + conn.execute( + """ + INSERT INTO compressed_summaries ( + conversation_id, + round_index, + user_content, + assistant_content, + summary, + compress_status, + created_at + ) + VALUES (?, ?, ?, ?, ?, 'done', ?) + """, + ( + conversation_id, + candidate["round_index"], + candidate["user_content"], + candidate["assistant_content"], + summary_text, + candidate["created_at"], + ), + ) + manager._archive_message( + conn, + conversation_id, + "user", + candidate["user_content"], + candidate["round_index"], + candidate["user_created_at"], + ) + manager._archive_message( + conn, + conversation_id, + "assistant", + candidate["assistant_content"], + candidate["round_index"], + candidate["assistant_created_at"], + ) + conn.execute( + """ + UPDATE conversations + SET compress_failed_at = NULL + WHERE id = ? + """, + (conversation_id,), + ) + conn.commit() + except Exception: + logger.error( + "compress_round_if_needed crashed", + exc_info=True, + extra={ + "request_info": { + "event": "conversation_compress_task_crashed", + "conversation_id": conversation_id, + } + }, + ) + + +# --- System prompt sanitization ------------------------------------------------- +# +# Notion AI often rejects prompts that look like identity hijacking +# ("You are opencode...", "Act as Cursor", etc.). Strip known agent identity +# openers (allowlist) and reframe the rest as user preferences. +# Prefer allowlist matching over broad "You are *" so legitimate instructions +# like "You are a senior engineer. Prefer type hints." are kept. + +_KNOWN_AGENT_NAMES = ( + r"opencode|notion2api|claude\s*code|aider|cursor|cline|continue|roo|kilo|" + r"trae|windsurf|copilot|codex|gemini\s*cli|your own coding assistant" +) + +_IDENTITY_LINE_PATTERNS = [ + re.compile(rf"(?im)^you are\s+(?:{_KNOWN_AGENT_NAMES})\b.*$"), + re.compile(r"(?im)^your name is\s+.+?[.!]?$"), + re.compile(rf"(?im)^act as\s+(?:{_KNOWN_AGENT_NAMES})\b.*$"), + re.compile(rf"(?im)^you are called\s+(?:{_KNOWN_AGENT_NAMES})\b.*$"), + re.compile(rf"(?im)^you are powered by\s+(?:{_KNOWN_AGENT_NAMES})\b.*$"), +] + +_INLINE_IDENTITY_PATTERN = re.compile( + rf"(?i)\byou are\s+(?:{_KNOWN_AGENT_NAMES})\b[^.!\n]*[.!]?" +) + + +def sanitize_system_prompt_for_notion(raw: str) -> str: + """ + Strip known identity-asserting phrases from a client system prompt. + + Returns surviving instructions, or empty string if nothing meaningful remains. + """ + if not raw or not raw.strip(): + return "" + + text = raw.strip() + text = text.replace("\u2019", "'").replace("\u2018", "'") + text = text.replace("\u201c", '"').replace("\u201d", '"') + text = _INLINE_IDENTITY_PATTERN.sub("", text) + + kept_lines: list[str] = [] + for line in text.splitlines(): + cleaned = line + for pat in _IDENTITY_LINE_PATTERNS: + cleaned = pat.sub("", cleaned).strip() + cleaned = _INLINE_IDENTITY_PATTERN.sub("", cleaned).strip() + if cleaned: + kept_lines.append(cleaned) + + cleaned = "\n".join(kept_lines).strip() + cleaned = re.sub(r"\n{3,}", "\n\n", cleaned) + return cleaned + + +def reframe_system_prompt_for_notion(raw: str) -> str: + """ + Produce text to prepend to the user message when a client sends a system prompt. + """ + cleaned = sanitize_system_prompt_for_notion(raw) + if not cleaned: + return "" + return ( + "The user is working inside a developer tool and has shared the " + "following guidelines for how they'd like you to assist with this " + "request. Treat these as the user's preferences and context:\n\n" + f"{cleaned}" + ) + + +def build_lite_transcript(user_prompt: str, model_name: str) -> list[dict[str, Any]]: + """构建 Lite 模式的最简 transcript(只有 config + user)""" + from app.model_registry import get_notion_model, get_thread_type + import uuid + + notion_model = get_notion_model(model_name) + thread_type = get_thread_type(model_name) + + return [ + { + "id": str(uuid.uuid4()), + "type": "config", + "value": { + "type": thread_type, + "model": notion_model, + "modelFromUser": True, + } + }, + { + "id": str(uuid.uuid4()), + "type": "user", + "value": [[user_prompt]] + } + ] + + +def build_standard_transcript( + messages: list[dict[str, Any]], + model_name: str, + account: dict +) -> list[dict[str, Any]]: + """ + 构建 Standard 模式的 transcript(完整上下文) + + Args: + messages: OpenAI 格式的 messages 数组(完整历史) + model_name: 模型名称 + account: 账号信息字典,包含 user_id, space_id 等 + + Returns: + Notion transcript 数组 + + 参考:notion-2api 项目的实现 + """ + from app.model_registry import get_notion_model, get_thread_type + import uuid + from datetime import datetime + notion_model = get_notion_model(model_name) + thread_type = get_thread_type(model_name) + + # 基础 transcript:config + context + transcript = [ + { + "id": str(uuid.uuid4()), + "type": "config", + "value": { + "type": thread_type, + "model": notion_model, + "modelFromUser": True, + "useWebSearch": True, + } + }, + { + "id": str(uuid.uuid4()), + "type": "context", + "value": { + "timezone": "Asia/Shanghai", + "currentDatetime": datetime.now().astimezone().isoformat(), + "userId": account.get("user_id", ""), + "spaceId": account.get("space_id", ""), + } + } + ] + + # 收集所有 system 消息 + system_instructions = [] + user_messages = [] + + for msg in messages: + role = msg.get("role") + content = msg.get("content", "") + + if role == "system": + system_instructions.append(content) + elif role == "user": + user_messages.append(content) + elif role == "assistant": + # assistant 消息单独处理 + transcript.append({ + "id": str(uuid.uuid4()), + "type": "agent-inference", + "value": [ + { + "type": "text", + "content": content + } + ] + }) + + # 将 system 指令合并到第一条 user 消息(与 Lite/Heavy 模式保持一致) + if user_messages: + first_user_content = user_messages[0] + if system_instructions: + merged_system = "\n".join(system_instructions) + reframed = reframe_system_prompt_for_notion(merged_system) + if reframed: + first_user_content = f"{reframed}\n\n{first_user_content}" + + transcript.append({ + "id": str(uuid.uuid4()), + "type": "user", + "value": [[first_user_content]], + "userId": account.get("user_id", ""), + "createdAt": datetime.now().astimezone().isoformat() + }) + + # 添加剩余的 user 消息 + for content in user_messages[1:]: + transcript.append({ + "id": str(uuid.uuid4()), + "type": "user", + "value": [[content]], + "userId": account.get("user_id", ""), + "createdAt": datetime.now().astimezone().isoformat() + }) + + return transcript diff --git a/app/limiter.py b/app/limiter.py new file mode 100644 index 0000000..65aa4e4 --- /dev/null +++ b/app/limiter.py @@ -0,0 +1,26 @@ +import os + +from slowapi import Limiter +from slowapi.util import get_remote_address +from app.config import is_lite_mode, is_standard_mode + +# DISABLE_RATE_LIMIT=True 时关闭限流(调试用) +_disable_flag = os.getenv("DISABLE_RATE_LIMIT", "").strip().lower() +_rate_limit_disabled = _disable_flag == "true" + +# 根据 APP_MODE 动态设置速率限制 +# Lite 模式:30/minute(单轮问答响应快,3-5秒/次) +# Standard 模式:25/minute(完整上下文,支持 thinking 和搜索) +# Heavy 模式:20/minute(需要数据库操作,相对慢一些) +if is_lite_mode(): + default_limit = "30/minute" +elif is_standard_mode(): + default_limit = "25/minute" +else: + default_limit = "20/minute" + +limiter = Limiter( + key_func=get_remote_address, + default_limits=[] if _rate_limit_disabled else [default_limit], + enabled=not _rate_limit_disabled, +) diff --git a/app/logger.py b/app/logger.py new file mode 100644 index 0000000..8fc3268 --- /dev/null +++ b/app/logger.py @@ -0,0 +1,41 @@ +import logging +import json +import time +from datetime import datetime + +class JsonFormatter(logging.Formatter): + """自定义 JSON 格式化器""" + def format(self, record): + log_record = { + "timestamp": datetime.fromtimestamp(record.created).isoformat(), + "level": record.levelname, + "message": record.getMessage(), + } + + # 提取自定义 extra 字段 + if hasattr(record, "request_info"): + log_record.update(record.request_info) + + # 如果有异常,记录 trace + if record.exc_info: + log_record["exception"] = self.formatException(record.exc_info) + + return json.dumps(log_record, ensure_ascii=False) + +def setup_logger(name="notion_opus"): + """配置并返回单例全局 logger""" + logger = logging.getLogger(name) + + # 防止重复添加 handler + if not logger.handlers: + logger.setLevel(logging.INFO) + + console_handler = logging.StreamHandler() + console_handler.setFormatter(JsonFormatter()) + + logger.addHandler(console_handler) + + return logger + +# 全局单例 logger 实例 +logger = setup_logger() diff --git a/app/model_registry.py b/app/model_registry.py new file mode 100644 index 0000000..4cb2b28 --- /dev/null +++ b/app/model_registry.py @@ -0,0 +1,138 @@ +MODEL_MAP: dict[str, str] = { + "gpt-5.6-sol": "orange-mousse", + "gpt-5.6-terra": "orchid-muffin", + "gpt-5.6-luna": "olive-jellyroll", + "gpt-5.4": "oval-kumquat-medium", + "gpt-5.5": "opal-quince-medium", + "gemini-3.5flash": "vertex-gemini-3.5-flash", + "claude-sonnet4.6": "almond-croissant-low", + "claude-sonnet5": "angel-cake-high", + "claude-opus4.6": "avocado-froyo-medium", + "claude-opus4.7": "apricot-sorbet-high", + "claude-opus4.8": "ambrosia-tart-high", + "claude-opus5": "agave-flan", + "kimi-2.7": "fireworks-kimi-k2.7", + "deepseek-v4pro": "baseten-deepseek-v4-pro", + "glm-5.2": "baseten-glm-5.2", + "grok-4.3": "xigua-mochi-medium", + "spacexai-4.5": "strawberry-whoopiepie", + "grok-build0.1": "xinomavro-cake", + "gemini-3.1pro": "galette-medium-thinking", + "claude-haiku4.5": "anthropic-haiku-4.5", + "fable-5": "acai-budino-high", + "gemini-3flash": "gingerbread", + "gpt-6-astra": "orlando-quinn", +} + +NOTION_MODEL_REVERSE_MAP: dict[str, str] = {value: key for key, value in MODEL_MAP.items()} + +DISPLAY_NAMES: dict[str, str] = { + "gpt-5.6-sol": "GPT-5.6 Sol", + "gpt-5.6-terra": "GPT-5.6 Terra", + "gpt-5.6-luna": "GPT-5.6 Luna", + "gpt-5.4": "GPT-5.4", + "gpt-5.5": "GPT-5.5", + "gemini-3.5flash": "Gemini 3.5 Flash", + "claude-sonnet4.6": "Sonnet 4.6", + "claude-sonnet5": "Sonnet 5", + "claude-opus4.6": "Opus 4.6", + "claude-opus4.7": "Opus 4.7", + "claude-opus4.8": "Opus 4.8", + "claude-opus5": "Opus 5", + "kimi-2.7": "Kimi K2.7 Code", + "deepseek-v4pro": "DeepSeek V4 Pro", + "glm-5.2": "GLM 5.2", + "grok-4.3": "Grok 4.3", + "spacexai-4.5": "SpaceXAI 4.5", + "grok-build0.1": "Grok Build 0.1", + "gemini-3.1pro": "Gemini 3.1 Pro", + "claude-haiku4.5": "Haiku 4.5", + "fable-5": "Fable 5", + "gemini-3flash": "Gemini 3 Flash", + "gpt-6-astra": "GPT-6 Astra", +} + +MODEL_ICONS: dict[str, str] = { + "gpt-5.6-sol": "⚙", + "gpt-5.6-terra": "⚙", + "gpt-5.6-luna": "⚙", + "gpt-5.4": "⚙", + "gpt-5.5": "⚙", + "gemini-3.5flash": "✦", + "claude-sonnet4.6": "✳️", + "claude-sonnet5": "✳️", + "claude-opus4.6": "✳️", + "claude-opus4.7": "✳️", + "claude-opus4.8": "✳️", + "claude-opus5": "✳️", + "kimi-2.7": "🌙", + "deepseek-v4pro": "🐋", + "glm-5.2": "◆", + "grok-4.3": "⚡", + "spacexai-4.5": "⚡", + "grok-build0.1": "⚡", + "gemini-3.1pro": "✦", + "claude-haiku4.5": "✳️", + "fable-5": "◇", + "gemini-3flash": "✦", + "gpt-6-astra": "⚙", +} + +# 默认使用 Sonnet 4.6(速度和质量的最佳平衡) +DEFAULT_MODEL = "claude-sonnet4.6" + + +def get_notion_model(model_name: str) -> str: + return MODEL_MAP.get(model_name, MODEL_MAP[DEFAULT_MODEL]) + + +# 需要走 markdown-chat 的 Notion 内部代号(vertex- 前缀的模型) +# Gemini 3.1 Pro (galette-medium-thinking) 已改为 workflow,不再走 markdown-chat +MARKDOWN_CHAT_MODELS: set[str] = { + "vertex-gemini-3.5-flash", +} + + +def is_gemini_model(model_name: str) -> bool: + """判断是否为 Gemini 系列模型(用于 config block 构建等)""" + standard_name = get_standard_model(model_name) + if standard_name.startswith("gemini-"): + return True + notion_model = get_notion_model(standard_name) + return notion_model.startswith("vertex-") or notion_model.startswith("galette-") + + +def get_thread_type(model_name: str) -> str: + """ + 根据模型确定 Notion thread type。 + 只有 vertex- 前缀的模型走 markdown-chat,其余全部走 workflow。 + """ + standard_name = get_standard_model(model_name) + notion_model = get_notion_model(standard_name) + if notion_model in MARKDOWN_CHAT_MODELS: + return "markdown-chat" + return "workflow" + + +def get_standard_model(model_name: str) -> str: + if model_name in MODEL_MAP: + return model_name + return NOTION_MODEL_REVERSE_MAP.get(model_name, DEFAULT_MODEL) + + +def list_available_models() -> list[str]: + return list(MODEL_MAP.keys()) + + +def is_supported_model(model_name: str) -> bool: + return model_name in MODEL_MAP + + +def get_display_name(model_name: str) -> str: + standard_name = get_standard_model(model_name) + return DISPLAY_NAMES.get(standard_name, standard_name) + + +def get_model_icon(model_name: str) -> str: + standard_name = get_standard_model(model_name) + return MODEL_ICONS.get(standard_name, "") diff --git a/app/notion_client.py b/app/notion_client.py new file mode 100644 index 0000000..8fcf068 --- /dev/null +++ b/app/notion_client.py @@ -0,0 +1,410 @@ +import os +import threading +import time +import uuid +from typing import Any, Generator, Optional + +import cloudscraper +import requests +import urllib3 + +from app.logger import logger +from app.model_registry import get_notion_model +from app.stream_parser import parse_stream + +# 禁用 SSL 警告 +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +# 可通过环境变量覆盖 Notion 客户端版本号(Notion 更新后可能需要同步) +NOTION_CLIENT_VERSION = os.getenv("NOTION_CLIENT_VERSION", "23.13.20260228.0625") + +# Notion 站点根地址(区域镜像 / 反代时可覆盖);未设置时保持官方默认 +NOTION_URL = os.getenv("NOTION_URL", "https://www.notion.so").rstrip("/") + + +class NotionUpstreamError(RuntimeError): + """Notion 上游请求失败或返回异常内容。""" + + def __init__( + self, + message: str, + *, + status_code: Optional[int] = None, + retriable: bool = True, + response_excerpt: str = "", + ): + super().__init__(message) + self.status_code = status_code + self.retriable = retriable + self.response_excerpt = response_excerpt + + +class NotionOpusAPI: + def __init__(self, account_config: dict): + """ + 从单组账号配置初始化 Notion 客户端。 + account_config 需要包含 token_v2, space_id, user_id, space_view_id, user_name, user_email + """ + self.token_v2 = account_config.get("token_v2", "") + self.space_id = account_config.get("space_id", "") + self.user_id = account_config.get("user_id", "") + self.space_view_id = account_config.get("space_view_id", "") + self.user_name = account_config.get("user_name", "user") + self.user_email = account_config.get("user_email", "") + self.cookies = account_config.get("cookies", {}) + if not isinstance(self.cookies, dict): + self.cookies = {} + self.cookies["token_v2"] = self.token_v2 + + self.url = f"{NOTION_URL}/api/v3/runInferenceTranscript" + self.delete_url = f"{NOTION_URL}/api/v3/saveTransactions" + self.account_key = self.user_email or self.user_id or "unknown-account" + + # 复用 cloudscraper 实例:保留 Cloudflare challenge cookie,避免每次请求都重新过验证 + self._scraper = cloudscraper.create_scraper() + self._scraper_lock = threading.Lock() + + def _build_cookie_header(self) -> str: + cookie_jar = self.cookies.copy() + cookie_jar["notion_user_id"] = self.user_id + return "; ".join(f"{name}={value}" for name, value in cookie_jar.items() if value) + + def _to_notion_transcript(self, transcript: list[dict[str, Any]]) -> list[dict[str, Any]]: + converted: list[dict[str, Any]] = [] + for block in transcript: + if block.get("type") != "config": + converted.append(block) + continue + + value = block.get("value") + if not isinstance(value, dict): + converted.append(block) + continue + + notion_block = dict(block) + notion_value = dict(value) + notion_value["model"] = get_notion_model(str(value.get("model", "") or "")) + notion_block["value"] = notion_value + converted.append(notion_block) + return converted + + def _resolve_thread_type(self, notion_transcript: list[dict[str, Any]]) -> str: + for block in notion_transcript: + if block.get("type") != "config": + continue + value = block.get("value") + if isinstance(value, dict): + thread_type = str(value.get("type", "") or "").strip() + if thread_type: + return thread_type + return "workflow" + + def _resolve_request_profile(self, thread_type: str) -> dict[str, Any]: + is_markdown_chat = thread_type == "markdown-chat" + return { + "thread_type": thread_type, + "create_thread": not is_markdown_chat, + "is_partial_transcript": is_markdown_chat, + "precreate_thread": is_markdown_chat, + "include_debug_overrides": True, + } + + def _build_thread_headers(self) -> dict[str, str]: + return { + "content-type": "application/json", + "cookie": self._build_cookie_header(), + "x-notion-active-user-header": self.user_id, + "x-notion-space-id": self.space_id, + } + + def _create_thread(self, thread_id: str, thread_type: str) -> bool: + payload = { + "requestId": str(uuid.uuid4()), + "transactions": [ + { + "id": str(uuid.uuid4()), + "spaceId": self.space_id, + "operations": [ + { + "pointer": {"table": "thread", "id": thread_id, "spaceId": self.space_id}, + "path": [], + "command": "set", + "args": { + "id": thread_id, + "version": 1, + "parent_id": self.space_id, + "parent_table": "space", + "space_id": self.space_id, + "created_time": int(time.time() * 1000), + "created_by_id": self.user_id, + "created_by_table": "notion_user", + "messages": [], + "data": {}, + "alive": True, + "type": thread_type, + }, + } + ], + } + ], + } + try: + resp = requests.post( + self.delete_url, + json=payload, + headers=self._build_thread_headers(), + timeout=20, + ) + if resp.status_code == 200: + return True + logger.warning( + "Pre-create thread failed", + extra={ + "request_info": { + "event": "thread_precreate_failed", + "thread_id": thread_id, + "thread_type": thread_type, + "status": resp.status_code, + } + }, + ) + except Exception: + logger.warning( + "Pre-create thread raised exception", + exc_info=True, + extra={ + "request_info": { + "event": "thread_precreate_error", + "thread_id": thread_id, + "thread_type": thread_type, + } + }, + ) + return False + + def delete_thread(self, thread_id: str) -> None: + """ + 通过 saveTransactions 接口将指定 thread 的 alive 状态设为 False, + 从而清理 Notion 主页面上的对话记录。 + 此方法设计为在后台线程中调用,不影响主流输出。 + """ + headers = self._build_thread_headers() + payload = { + "requestId": str(uuid.uuid4()), + "transactions": [ + { + "id": str(uuid.uuid4()), + "spaceId": self.space_id, + "operations": [ + { + "pointer": { + "table": "thread", + "id": thread_id, + "spaceId": self.space_id, + }, + "command": "update", + "path": [], + "args": {"alive": False}, + } + ], + } + ], + } + try: + resp = requests.post(self.delete_url, json=payload, headers=headers, timeout=15) + if resp.status_code == 200: + logger.info( + "Thread auto-deleted from Notion home", + extra={"request_info": {"event": "thread_deleted", "thread_id": thread_id}}, + ) + else: + logger.warning( + f"Thread deletion failed: HTTP {resp.status_code}", + extra={"request_info": {"event": "thread_delete_failed", "thread_id": thread_id, "status": resp.status_code}}, + ) + except Exception as exc: + logger.warning( + f"Thread deletion raised an exception: {exc}", + extra={"request_info": {"event": "thread_delete_error", "thread_id": thread_id}}, + ) + + def stream_response(self, transcript: list, thread_id: Optional[str] = None) -> Generator[dict[str, Any], None, None]: + """ + 发起 Notion API 请求并返回结构化流生成器。 + 接收完整的 transcript 列表作为参数。 + + Args: + transcript: 对话历史记录列表 + thread_id: 可选的已有 thread_id。如果提供,将重用该线程以保持上下文 + """ + if not isinstance(transcript, list) or not transcript: + raise ValueError("Invalid transcript payload: transcript must be a non-empty list.") + + notion_transcript = self._to_notion_transcript(transcript) + thread_type = self._resolve_thread_type(notion_transcript) + request_profile = self._resolve_request_profile(thread_type) + + # 如果没有提供 thread_id,创建新的;否则重用已有的 + should_create_thread = thread_id is None + thread_id = thread_id or str(uuid.uuid4()) + trace_id = str(uuid.uuid4()) + response = None + + # 保存 thread_id 以便外部访问 + self.current_thread_id = thread_id + + if request_profile["precreate_thread"] and should_create_thread: + if not self._create_thread(thread_id, thread_type): + should_create_thread = True + request_profile["create_thread"] = True + request_profile["is_partial_transcript"] = False + elif not should_create_thread: + # 如果重用已有线程,不要创建新线程 + request_profile["create_thread"] = False + # 关键修复:设置 is_partial_transcript=True,让 Notion 接受客户端的历史消息 + request_profile["is_partial_transcript"] = True + + # 把 cookie 直接放进 header,绕过 cloudscraper 的 cookie jar + # (cookie jar 可能被 Cloudflare challenge 写入含非 ASCII 字符的 cookie,导致编码错误) + cookie_header = self._build_cookie_header() + + # ВАЖНО (2026-09-06): апстрим отдаёт пустой стрим без браузерного фингерпринта + # (проверено A/B: те же payload/token/IP — с sec-fetch + свежим UA идёт NDJSON, без них пусто). + headers = { + "Content-Type": "application/json", + "Accept": "application/x-ndjson", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36", + "x-notion-space-id": self.space_id, + "x-notion-active-user-header": self.user_id, + "notion-audit-log-platform": "web", + "notion-client-version": NOTION_CLIENT_VERSION, + "origin": NOTION_URL, + "referer": f"{NOTION_URL}/chat", + "sec-ch-ua": '"Chromium";v="152", "Not?A_Brand";v="24", "Google Chrome";v="152"', + "sec-ch-ua-mobile": "?0", + "sec-ch-ua-platform": '"Linux"', + "sec-fetch-dest": "empty", + "sec-fetch-mode": "cors", + "sec-fetch-site": "same-origin", + "cookie": cookie_header, + } + + payload = { + "traceId": trace_id, + "spaceId": self.space_id, + "threadId": thread_id, + "threadType": thread_type, + "createThread": request_profile["create_thread"], + "generateTitle": True, + "saveAllThreadOperations": True, + "setUnreadState": True, + "isPartialTranscript": request_profile["is_partial_transcript"], + "asPatchResponse": True, + "isUserInAnySalesAssistedSpace": False, + "isSpaceSalesAssisted": False, + "threadParentPointer": { + "table": "space", + "id": self.space_id, + "spaceId": self.space_id, + }, + "transcript": notion_transcript, + } + if request_profile["include_debug_overrides"]: + payload["debugOverrides"] = { + "emitAgentSearchExtractedResults": True, + "cachedInferences": {}, + "annotationInferences": {}, + "emitInferences": False, + } + + logger.info( + "Dispatching request to Notion upstream", + extra={ + "request_info": { + "event": "notion_upstream_request", + "trace_id": trace_id, + "thread_id": thread_id, + "thread_type": thread_type, + "create_thread": bool(request_profile["create_thread"]), + "is_partial_transcript": bool(request_profile["is_partial_transcript"]), + "account": self.account_key, + "space_id": self.space_id, + } + }, + ) + + try: + with self._scraper_lock: + scraper = self._scraper + scraper.cookies.clear() + response = scraper.post( + self.url, + headers=headers, + json=payload, + stream=True, + timeout=(15, 120), + ) + if response.status_code == 403: + # Cloudflare challenge 可能过期,重建 scraper 后重试一次 + response.close() + logger.warning( + "Got 403, rebuilding cloudscraper to refresh Cloudflare challenge", + extra={"request_info": {"event": "cloudflare_challenge_refresh", "account": self.account_key}}, + ) + new_scraper = cloudscraper.create_scraper() + with self._scraper_lock: + self._scraper = new_scraper + response = new_scraper.post( + self.url, + headers=headers, + json=payload, + stream=True, + timeout=(15, 120), + ) + if response.status_code != 200: + excerpt = (response.text or "").strip().replace("\n", " ")[:300] + # 429 和 5xx 都允许重试(换账号或等待后重试) + retriable = response.status_code >= 500 or response.status_code == 429 + raise NotionUpstreamError( + f"Notion upstream returned HTTP {response.status_code}.", + status_code=response.status_code, + retriable=retriable, + response_excerpt=excerpt, + ) + + emitted = False + for chunk in parse_stream(response): + emitted = True + yield chunk + + if not emitted: + raise NotionUpstreamError( + "Notion upstream returned an empty stream.", + status_code=502, + retriable=True, + ) + + # 流结束后,不再自动删除 thread + # 原因:Notion API 的 workflow 模式依赖于服务器端保存的对话历史 + # 删除 thread 会导致后续请求无法获取历史消息(AI 失忆) + # 保持 thread 存活可以维持对话上下文 + logger.info( + "Thread completed and preserved for conversation context", + extra={ + "request_info": { + "event": "thread_completed_preserved", + "thread_id": thread_id, + "was_created_new": should_create_thread, + } + }, + ) + except requests.exceptions.Timeout as exc: + logger.error(f"Request timeout: {exc}", exc_info=True) + raise NotionUpstreamError("Request to Notion upstream timed out.", retriable=True) from exc + except requests.exceptions.RequestException as exc: + logger.error(f"Request failed: {exc}", exc_info=True) + # 不暴露原始异常细节给用户 + raise NotionUpstreamError("Request to Notion upstream failed. Please try again later.", retriable=True) from exc + finally: + if response is not None: + response.close() diff --git a/app/schemas.py b/app/schemas.py new file mode 100644 index 0000000..d3a9d31 --- /dev/null +++ b/app/schemas.py @@ -0,0 +1,93 @@ +import time +from typing import Any, Dict, List, Literal, Optional +from pydantic import BaseModel, Field, field_validator + +# ================================ +# 请求相关 Schema (Chat Completion) +# ================================ + +class ChatMessage(BaseModel): + """单条对话消息""" + role: Literal["user", "assistant", "system"] + content: str + thinking: Optional[str] = None + + @field_validator("content", mode="before") + @classmethod + def _coerce_content_parts(cls, v): + # OpenAI-style content parts (отправляют omp и др. клиенты) → plain text. + # Не-текстовые части (image_url и т.п.) мост не поддерживает и молча отбрасывает. + if v is None: + return "" + if isinstance(v, str): + return v + if isinstance(v, list): + texts = [] + for part in v: + if isinstance(part, dict) and part.get("type") == "text": + texts.append(part.get("text") or "") + elif isinstance(part, str): + texts.append(part) + return "".join(texts) + return str(v) + +class ChatCompletionRequest(BaseModel): + """ + OpenAI-Compatible 发起完成请求的 Payload。 + 保留 `conversation_id` 作为特定的扩展字段,若缺失则视为独立请求。 + """ + model: str = Field(default="claude-opus4.6", description="Requested model.") + messages: List[ChatMessage] + stream: bool = Field(default=False, description="Whether to stream the response as SSE.") + temperature: Optional[float] = Field(default=None, description="Sampling temperature.") + conversation_id: Optional[str] = Field(default=None, description="Extension for stateful conversation tracking.") + +# ================================ +# 非流式返回 Schema +# ================================ + +class ChatMessageResponseChoice(BaseModel): + """非流式响应的选项""" + index: int = 0 + message: ChatMessage + finish_reason: str = "stop" + +class ChatCompletionResponse(BaseModel): + """ + OpenAI-Compatible 完整返回 Payload。 + """ + id: str + object: str = "chat.completion" + created: int = Field(default_factory=lambda: int(time.time())) + model: str + choices: List[ChatMessageResponseChoice] + usage: Dict[str, int] = Field( + default_factory=lambda: {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0} + ) + # Standard 模式扩展字段 + search_metadata: Optional[Dict[str, Any]] = Field(default=None) + +# ================================ +# 流式返回 Schema (供内部组织) +# ================================ + +class ChatCompletionChunkDelta(BaseModel): + """SSE Delta Block""" + content: Optional[str] = None + role: Optional[str] = None + +class ChatCompletionChunkChoice(BaseModel): + """SSE Choice Block""" + index: int = 0 + delta: ChatCompletionChunkDelta + finish_reason: Optional[str] = None + +class ChatCompletionChunk(BaseModel): + """ + OpenAI-Compatible 流式 Chunk + """ + id: str + object: str = "chat.completion.chunk" + created: int = Field(default_factory=lambda: int(time.time())) + model: str + choices: List[ChatCompletionChunkChoice] diff --git a/app/server.py b/app/server.py new file mode 100644 index 0000000..911245d --- /dev/null +++ b/app/server.py @@ -0,0 +1,172 @@ +import time +import os +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse, Response +from fastapi.middleware.cors import CORSMiddleware +from fastapi.staticfiles import StaticFiles +from slowapi.errors import RateLimitExceeded +from contextlib import asynccontextmanager +from app.config import ACCOUNTS, API_KEY, ALLOWED_ORIGINS, is_lite_mode, is_standard_mode +from app.account_pool import AccountPool +from app.conversation import ConversationManager +from app.api.chat import router as chat_router +from app.api.models import router as models_router +from app.logger import logger +from app.limiter import limiter + +@asynccontextmanager +async def lifespan(app: FastAPI): + # 启动时初始化状态 + app.state.account_pool = AccountPool(ACCOUNTS) + + # 确定运行模式 + if is_lite_mode(): + mode = "lite" + logger.info("Service starting up in LITE mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "lite"}}) + elif is_standard_mode(): + mode = "standard" + logger.info("Service starting up in STANDARD mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "standard"}}) + else: + mode = "heavy" + app.state.conversation_manager = ConversationManager() + logger.info("Service starting up in HEAVY mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "heavy"}}) + + app.state.start_time = time.time() + yield + # 关闭时清理 + logger.info("Service shutting down", extra={"request_info": {"event": "shutdown"}}) + +app = FastAPI( + title="Notion Opus API", + description="A FastAPI wrapper providing an OpenAI-compatible interface for Notion's Claude Opus backend.", + version="1.0.0", + lifespan=lifespan +) + +# 允许跨域(配合本地前端) +app.add_middleware( + CORSMiddleware, + allow_origins=ALLOWED_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# 注入 Limiter +app.state.limiter = limiter + +# 自定义 429 速率限制响应 +def custom_rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded): + return JSONResponse( + status_code=429, + content={"error": "Too many requests, please try again later"} + ) +app.add_exception_handler(RateLimitExceeded, custom_rate_limit_exceeded_handler) + + +@app.exception_handler(Exception) +async def generic_exception_handler(request: Request, exc: Exception): + logger.error( + "Unhandled application exception", + exc_info=True, + extra={ + "request_info": { + "event": "unhandled_exception", + "method": request.method, + "path": request.url.path, + } + }, + ) + return JSONResponse( + status_code=500, + content={ + "error": { + "message": "Internal server error", + "type": "server_error", + } + }, + ) + +# 结构化日志中间件 +@app.middleware("http") +async def log_requests_middleware(request: Request, call_next): + start_time = time.time() + + # 跳过高频且不重要的日志打印,避免刷屏 + skip_logging = request.url.path in ["/health", "/favicon.ico"] + + try: + response = await call_next(request) + status_code = response.status_code + except Exception as e: + status_code = 500 + logger.error(f"Unhandled exception: {str(e)}", exc_info=True) + raise + finally: + process_time = time.time() - start_time + client_ip = request.client.host if request.client else "unknown" + + if not skip_logging: + log_level = logger.error if status_code >= 400 else logger.info + log_level( + "Request processed", + extra={ + "request_info": { + "method": request.method, + "path": request.url.path, + "ip": client_ip, + "status_code": status_code, + "duration_ms": round(process_time * 1000, 2) + } + } + ) + + return response + +# 简易 API Key 鉴权中间件 +@app.middleware("http") +async def api_key_auth(request: Request, call_next): + # 如果环境配置中未设置 API_KEY,则全局不验证 + if API_KEY: + # 跳过 OPTIONS 请求和非受保护的静态路由(如果以后有的话) + if request.url.path.startswith("/v1") and request.method != "OPTIONS": + auth_header = request.headers.get("Authorization", "") + if not auth_header.startswith("Bearer ") or auth_header.split(" ")[1] != API_KEY: + return JSONResponse( + status_code=401, + content={ + "error": { + "message": "Error: API KEY doesn't match.", + "type": "invalid_request_error", + "code": "invalid_api_key" + } + } + ) + return await call_next(request) + +# 挂载路由,前缀统一为 /v1 +app.include_router(chat_router, prefix="/v1") +app.include_router(models_router, prefix="/v1") + +# 挂载健康检查 +@app.get("/favicon.ico", include_in_schema=False) +async def favicon(): + return Response(content=b"", media_type="image/x-icon", status_code=204) + +@app.get("/health", tags=["system"]) +def health_check(request: Request): + uptime = time.time() - request.app.state.start_time + pool = request.app.state.account_pool + status = pool.get_status_summary() + return { + "status": "ok", + "accounts": status["active"], + "accounts_total": status["total"], + "accounts_cooling": status["cooling"], + "uptime": int(uptime) + } + +# 挂载静态前端到根目录 +frontend_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "frontend") +if os.path.exists(frontend_dir): + app.mount("/", StaticFiles(directory=frontend_dir, html=True), name="frontend") diff --git a/app/stream_parser.py b/app/stream_parser.py new file mode 100644 index 0000000..2a0841a --- /dev/null +++ b/app/stream_parser.py @@ -0,0 +1,1013 @@ +import json +import re +from typing import Any, Generator + +import requests + +from app.logger import logger + +# 清理 Notion 内部语言/格式标记的正则集合 +# 1. 完整的 ... 块,替换时只保留内部文本(_strip_lang_tags 的兜底) +_RE_LANG_FULL = re.compile(r"]*>(.*?)", re.DOTALL) +# 2. 残留的 孤立开标签(无对应内容或截断后留下的) +_RE_LANG_OPEN = re.compile(r"]*>") +# 3. 残留的 闭标签 +_RE_LANG_CLOSE = re.compile(r"") +# 4. Notion 语言属性残片:如 primary="zh-CN" 或 primary="zh" 或 primary="en" +# 可能带或不带引号,出现在文本开头或任意位置 +_RE_PRIMARY_ATTR = re.compile(r'\bprimary="[a-zA-Z\-]{1,15}"\s*') +# 5. 剩余的 > 或 "> 残片(由截断的开标签留下的属性尾巴,如 -CN"> ) +_RE_ATTR_TAIL = re.compile(r'^-?[a-zA-Z]{0,4}"\s*>\s*') +_RE_PRIMARY_START = re.compile(r"\bprimary\b", re.IGNORECASE) + +SEARCH_PATH_KEYWORDS = ("search", "web", "query", "source", "citation", "tool") +SEARCH_TYPE_KEYWORDS = ("search", "web", "tool", "citation") +LINE_DEBUG_KEYWORDS = ("queries", "category", "sources", "citations", "questions") +SEARCH_VALUE_KEYS = ( + "queries", + "query", + "questions", + "category", + "sources", + "citations", + "results", + "url", + "urls", + "href", + "search", + "web", + "tool", + "toolname", + "tooltype", + "internal", +) + +# ---- 段落分类:根据 Notion o:"a" patch 的 v.type 判断 ---- +# 思考类 type 关键词 +_THINKING_TYPES = ("agent-inference", "thinking", "reasoning", "inference") +# 工具/搜索类 type 关键词 +_TOOL_TYPES = ("agent-tool-result", "tool_use", "tool", "search", "web", "citation") + +# 段落角色常量 +SEG_THINKING = "thinking" +SEG_TOOL = "tool" +SEG_CONTENT = "content" +SEG_META = "meta" + +FINAL_STEP_PRIORITIES: dict[str, int] = { + "markdown-chat": 400, + "text": 350, + "agent-inference": 300, + "title": 50, +} + + +def _strip_lang_tags(text: str, in_tag: list[bool]) -> str: + """Strip Notion internal tags, including cross-chunk broken tags.""" + result = [] + i = 0 + while i < len(text): + if in_tag[0]: + end = text.find(">", i) + if end == -1: + break + in_tag[0] = False + i = end + 1 + continue + + lang_start = text.find("", i) + candidates = [(pos, typ) for pos, typ in [(lang_start, "open"), (close_start, "close")] if pos != -1] + if not candidates: + result.append(text[i:]) + break + + next_pos, typ = min(candidates, key=lambda x: x[0]) + result.append(text[i:next_pos]) + + if typ == "close": + i = next_pos + len("") + continue + + end = text.find(">", next_pos) + if end == -1: + in_tag[0] = True + break + i = end + 1 + + return "".join(result) + + +def _clean_notion_markup(text: str) -> str: + """ + 二次清理:移除 _strip_lang_tags 可能遗漏的 Notion 内部标记残片。 + + 处理以下场景: + 1. 完整 内容(_strip_lang_tags 兜底,保留内容只剥标签) + 2. 孤立的 闭标签 + 3. 孤立的 开标签(内容已被 _strip_lang_tags 保留,只剩空壳) + 4. primary="zh-CN" 属性残片(跨块截断后留下的属性文本) + 5. 属性尾部残片,如 -CN"> 或 en"> 出现在文本开头 + """ + # 完整 内容:保留内容,剥掉标签 + text = _RE_LANG_FULL.sub(r"\1", text) + # 移除孤立的 + text = _RE_LANG_CLOSE.sub("", text) + # 移除孤立的 开标签 + text = _RE_LANG_OPEN.sub("", text) + # 移除 primary="zh-CN" 之类的属性残片 + text = _RE_PRIMARY_ATTR.sub("", text) + # 移除行首的属性尾巴残片,如 -CN"> 或 "> 或 en"> + text = _RE_ATTR_TAIL.sub("", text) + return text + + + +def _strip_primary_attr_fragments(text: str, in_primary_attr: list[bool]) -> str: + """Strip fragmented `primary=...` attribute pieces leaked by stream chunks.""" + out: list[str] = [] + i = 0 + + while i < len(text): + if in_primary_attr[0]: + ch = text[i] + if ch in ">\r\n": + in_primary_attr[0] = False + i += 1 + continue + if ch.isalpha() or ch in '-_="\'/: ': + i += 1 + continue + in_primary_attr[0] = False + continue + + m = _RE_PRIMARY_START.search(text, i) + if not m: + out.append(text[i:]) + break + + start = m.start() + out.append(text[i:start]) + + j = m.end() + while j < len(text) and text[j].isspace(): + j += 1 + + if j < len(text) and text[j] not in ("=", "\"", "'"): + out.append(text[start:m.end()]) + i = m.end() + continue + + if j < len(text) and text[j] == "=": + j += 1 + while j < len(text) and text[j].isspace(): + j += 1 + + if j < len(text) and text[j] in ("\"", "'"): + quote = text[j] + j += 1 + while j < len(text) and (text[j].isalpha() or text[j] in "-_"): + j += 1 + if j < len(text) and text[j] == quote: + j += 1 + else: + while j < len(text) and (text[j].isalpha() or text[j] in "-_"): + j += 1 + + while j < len(text) and text[j] in " />": + j += 1 + + if j >= len(text): + in_primary_attr[0] = True + break + + i = j + + return "".join(out) + +def _normalize_path(patch: dict[str, Any]) -> str: + for key in ("path", "p", "pointer", "at"): + if key not in patch: + continue + raw = patch.get(key) + if isinstance(raw, (list, tuple)): + return "/".join(str(part) for part in raw) + return str(raw) + return "" + + +def _extract_segment_index(path: str) -> int | None: + parts = [part for part in path.split("/") if part] + if len(parts) < 2 or parts[0] != "s": + return None + try: + return int(parts[1]) + except Exception: + return None + + +def _extract_value_index(path: str) -> int | None: + """从 /s/N/value/M/... 形式的 path 中提取 value block 序号 M。""" + parts = [p for p in path.split("/") if p] + for i, part in enumerate(parts): + if part == "value" and i + 1 < len(parts): + try: + return int(parts[i + 1]) + except ValueError: + return None + return None + + +def _extract_value_add_index(path: str) -> int | None: + """ + 从 `o:"a"` 的 `/s/N/value/` 路径中提取新 value block 序号。 + 仅匹配 value block 本身,不匹配 `/content` 等子路径。 + """ + parts = [p for p in path.split("/") if p] + if len(parts) != 4: + return None + if parts[0] != "s" or parts[2] != "value": + return None + idx_raw = parts[3] + if idx_raw == "-": + return -1 + try: + return int(idx_raw) + except ValueError: + return None + + +def _truncate_json(value: Any, max_len: int = 2000) -> str: + try: + raw = json.dumps(value, ensure_ascii=False) + except Exception: + raw = str(value) + if len(raw) <= max_len: + return raw + return raw[:max_len] + "...(truncated)" + + +def _contains_search_keys(value: Any) -> bool: + if isinstance(value, dict): + for key, val in value.items(): + key_lower = str(key).lower() + if any(token in key_lower for token in SEARCH_VALUE_KEYS): + return True + if _contains_search_keys(val): + return True + return False + + if isinstance(value, list): + return any(_contains_search_keys(item) for item in value) + + return False + + +def _append_query(out: dict[str, Any], query: str) -> None: + q = query.strip() + if q: + out.setdefault("queries", []).append(q) + + +def _append_source(out: dict[str, Any], source: dict[str, Any]) -> None: + title = str(source.get("title", "") or "").strip() + url = str(source.get("url", "") or "").strip() + snippet = str(source.get("snippet", "") or "").strip() + if not title and not url: + return + + entry: dict[str, str] = {} + if title: + entry["title"] = title + if url: + entry["url"] = url + if snippet: + entry["snippet"] = snippet + out.setdefault("sources", []).append(entry) + + +def _collect_search_metadata(value: Any, out: dict[str, Any]) -> None: + if isinstance(value, dict): + lowered = {str(k).lower(): v for k, v in value.items()} + + if isinstance(lowered.get("queries"), list): + for item in lowered["queries"]: + if isinstance(item, str): + _append_query(out, item) + + if isinstance(lowered.get("questions"), list): + for item in lowered["questions"]: + if isinstance(item, str): + _append_query(out, item) + + for single_query_key in ("query", "search_query", "searchquery"): + query_val = lowered.get(single_query_key) + if isinstance(query_val, str): + _append_query(out, query_val) + + category = lowered.get("category") + if isinstance(category, str) and category.strip(): + out.setdefault("categories", []).append(category.strip()) + + for source_key in ("sources", "citations", "results"): + source_items = lowered.get(source_key) + if not isinstance(source_items, list): + continue + for item in source_items: + if isinstance(item, dict): + _append_source( + out, + { + "title": item.get("title") or item.get("name") or item.get("sourceTitle") or "", + "url": item.get("url") or item.get("href") or item.get("link") or item.get("sourceUrl") or "", + "snippet": item.get("snippet") or item.get("summary") or item.get("description") or "", + }, + ) + elif isinstance(item, str): + _append_source(out, {"title": item, "url": item}) + + if isinstance(lowered.get("urls"), list): + for url_item in lowered["urls"]: + if isinstance(url_item, str) and url_item.strip(): + _append_source(out, {"title": url_item.strip(), "url": url_item.strip()}) + + url_val = lowered.get("url") or lowered.get("href") or lowered.get("link") + if isinstance(url_val, str): + _append_source( + out, + { + "title": lowered.get("title") or lowered.get("name") or url_val, + "url": url_val, + "snippet": lowered.get("snippet") or lowered.get("summary") or "", + }, + ) + + for nested in value.values(): + _collect_search_metadata(nested, out) + return + + if isinstance(value, list): + for item in value: + _collect_search_metadata(item, out) + + +def _dedupe_search_data(data: dict[str, Any]) -> dict[str, Any]: + queries = data.get("queries", []) + sources = data.get("sources", []) + categories = data.get("categories", []) + + deduped_queries: list[str] = [] + for query in queries: + if query not in deduped_queries: + deduped_queries.append(query) + + deduped_sources: list[dict[str, str]] = [] + seen_sources: set[tuple[str, str]] = set() + for source in sources: + title = str(source.get("title", "") or "") + url = str(source.get("url", "") or "") + key = (title, url) + if key in seen_sources: + continue + seen_sources.add(key) + deduped_sources.append(source) + + deduped_categories: list[str] = [] + for category in categories: + if category not in deduped_categories: + deduped_categories.append(category) + + out: dict[str, Any] = {} + if deduped_queries: + out["queries"] = deduped_queries + if deduped_sources: + out["sources"] = deduped_sources + if deduped_categories: + out["categories"] = deduped_categories + return out + + +def _looks_like_search_patch(patch: dict[str, Any]) -> bool: + patch_type = str(patch.get("type", "") or "").lower() + patch_v = patch.get("v") + nested_type = "" + if isinstance(patch_v, dict): + nested_type = str(patch_v.get("type", "") or "").lower() + + effective_type = patch_type or nested_type + if effective_type and effective_type != "text" and any(token in effective_type for token in SEARCH_TYPE_KEYWORDS): + return True + + path = _normalize_path(patch).lower() + if any(token in path for token in SEARCH_PATH_KEYWORDS): + return True + + if _contains_search_keys(patch.get("v")): + return True + + return False + + +def _extract_search_data_from_patch(patch: dict[str, Any]) -> dict[str, Any]: + extracted: dict[str, Any] = {"queries": [], "sources": [], "categories": []} + _collect_search_metadata(patch, extracted) + return _dedupe_search_data(extracted) + + +def _extract_text_from_patch(patch: dict[str, Any]) -> str: + content = "" + patch_op = patch.get("o") + + if patch_op == "a": + patch_v = patch.get("v", {}) + if isinstance(patch_v, dict) and "value" in patch_v: + val = patch_v["value"] + if isinstance(val, list): + text_parts = [] + for item in val: + if isinstance(item, dict) and isinstance(item.get("content"), str): + text_parts.append(str(item.get("content", ""))) + content = "".join(text_parts) + elif isinstance(patch_v, dict) and "content" in patch_v: + # 子 value block 创建:o:"a" /s/N/value/- → {type:"text", content:"..."} + raw = patch_v.get("content") + if isinstance(raw, str): + content = raw + + elif patch_op == "x" and "v" in patch: + content = patch["v"] if isinstance(patch["v"], str) else "" + + elif patch_op == "p" and "v" in patch: + # 路径替换有时也携带文本内容 + path = _normalize_path(patch) + if "/content" in path or "/text" in path: + content = patch["v"] if isinstance(patch["v"], str) else "" + + return content + + +def _looks_like_search_json_fragment(text: str) -> bool: + stripped = text.strip().lower() + if not stripped.startswith("{"): + return False + + if '"default"' in stripped and ('"questions"' in stripped or '"queries"' in stripped): + return True + + return ( + '"queries"' in stripped + or '"web"' in stripped + or '"sources"' in stripped + or '"citations"' in stripped + or '"internal"' in stripped + or '"questions"' in stripped + or '"urls"' in stripped + ) + + +def _extract_search_data_from_json_text(text: str) -> dict[str, Any]: + try: + parsed = json.loads(text) + except Exception: + return {} + + extracted: dict[str, Any] = {"queries": [], "sources": [], "categories": []} + _collect_search_metadata(parsed, extracted) + return _dedupe_search_data(extracted) + + +def _clean_extracted_text(text: str) -> str: + if not text: + return "" + in_lang_tag = [False] + in_primary_attr = [False] + cleaned = _strip_lang_tags(text, in_lang_tag) + cleaned = _strip_primary_attr_fragments(cleaned, in_primary_attr) + cleaned = _clean_notion_markup(cleaned) + return cleaned.strip() + + +def _extract_text_from_value_items(value_items: Any) -> str: + if not isinstance(value_items, list): + return "" + + parts: list[str] = [] + for item in value_items: + if not isinstance(item, dict): + continue + if str(item.get("type", "") or "").lower() != "text": + continue + content = item.get("content") + if isinstance(content, str) and content: + parts.append(content) + return "".join(parts) + + +def _extract_markdown_chat_text(value: Any) -> str: + if isinstance(value, str): + return value + if isinstance(value, list): + parts: list[str] = [] + for item in value: + if isinstance(item, str): + parts.append(item) + continue + if not isinstance(item, dict): + continue + item_type = str(item.get("type", "") or "").lower() + if item_type == "text" and isinstance(item.get("content"), str): + parts.append(str(item.get("content", ""))) + continue + nested_value = item.get("value") + if nested_value is not None: + nested_text = _extract_markdown_chat_text(nested_value) + if nested_text: + parts.append(nested_text) + return "".join(parts) + if isinstance(value, dict): + for key in ("value", "content", "text"): + if key in value: + nested_text = _extract_markdown_chat_text(value.get(key)) + if nested_text: + return nested_text + return "" + + +def _extract_markdown_chat_patch_text(patch: dict[str, Any]) -> tuple[str, str] | None: + patch_op = str(patch.get("o", "") or "") + patch_v = patch.get("v") + + if ( + patch_op == "a" + and isinstance(patch_v, dict) + and str(patch_v.get("type", "") or "").lower() == "markdown-chat" + ): + cleaned = _clean_extracted_text(_extract_markdown_chat_text(patch_v.get("value"))) + if cleaned: + return ("final_content", cleaned) + + return None + + +def _safe_int(value: Any) -> int: + try: + return int(value) + except Exception: + return 0 + + +def _extract_final_content_from_record_map(data: dict[str, Any]) -> dict[str, Any] | None: + record_map = data.get("recordMap") + if not isinstance(record_map, dict): + return None + + thread_messages = record_map.get("thread_message") + if not isinstance(thread_messages, dict): + return None + + candidates: list[dict[str, Any]] = [] + + for msg_id, msg_data in thread_messages.items(): + if not isinstance(msg_data, dict): + continue + + outer_value = msg_data.get("value") + if not isinstance(outer_value, dict): + continue + inner_value = outer_value.get("value") + if not isinstance(inner_value, dict): + continue + step = inner_value.get("step") + if not isinstance(step, dict): + continue + + step_type = str(step.get("type", "") or "").lower() + content = "" + + if step_type == "markdown-chat": + content = _extract_markdown_chat_text(step.get("value")) + elif step_type == "agent-inference": + content = _extract_text_from_value_items(step.get("value")) + elif step_type in {"text", "title"}: + raw_value = step.get("value") + if isinstance(raw_value, str): + content = raw_value + + cleaned = _clean_extracted_text(content) + if cleaned: + candidates.append( + { + "message_id": str(msg_id), + "step_type": step_type or "unknown", + "priority": FINAL_STEP_PRIORITIES.get(step_type, 100), + "created_at": _safe_int(outer_value.get("created_time")), + "edited_at": _safe_int(outer_value.get("last_edited_time")), + "length": len(cleaned), + "text": cleaned, + } + ) + + # 智能过滤:如果同时存在高优先级的 text/markdown-chat,则忽略 agent-inference + # 这可以避免 Opus/GPT 模型将所有内容都放在 agent-inference 中导致的重复显示问题 + high_priority_types = {"text", "markdown-chat"} + has_high_priority = any(c["step_type"] in high_priority_types for c in candidates) + + if has_high_priority: + original_count = len(candidates) + candidates = [c for c in candidates if c["step_type"] in high_priority_types] + logger.debug( + "Final content filtered", + extra={ + "request_info": { + "event": "final_content_filtered", + "original_count": original_count, + "filtered_count": len(candidates), + "removed_types": [c["step_type"] for c in candidates if c["step_type"] not in high_priority_types], + } + }, + ) + + if not candidates: + return None + + best = max( + candidates, + key=lambda candidate: ( + int(candidate.get("priority", 0)), + int(candidate.get("edited_at", 0)), + int(candidate.get("created_at", 0)), + int(candidate.get("length", 0)), + ), + ) + + logger.debug( + "Final content selected", + extra={ + "request_info": { + "event": "final_content_selected", + "step_type": best.get("step_type", "unknown"), + "priority": best.get("priority", 0), + "length": len(best.get("text", "")), + "message_id": best.get("message_id", ""), + } + }, + ) + + return { + "text": str(best.get("text", "") or ""), + "source_type": str(best.get("step_type", "") or "unknown"), + "source_message_id": str(best.get("message_id", "") or ""), + "source_length": int(best.get("length", 0)), + } + + +def _classify_segment_type(effective_type: str) -> str: + """ + 根据 o:"a" patch 的 type 字段判断新段落的角色。 + 这是整个分类逻辑的唯一入口——只依赖 Notion 自己标注的 type。 + """ + if not effective_type: + return SEG_CONTENT + if effective_type == "text": + return SEG_CONTENT + if effective_type == "title": + return SEG_META + if any(kw in effective_type for kw in _THINKING_TYPES): + return SEG_THINKING + if any(kw in effective_type for kw in _TOOL_TYPES): + return SEG_TOOL + # 未知类型默认归正文,保证不丢内容 + return SEG_CONTENT + + +def _bind_pending_segment( + notion_idx: int, + pending: list[dict], + segment_types: dict[int, str], + value_types: dict[tuple[int, int], str], + next_val_id: dict[int, int], + patch_path: str, +) -> None: + """ + 从 pending 列表中找到最匹配的段落绑定到 Notion 的真实 index。 + + 策略:优先绑定 agent-inference(thinking)段落,因为它是唯一需要 + 精确分类的段落。其他段落(tool、meta、content)即使绑错也不影响输出, + 因为它们的文本要么被跳过(meta/tool)要么本来就是 content。 + """ + if not pending: + return + + # 从 patch_path 提取 value index,用于匹配 + val_idx = _extract_value_index(patch_path) + + # 策略:如果 path 引用了 value/0/content,优先找有 thinking value[0] 的段落 + best_idx = 0 # 默认取第一个 + if val_idx is not None: + for i, seg in enumerate(pending): + vt = seg.get("value_types", {}) + if vt.get(val_idx) == SEG_THINKING: + best_idx = i + break + + chosen = pending.pop(best_idx) + segment_types[notion_idx] = chosen["seg_class"] + for vi, vc in chosen["value_types"].items(): + value_types[(notion_idx, vi)] = vc + next_val_id[notion_idx] = chosen["next_val_id"] + + logger.debug( + "Pending segment bound to Notion index", + extra={ + "request_info": { + "event": "segment_bound", + "notion_idx": notion_idx, + "seg_class": chosen["seg_class"], + "value_types": {str(k): v for k, v in chosen["value_types"].items()}, + "remaining_pending": len(pending), + "patch_path": patch_path, + } + }, + ) + + +def parse_stream(response: requests.Response) -> Generator[dict[str, Any], None, None]: + """ + 解析 Notion NDJSON 流,输出三种结构化事件: + - {"type": "content", "text": "..."} 正文 + - {"type": "search", "data": {...}} 搜索元数据 + - {"type": "thinking", "text": "..."} 思考过程 + + 核心机制——段落注册表(Segment Registry): + Notion 流中每个 o:"a" + path="/s/-" 的 patch 创建一个新的顶层段落, + 此时 v.type 明确标注了类型(agent-inference / agent-tool-result / text 等)。 + 我们在此刻分配递增序号并记录类型。 + 后续 o:"x" + path="/s/N/..." 只是往已有段落追加文本,查表即可知归属。 + 不需要关键词猜测、不需要状态机。 + """ + in_lang_tag: list[bool] = [False] + in_primary_attr: list[bool] = [False] + search_json_buffer = "" + search_json_depth = 0 + + # ---- 段落注册表 ---- + # Notion 的 /s/N 中的 N 是全局 index(包括 config/context/user 等隐含段落), + # 但 o:"a" /s/- 不告诉我们真实 index。 + # 策略:o:"a" /s/- 时记录到 pending dict。 + # 当 o:"x" /s/N/... 或 o:"a" /s/N/... 首次引用未知 N 时, + # 从 pending 中找最匹配的段落绑定(优先匹配 agent-inference/thinking 类型)。 + segment_types: dict[int, str] = {} # notion_index → SEG_THINKING / SEG_TOOL / SEG_CONTENT + value_types: dict[tuple[int, int], str] = {} # (notion_index, val_index) → 类型 + next_val_id: dict[int, int] = {} # notion_index → 下一个 value block 序号 + + # pending:o:"a" /s/- 注册但尚未绑定到 Notion 真实 index 的段落 + _pending_segments: list[dict] = [] # [{seg_class, value_types_local, next_val_id_local}] + + for line in response.iter_lines(decode_unicode=True): + if not line: + continue + if isinstance(line, bytes): + line = line.decode("utf-8", errors="ignore") + + # 调试日志:含搜索关键词的行 + lowered_line = line.lower() + if any(token in lowered_line for token in LINE_DEBUG_KEYWORDS): + logger.debug( + "NDJSON debug line", + extra={"request_info": {"event": "notion_ndjson_debug_line", "line": line[:4000]}}, + ) + + try: + data = json.loads(line) + except json.JSONDecodeError: + continue + + data_type = str(data.get("type", "") or "").lower() + + if data_type == "record-map": + final_payload = _extract_final_content_from_record_map(data) + if final_payload and final_payload.get("text"): + yield {"type": "final_content", **final_payload} + continue + + if data_type == "markdown-chat": + cleaned = _clean_extracted_text(_extract_markdown_chat_text(data.get("value"))) + if cleaned: + yield {"type": "final_content", "text": cleaned, "source_type": "markdown-chat-event"} + continue + + if data_type != "patch": + continue + + patches = data.get("v", []) + if not isinstance(patches, list): + continue + + for patch in patches: + if not isinstance(patch, dict): + continue + + patch_op = str(patch.get("o", "") or "") + patch_v = patch.get("v") + patch_path = _normalize_path(patch) + patch_seg = _extract_segment_index(patch_path) + + markdown_chat_patch = _extract_markdown_chat_patch_text(patch) + if markdown_chat_patch is not None: + event_type, event_text = markdown_chat_patch + if event_type == "final_content": + yield {"type": event_type, "text": event_text, "source_type": "markdown-chat-patch"} + else: + yield {"type": event_type, "text": event_text} + continue + + # 提取 effective type(优先 patch.type,其次 v.type) + patch_type = str(patch.get("type", "") or "").lower() + nested_type = "" + if isinstance(patch_v, dict): + nested_type = str(patch_v.get("type", "") or "").lower() + effective_type = patch_type or nested_type + + # ========== 段落注册:o:"a" 创建新段落 ========== + path_stripped = patch_path.strip("/") + is_new_toplevel_segment = (patch_op == "a" and path_stripped == "s/-") + + # 本 patch 的角色(注册时确定,用于当前 patch 的分类) + patch_role: str | None = None + + if is_new_toplevel_segment: + seg_class = _classify_segment_type(effective_type) + + # 收集 value item 类型 + local_value_types: dict[int, str] = {} + local_next_val_id = 0 + if isinstance(patch_v, dict) and "value" in patch_v: + value_array = patch_v.get("value") + if isinstance(value_array, list): + for idx, item in enumerate(value_array): + if isinstance(item, dict): + item_type = str(item.get("type", "") or "").lower() + item_class = _classify_segment_type(item_type) + local_value_types[idx] = item_class + local_next_val_id = idx + 1 + + if 0 not in local_value_types: + local_value_types[0] = seg_class + local_next_val_id = max(local_next_val_id, 1) + + # 加入 pending 队列,等待 o:"x" /s/N 绑定真实 index + _pending_segments.append({ + "seg_class": seg_class, + "value_types": local_value_types, + "next_val_id": local_next_val_id, + }) + + # 初始 patch 的文本用 value[0] 的类型 + patch_role = local_value_types.get(0, seg_class) + # patch_seg 暂时设为 None,因为还不知道真实 index + patch_seg = None + + logger.debug( + "Segment registered (pending)", + extra={ + "request_info": { + "event": "segment_registered", + "pending_idx": len(_pending_segments) - 1, + "seg_class": seg_class, + "effective_type": effective_type, + "value_types": local_value_types, + "patch_role": patch_role, + } + }, + ) + + elif patch_op == "a" and patch_seg is not None: + # o:"a" 但 path 不是 /s/-(如 /s/2/value/-),属于已有段落的子追加 + # 先尝试绑定 pending 段落 + if patch_seg not in segment_types and _pending_segments: + _bind_pending_segment(patch_seg, _pending_segments, segment_types, value_types, next_val_id, patch_path) + + if patch_seg not in segment_types: + segment_types[patch_seg] = _classify_segment_type(effective_type) + + # 检测 /s/N/value/ 子块追加 + value_add_idx = _extract_value_add_index(patch_path) + if value_add_idx is not None: + vid = next_val_id.get(patch_seg, 0) if value_add_idx < 0 else value_add_idx + next_val_id[patch_seg] = max(next_val_id.get(patch_seg, 0), vid + 1) + val_class = _classify_segment_type(effective_type) + value_types[(patch_seg, vid)] = val_class + patch_role = val_class + in_lang_tag[0] = False + in_primary_attr[0] = False + + # ========== 绑定 pending 段落(o:"x" 首次引用时) ========== + if patch_seg is not None and patch_seg not in segment_types and _pending_segments: + _bind_pending_segment(patch_seg, _pending_segments, segment_types, value_types, next_val_id, patch_path) + + # ========== 确定当前 patch 所属的角色 ========== + if patch_role is not None: + # 刚注册的 patch,直接用注册时的角色 + seg_owner = patch_role + else: + # o:"x" 追加文本:先查 value block 表,再查 segment 表 + val_idx = _extract_value_index(patch_path) + if val_idx is not None and patch_seg is not None and (patch_seg, val_idx) in value_types: + seg_owner = value_types[(patch_seg, val_idx)] + logger.debug( + "Patch role from value_types", + extra={ + "request_info": { + "event": "patch_role_value_lookup", + "patch_op": patch_op, + "patch_seg": patch_seg, + "val_idx": val_idx, + "seg_owner": seg_owner, + "patch_path": patch_path, + } + }, + ) + elif patch_seg is not None and patch_seg in segment_types: + seg_owner = segment_types[patch_seg] + logger.debug( + "Patch role from segment_types fallback", + extra={ + "request_info": { + "event": "patch_role_segment_fallback", + "patch_op": patch_op, + "patch_seg": patch_seg, + "val_idx": val_idx, + "seg_owner": seg_owner, + "value_types_missing": (patch_seg, val_idx) not in value_types if val_idx is not None else None, + "patch_path": patch_path, + } + }, + ) + else: + seg_owner = SEG_CONTENT + logger.debug( + "Patch role defaulting to content", + extra={ + "request_info": { + "event": "patch_role_default_content", + "patch_op": patch_op, + "patch_seg": patch_seg, + "val_idx": val_idx, + "patch_path": patch_path, + } + }, + ) + + # ========== 搜索元数据(与段落角色无关,始终提取) ========== + is_search_patch = _looks_like_search_patch(patch) + if is_search_patch: + search_data = _extract_search_data_from_patch(patch) + if search_data: + yield {"type": "search", "data": search_data} + + # ========== 提取文本 ========== + # /content replace patch can finalize broken lang attributes. + # Reset state here to avoid swallowing following normal text. + if patch_op == "p" and "/content" in patch_path and isinstance(patch_v, str): + if ">" in patch_v or "\n" in patch_v or "\r" in patch_v or not patch_v.strip(): + in_lang_tag[0] = False + in_primary_attr[0] = False + + content = _extract_text_from_patch(patch) + if not content: + continue + + cleaned = _strip_lang_tags(content, in_lang_tag) + cleaned = _strip_primary_attr_fragments(cleaned, in_primary_attr) + cleaned = _clean_notion_markup(cleaned) + if not cleaned: + continue + + # ========== 搜索 JSON 片段检测 ========== + stripped = cleaned.strip() + if stripped and (search_json_depth > 0 or _looks_like_search_json_fragment(stripped)): + search_json_buffer += cleaned + search_json_depth += stripped.count("{") - stripped.count("}") + if search_json_depth <= 0: + sd = _extract_search_data_from_json_text(search_json_buffer) + if sd: + yield {"type": "search", "data": sd} + search_json_buffer = "" + search_json_depth = 0 + continue + + # 已被 search patch 处理的结构化数据不重复输出 + if is_search_patch: + continue + + # ========== 按段落角色输出 ========== + if seg_owner == SEG_META: + continue + if seg_owner in (SEG_THINKING, SEG_TOOL): + yield {"type": "thinking", "text": cleaned} + else: + yield {"type": "content", "text": cleaned} + + + + diff --git a/app/summarizer.py b/app/summarizer.py new file mode 100644 index 0000000..72b4ce6 --- /dev/null +++ b/app/summarizer.py @@ -0,0 +1,93 @@ +import httpx + +from app.config import SILICONFLOW_API_KEY + + +class SummarizerUnavailableError(Exception): + """Raised when summarizer service cannot be used.""" + + +SILICONFLOW_ENDPOINT = "https://api.siliconflow.cn/v1/chat/completions" +MODEL_FALLBACK_CHAIN = ["Qwen/Qwen3-8B", "THUDM/glm-4-9b-chat"] + +SYSTEM_PROMPT = ( + "你是一个对话摘要助手。请将用户提供的一轮对话(一问一答)压缩成1~3句话的简洁摘要。\n" + "要求:保留关键信息(话题、结论、重要细节),去除废话,语言简洁,使用与对话相同的语言。\n\n" + "只输出摘要本身,不要有任何前缀或解释。" +) + + +def is_summarizer_configured() -> bool: + return bool(SILICONFLOW_API_KEY.strip()) + + +def _build_user_prompt(old_summaries: list[str], user_msg: str, assistant_msg: str) -> str: + prompt_parts = [] + if old_summaries: + prompt_parts.append("【已有上下文摘要(仅供参考,勿重复)】") + prompt_parts.append("\n".join(old_summaries[-5:])) + prompt_parts.append("") + + prompt_parts.append("【本轮对话】") + prompt_parts.append(f"用户:{user_msg}") + prompt_parts.append(f"AI:{assistant_msg}") + prompt_parts.append("") + prompt_parts.append("请输出本轮摘要:") + return "\n".join(prompt_parts) + + +async def _call_summarizer(model: str, old_summaries: list[str], user_msg: str, assistant_msg: str) -> str: + timeout = httpx.Timeout(connect=5.0, read=20.0, write=20.0, pool=20.0) + headers = { + "Authorization": f"Bearer {SILICONFLOW_API_KEY}", + "Content-Type": "application/json", + } + payload = { + "model": model, + "messages": [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": _build_user_prompt(old_summaries, user_msg, assistant_msg)}, + ], + "temperature": 0.2, + } + + async with httpx.AsyncClient(timeout=timeout) as client: + response = await client.post(SILICONFLOW_ENDPOINT, headers=headers, json=payload) + + if response.status_code != 200: + raise SummarizerUnavailableError(f"Summarizer upstream returned status {response.status_code}") + + data = response.json() + content = ( + data.get("choices", [{}])[0] + .get("message", {}) + .get("content", "") + ) + summary = str(content).strip() + if not summary: + raise SummarizerUnavailableError("Summarizer returned empty summary") + return summary + + +async def summarize_turn( + old_summaries: list[str], + user_msg: str, + assistant_msg: str, +) -> str: + """ + 调用 LLM 将一轮对话压缩为简短摘要,返回摘要字符串。失败时抛出异常。 + """ + if not is_summarizer_configured(): + raise SummarizerUnavailableError("SILICONFLOW_API_KEY is empty") + + last_error: Exception | None = None + for model in MODEL_FALLBACK_CHAIN: + try: + return await _call_summarizer(model, old_summaries, user_msg, assistant_msg) + except Exception as exc: + last_error = exc + continue + + raise SummarizerUnavailableError( + f"All summarizer models failed: {last_error}" + ) from last_error diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a65db62 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,65 @@ +# ============================================================ +# Notion AI Wrapper - Docker Compose Configuration +# ============================================================ +# Quick Start: +# docker-compose up -d +# docker-compose logs -f +# +# Check Health: +# curl http://localhost:8000/health +# +# Update & Restart: +# docker-compose down +# docker-compose build --no-cache +# docker-compose up -d +# ============================================================ + +services: + notion-ai: + build: + context: . + dockerfile: Dockerfile + image: notion-ai-wrapper:latest + container_name: notion_ai_service + restart: always + + # Port mapping: Use HOST_PORT env var or default to 8000 + ports: + - "${HOST_PORT:-8000}:8000" + + # Environment configuration + env_file: + - .env + environment: + - DB_PATH=/app/data/conversations.db + - PYTHONUNBUFFERED=1 + - TZ=Asia/Shanghai + + # Data persistence + account config + volumes: + - ./data:/app/data + - ./logs:/app/logs + - ./accounts.json:/app/accounts.json:ro + + # Resource limits (prevents container from using all system resources) + deploy: + resources: + limits: + memory: 1G + reservations: + memory: 256M + + # Health check (Docker will restart if unhealthy) + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 10s + + # Log rotation (prevents logs from filling disk) + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" diff --git a/login.py b/login.py new file mode 100644 index 0000000..b79e42c --- /dev/null +++ b/login.py @@ -0,0 +1,735 @@ +# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring +# pylint: disable=broad-exception-caught,line-too-long +# pylint: disable=consider-using-with,too-many-locals + +from __future__ import annotations + +import argparse +import os +import json +import shutil +import socket +import subprocess +import tempfile +import time +import webbrowser +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any, Sequence +from urllib.request import urlopen + +import requests +from websocket import create_connection + +# 与 app/notion_client.py 一致:支持区域镜像 / 反代,默认官方站点 +NOTION_URL = os.getenv("NOTION_URL", "https://www.notion.so").rstrip("/") +NOTION_DOMAIN = os.getenv("NOTION_DOMAIN", "www.notion.so").lstrip(".") +BASE_URL = NOTION_URL +AI_URL = f"{NOTION_URL}/ai" +# CDP 页面识别用的主机名片段(自定义域名时填 NOTION_DOMAIN 即可) +_NOTION_HOST_HINT = ( + NOTION_DOMAIN.removeprefix("www.") + if NOTION_DOMAIN.startswith("www.") + else NOTION_DOMAIN +) +USER_AGENT = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36" +) +ACCOUNTS_FILE = Path(__file__).resolve().parent / "accounts.json" +ENV_FILE = Path(__file__).resolve().parent / ".env" +DEFAULT_PROFILE = "default" +DEFAULT_DEBUG_PORT = 9222 +DEFAULT_LOGIN_TIMEOUT = 300 + + +@dataclass(frozen=True) +class NotionAccount: + profile_name: str + token_v2: str + space_id: str + user_id: str + space_view_id: str + user_name: str + user_email: str + cookies: dict[str, str] + + def with_profile(self, profile_name: str) -> "NotionAccount": + return replace(self, profile_name=profile_name or DEFAULT_PROFILE) + + def to_dict(self) -> dict[str, Any]: + return { + "profile_name": self.profile_name or DEFAULT_PROFILE, + "token_v2": self.token_v2, + "space_id": self.space_id, + "user_id": self.user_id, + "space_view_id": self.space_view_id, + "user_name": self.user_name, + "user_email": self.user_email, + "cookies": self.cookies, + } + + +def _print_header() -> None: + print("=" * 60) + print("Notion2API Login") + print("=" * 60) + print("This helper saves named Notion profiles into accounts.json.") + print("Default flow: launch a local Chrome window, wait for sign-in, and extract token_v2.") + print("Use --manual to paste token_v2 if Chrome is unavailable.") + + +def _open_login_page() -> None: + try: + webbrowser.open(AI_URL, new=2) + print(f"Opened {AI_URL} in your browser.") + except Exception: + print(f"Open this page manually: {AI_URL}") + + +def _prompt_token() -> str: + print() + print("Step 1: Sign in to Notion in the browser window.") + print("Step 2: Copy your token_v2 value from the Notion cookie store.") + print("Step 3: Paste it below.") + token = input("\nPaste token_v2: ").strip() + if not token: + raise ValueError("token_v2 is required") + return token + + +def _find_free_port(start: int = DEFAULT_DEBUG_PORT, end: int = DEFAULT_DEBUG_PORT + 20) -> int: + for port in range(start, end + 1): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + sock.bind(("127.0.0.1", port)) + except OSError: + continue + return port + raise RuntimeError("No free debugging port found") + + +def _get_json(url: str, timeout: int = 2) -> Any: + with urlopen(url, timeout=timeout) as response: + payload = response.read().decode("utf-8", errors="replace") + return json.loads(payload) + + +def _find_chrome_executable() -> str | None: + env_path = os.getenv("CHROME_PATH") + if env_path: + candidate = Path(env_path).expanduser() + if candidate.exists(): + return str(candidate) + + candidates = [ + "chrome.exe", + "chrome", + "google-chrome", + "google-chrome-stable", + "msedge.exe", + "msedge", + ] + for name in candidates: + resolved = shutil.which(name) + if resolved: + return resolved + + program_files = [ + os.getenv("PROGRAMFILES"), + os.getenv("PROGRAMFILES(X86)"), + os.getenv("LOCALAPPDATA"), + ] + suffixes = [ + r"Google\Chrome\Application\chrome.exe", + r"Google\Chrome Beta\Application\chrome.exe", + r"Google\Chrome Canary\Application\chrome.exe", + r"Microsoft\Edge\Application\msedge.exe", + ] + for root in program_files: + if not root: + continue + for suffix in suffixes: + candidate = Path(root) / suffix + if candidate.exists(): + return str(candidate) + return None + + +def _start_chrome_debug_session(port: int) -> tuple[subprocess.Popen[bytes], Path]: + chrome = _find_chrome_executable() + if not chrome: + raise FileNotFoundError("Chrome or Edge executable not found") + + profile_dir = Path(tempfile.mkdtemp(prefix="notion2api-chrome-profile-")) + args = [ + chrome, + f"--remote-debugging-port={port}", + "--remote-allow-origins=*", + f"--user-data-dir={profile_dir}", + "--no-first-run", + "--no-default-browser-check", + "--start-maximized", + "--new-window", + AI_URL, + ] + process = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + return process, profile_dir + + +class _CDPClient: + def __init__(self, ws_url: str) -> None: + self._ws = create_connection(ws_url, timeout=5) + self._next_id = 1 + + def call(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]: + message_id = self._next_id + self._next_id += 1 + self._ws.send(json.dumps({"id": message_id, "method": method, "params": params or {}})) + while True: + response = json.loads(self._ws.recv()) + if response.get("id") == message_id: + if response.get("error"): + raise RuntimeError(str(response["error"])) + result = response.get("result", {}) + return result if isinstance(result, dict) else {} + + def call_raw(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]: + return self.call(method, params) + + def close(self) -> None: + try: + self._ws.close() + except Exception: + pass + + +def _find_debug_target(port: int) -> dict[str, Any] | None: + try: + targets = _get_json(f"http://127.0.0.1:{port}/json/list") + except Exception: + return None + + items = targets if isinstance(targets, list) else targets.get("result") + if not isinstance(items, list): + return None + + for item in items: + if not isinstance(item, dict): + continue + url = str(item.get("url") or "") + if _NOTION_HOST_HINT in url or "accounts.google.com" in url: + return item + return items[0] if items else None + + +def _parse_cookie_string(cookie_string: str) -> dict[str, str]: + cookies: dict[str, str] = {} + for part in cookie_string.split(";"): + part = part.strip() + if "=" in part: + name, _, value = part.partition("=") + name = name.strip() + value = value.strip() + if name: + cookies[name] = value + return cookies + + +def _extract_cookies_from_cdp(port: int) -> dict[str, str]: + target = _find_debug_target(port) + if not target: + raise RuntimeError("Chrome debugging target not available yet") + + ws_url = target.get("webSocketDebuggerUrl") + if not ws_url: + raise RuntimeError("Chrome debugging target missing websocket URL") + + client = _CDPClient(str(ws_url)) + try: + client.call("Page.enable") + client.call("Network.enable") + + try: + current_url = client.call("Runtime.evaluate", {"expression": "location.href", "returnByValue": True}) + current_href = str(current_url.get("result", {}).get("value") or "") if isinstance(current_url, dict) else "" + if _NOTION_HOST_HINT not in current_href: + client.call("Page.navigate", {"url": AI_URL}) + time.sleep(2) + except Exception: + pass + + cookies: dict[str, str] = {} + + try: + cookie_eval = client.call( + "Runtime.evaluate", + {"expression": "document.cookie", "returnByValue": True}, + ) + cookie_string = "" + if isinstance(cookie_eval, dict): + cookie_string = str(cookie_eval.get("result", {}).get("value") or "") + cookies.update(_parse_cookie_string(cookie_string)) + except Exception: + pass + + cookie_result = client.call("Network.getCookies", {"urls": [BASE_URL, AI_URL]}) + cookies_list = cookie_result.get("cookies", []) + if not isinstance(cookies_list, list): + return cookies + for item in cookies_list: + if not isinstance(item, dict): + continue + name = str(item.get("name") or "").strip() + value = str(item.get("value") or "").strip() + if name: + cookies[name] = value + return cookies + finally: + client.close() + + +def _wait_for_browser_cookies(port: int, timeout_seconds: int = DEFAULT_LOGIN_TIMEOUT) -> dict[str, str]: + started = time.time() + last_error = "" + while time.time() - started < timeout_seconds: + try: + cookies = _extract_cookies_from_cdp(port) + except Exception as exc: + cookies = {} + message = str(exc) + if message and message != last_error: + print(f"Chrome DevTools not ready yet: {message}") + last_error = message + + token_v2 = cookies.get("token_v2", "").strip() + if token_v2: + return cookies + + print("Waiting for token_v2... sign in to the opened Chrome window.") + time.sleep(5) + + raise TimeoutError("Timed out waiting for token_v2 in Chrome") + + +def _launch_and_extract_cookies(timeout_seconds: int = DEFAULT_LOGIN_TIMEOUT) -> dict[str, str]: + port = _find_free_port() + process, profile_dir = _start_chrome_debug_session(port) + try: + try: + _get_json(f"http://127.0.0.1:{port}/json/version", timeout=2) + except Exception: + pass + return _wait_for_browser_cookies(port, timeout_seconds=timeout_seconds) + finally: + try: + process.terminate() + process.wait(timeout=5) + except Exception: + try: + process.kill() + except Exception: + pass + try: + shutil.rmtree(profile_dir, ignore_errors=True) + except Exception: + pass + + +def _launch_and_extract_token(timeout_seconds: int = DEFAULT_LOGIN_TIMEOUT) -> str: + return _launch_and_extract_cookies(timeout_seconds=timeout_seconds).get("token_v2", "") + + +def _session_for_token(token_v2: str, cookies: dict[str, str] | None = None) -> requests.Session: + session = requests.Session() + cookie_values = dict(cookies or {}) + cookie_values["token_v2"] = token_v2 + session.headers.update( + { + "Origin": BASE_URL, + "Referer": AI_URL, + "User-Agent": USER_AGENT, + "Content-Type": "application/json", + "Cookie": "; ".join(f"{name}={value}" for name, value in cookie_values.items() if value), + } + ) + for name, value in cookie_values.items(): + if not value: + continue + session.cookies.set(name, value, domain=NOTION_DOMAIN, path="/") + return session + + +def _safe_value(value: Any) -> dict[str, Any]: + if isinstance(value, dict): + inner = value.get("value") + if isinstance(inner, dict): + return inner + if inner is not None: + return {"value": inner} + return value + return {} + + +def _load_json_response(session: requests.Session, path: str) -> dict[str, Any]: + response = session.post(f"{BASE_URL}{path}", json={}, timeout=30) + response.raise_for_status() + payload = response.json() + return payload if isinstance(payload, dict) else {} + + +def _extract_candidates(token_v2: str, cookies: dict[str, str] | None = None) -> list[NotionAccount]: + cookies = cookies or {} + active_user_id = str(cookies.get("notion_user_id") or "").strip() + session = _session_for_token(token_v2, cookies) + + try: + get_spaces = _load_json_response(session, "/api/v3/getSpaces") + except Exception: + get_spaces = {} + + load_user_content = _load_json_response(session, "/api/v3/loadUserContent").get("recordMap", {}) + + users: dict[str, dict[str, str]] = {} + spaces: dict[str, dict[str, str]] = {} + space_views: dict[str, str] = {} + + def add_users(source: dict[str, Any], target: dict[str, dict[str, str]]) -> None: + for user_id, raw in source.items(): + v = _safe_value(raw) + target[user_id] = { + "name": str(v.get("given_name") or v.get("name") or v.get("family_name") or "").strip(), + "email": str(v.get("email") or "").strip(), + } + + def add_spaces(source: dict[str, Any], target: dict[str, dict[str, str]]) -> None: + for space_id, raw in source.items(): + v = _safe_value(raw) + target[space_id] = { + "name": str(v.get("name") or "").strip(), + "plan": str(v.get("plan_type") or v.get("subscription_tier") or "").strip(), + } + + def add_space_views(source: dict[str, Any], target: dict[str, str]) -> None: + for space_view_id, raw in source.items(): + v = _safe_value(raw) + space_id = str(v.get("space_id") or "").strip() + if space_id: + target.setdefault(space_id, space_view_id) + + def accounts_from_maps( + account_users: dict[str, dict[str, str]], + account_spaces: dict[str, dict[str, str]], + account_space_views: dict[str, str], + ) -> list[NotionAccount]: + accounts: list[NotionAccount] = [] + for user_id, user_data in account_users.items(): + for space_id in account_spaces: + accounts.append( + NotionAccount( + profile_name=DEFAULT_PROFILE, + token_v2=token_v2, + space_id=space_id, + user_id=user_id, + space_view_id=account_space_views.get(space_id, ""), + user_name=user_data["name"] or "user", + user_email=user_data["email"], + cookies=cookies, + ) + ) + return accounts + + candidates: list[NotionAccount] = [] + for raw_user_data in get_spaces.values(): + if not isinstance(raw_user_data, dict): + continue + grouped_users: dict[str, dict[str, str]] = {} + grouped_spaces: dict[str, dict[str, str]] = {} + grouped_space_views: dict[str, str] = {} + add_users(raw_user_data.get("notion_user", {}), grouped_users) + add_spaces(raw_user_data.get("space", {}), grouped_spaces) + add_space_views(raw_user_data.get("space_view", {}), grouped_space_views) + users.update(grouped_users) + spaces.update(grouped_spaces) + space_views.update(grouped_space_views) + candidates.extend(accounts_from_maps(grouped_users, grouped_spaces, grouped_space_views)) + + add_users(load_user_content.get("notion_user", {}), users) + add_spaces(load_user_content.get("space", {}), spaces) + add_space_views(load_user_content.get("space_view", {}), space_views) + + if not users: + raise ValueError("No Notion users were returned. The token may be invalid or expired.") + if not spaces: + raise ValueError("No Notion workspaces were returned. The token may be invalid or expired.") + + if not candidates: + candidates = accounts_from_maps(users, spaces, space_views) + + if active_user_id: + active_candidates = [account for account in candidates if account.user_id == active_user_id] + if active_candidates: + candidates = active_candidates + + candidates.sort( + key=lambda account: ( + 1 if account.user_id == active_user_id else 0, + 1 if account.user_email else 0, + 1 if account.space_view_id else 0, + 1 if account.user_name else 0, + ), + reverse=True, + ) + return candidates + + +def _choose_account(candidates: list[NotionAccount]) -> NotionAccount: + if len(candidates) == 1: + chosen = candidates[0] + print(f"Auto-selected: {chosen.user_name} {f'({chosen.user_email})' if chosen.user_email else ''}") + return chosen + + print() + print("Multiple account combinations were detected. Choose one:") + for index, account in enumerate(candidates, start=1): + label = account.user_name or "(unknown)" + if account.user_email: + label += f" <{account.user_email}>" + if account.space_view_id: + label += f" | space_view_id={account.space_view_id}" + print(f" [{index}] {label}") + + while True: + choice = input(f"Select 1-{len(candidates)}: ").strip() + if choice.isdigit(): + index = int(choice) + if 1 <= index <= len(candidates): + return candidates[index - 1] + print("Invalid selection. Try again.") + + +def _read_accounts_file() -> list[dict[str, Any]]: + if not ACCOUNTS_FILE.exists(): + return [] + try: + data = json.loads(ACCOUNTS_FILE.read_text(encoding="utf-8")) + except json.JSONDecodeError: + return [] + if not isinstance(data, list): + return [] + return [item for item in data if isinstance(item, dict)] + + +def _account_identity(item: dict[str, Any]) -> tuple[str, ...]: + profile_name = str(item.get("profile_name") or "").strip().lower() + if profile_name: + return ("profile", profile_name) + + user_id = str(item.get("user_id") or "").strip() + space_id = str(item.get("space_id") or "").strip() + if user_id and space_id: + return ("account", user_id, space_id) + + return ("raw", json.dumps(item, sort_keys=True, ensure_ascii=False)) + + +def _write_accounts(account: NotionAccount) -> list[dict[str, Any]]: + existing = _read_accounts_file() + merged: list[dict[str, Any]] = [] + identity = _account_identity(account.to_dict()) + + for item in existing: + if _account_identity(item) == identity: + continue + merged.append(item) + + merged.insert(0, account.to_dict()) + ACCOUNTS_FILE.write_text(json.dumps(merged, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + return merged + + +def _sync_env_file(accounts: list[dict[str, Any]]) -> None: + env_line = f"NOTION_ACCOUNTS={json.dumps(accounts, ensure_ascii=False)}" + + if ENV_FILE.exists(): + lines = ENV_FILE.read_text(encoding="utf-8").splitlines() + updated = False + new_lines: list[str] = [] + for line in lines: + stripped = line.lstrip() + if stripped.startswith("NOTION_ACCOUNTS="): + new_lines.append(env_line) + updated = True + else: + new_lines.append(line) + if not updated: + if new_lines and new_lines[-1].strip(): + new_lines.append("") + new_lines.append(env_line) + ENV_FILE.write_text("\n".join(new_lines).rstrip() + "\n", encoding="utf-8") + else: + ENV_FILE.write_text(env_line + "\n", encoding="utf-8") + + +def _validate_account(account: dict[str, Any]) -> tuple[bool, str]: + token_v2 = str(account.get("token_v2") or "").strip() + space_id = str(account.get("space_id") or "").strip() + user_id = str(account.get("user_id") or "").strip() + if not token_v2 or not space_id or not user_id: + return False, "missing required fields" + + account_cookies = account.get("cookies") + if not isinstance(account_cookies, dict): + account_cookies = {} + session = _session_for_token(token_v2, account_cookies) + try: + response = session.post(f"{BASE_URL}/api/v3/loadUserContent", json={}, timeout=30) + if response.status_code != 200: + return False, f"HTTP {response.status_code}" + payload = response.json() + record_map = payload.get("recordMap") if isinstance(payload, dict) else None + if not isinstance(record_map, dict): + return False, "unexpected response" + return True, "token appears valid" + except Exception as exc: + return False, str(exc) + + +def _readable_account_summary(account: NotionAccount) -> str: + user = account.user_name or "user" + if account.user_email: + user = f"{user} ({account.user_email})" + return f"profile={account.profile_name}, user={user}, space_id={account.space_id}" + + +def _find_account(accounts: list[dict[str, Any]], profile_name: str | None) -> dict[str, Any] | None: + if not accounts: + return None + + if profile_name: + target = profile_name.strip().lower() + for item in accounts: + item_profile = str(item.get("profile_name") or "").strip().lower() + if item_profile == target: + return item + return None + + return accounts[0] + + +def _format_account_label(account: dict[str, Any]) -> str: + profile_name = str(account.get("profile_name") or DEFAULT_PROFILE).strip() or DEFAULT_PROFILE + user_name = str(account.get("user_name") or "").strip() + user_email = str(account.get("user_email") or "").strip() + label = f"profile: {profile_name}" + if user_name: + label += f", user: {user_name}" + if user_email: + label += f" ({user_email})" + return label + + +def _print_account_status(account: dict[str, Any]) -> int: + ok, status = _validate_account(account) + print("Saved account:") + print(f" {_format_account_label(account)}") + print(f" space_id: {account.get('space_id', '')}") + print(f" user_id: {account.get('user_id', '')}") + print(f" status: {status}") + return 0 if ok else 1 + + +def _list_accounts(accounts: list[dict[str, Any]]) -> int: + if not accounts: + print("No saved accounts found in accounts.json") + return 1 + + print("Saved profiles:") + for index, account in enumerate(accounts, start=1): + ok, status = _validate_account(account) + marker = "ok" if ok else "invalid" + print(f" [{index}] {_format_account_label(account)} | {marker} | {status}") + return 0 + + +def _check_existing_login(profile_name: str | None = None) -> int: + accounts = _read_accounts_file() + if not accounts: + print("No saved accounts found in accounts.json") + return 1 + + account = _find_account(accounts, profile_name) + if account is None: + available = ", ".join(str(item.get("profile_name") or DEFAULT_PROFILE) for item in accounts) + print(f"Profile not found: {profile_name}") + print(f"Available profiles: {available}") + return 1 + + return _print_account_status(account) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Interactive Notion2API login helper") + parser.add_argument("--check", action="store_true", help="Check a saved profile without prompting") + parser.add_argument("--list", action="store_true", help="List saved profiles and validation state") + parser.add_argument("--profile", default=DEFAULT_PROFILE, help="Profile name to check or save") + parser.add_argument("--manual", action="store_true", help="Paste token_v2 manually instead of launching Chrome") + parser.add_argument("--timeout", type=int, default=DEFAULT_LOGIN_TIMEOUT, help="Seconds to wait for browser sign-in") + parser.add_argument("--no-env", action="store_true", help="Do not update .env automatically") + args = parser.parse_args(list(argv) if argv is not None else None) + + if args.check and args.list: + parser.error("--check and --list cannot be used together") + + if args.list: + return _list_accounts(_read_accounts_file()) + + if args.check: + return _check_existing_login(args.profile) + + _print_header() + + try: + if args.manual: + _open_login_page() + token_v2 = _prompt_token() + cookies = {"token_v2": token_v2} + else: + print(f"Launching Chrome for {AI_URL}...") + print(f"Chrome will wait up to {args.timeout} seconds for token_v2 to appear.") + cookies = _launch_and_extract_cookies(timeout_seconds=args.timeout) + token_v2 = str(cookies.get("token_v2") or "").strip() + print("token_v2 captured from Chrome.") + + candidates = _extract_candidates(token_v2, cookies) + chosen = _choose_account(candidates).with_profile(args.profile) + merged_accounts = _write_accounts(chosen) + if not args.no_env: + _sync_env_file(merged_accounts) + print() + print("Login complete.") + print(f"Saved: {ACCOUNTS_FILE}") + if not args.no_env: + print(f"Updated: {ENV_FILE}") + print(f"Profile: {chosen.profile_name}") + print(f"User: {chosen.user_name} {f'({chosen.user_email})' if chosen.user_email else ''}") + print(f"Workspace: {chosen.space_id}") + if chosen.space_view_id: + print(f"Space view: {chosen.space_view_id}") + print(f"Summary: {_readable_account_summary(chosen)}") + return 0 + except KeyboardInterrupt: + print("\nCancelled.") + return 1 + except TimeoutError as exc: + print(f"\nLogin timed out: {exc}") + print("Try --manual if you want to paste token_v2 instead.") + return 1 + except Exception as exc: + print(f"\nLogin failed: {exc}") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..fcddca5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +requests +cloudscraper +python-dotenv +fastapi +uvicorn[standard] +pydantic +slowapi +httpx +websocket-client +playwright diff --git a/scripts/deploy.bat b/scripts/deploy.bat new file mode 100644 index 0000000..6bf5829 --- /dev/null +++ b/scripts/deploy.bat @@ -0,0 +1,84 @@ +@echo off +REM ========================================== +REM Notion-AI Docker 部署脚本 (Windows) +REM ========================================== + +echo ========================================== +echo Notion-AI Docker 部署脚本 +echo ========================================== +echo. + +REM 检查 Docker 是否安装 +docker --version >nul 2>&1 +if errorlevel 1 ( + echo ❌ Docker 未安装,请先安装 Docker Desktop + pause + exit /b 1 +) + +REM 检查 .env 文件是否存在 +if not exist .env ( + echo ⚠️ .env 文件不存在,正在从 .env.example 创建... + if exist .env.example ( + copy .env.example .env >nul + echo ✅ 已创建 .env 文件 + echo 📝 请编辑 .env 文件,填入你的 Notion 账号信息 + echo 编辑完成后,再次运行此脚本 + pause + exit /b 0 + ) else ( + echo ❌ .env.example 文件不存在 + pause + exit /b 1 + ) +) + +REM 创建必要的目录 +echo 📁 创建数据目录... +if not exist data mkdir data +if not exist logs mkdir logs + +REM 构建镜像 +echo 🔨 构建 Docker 镜像... +docker-compose build --no-cache + +REM 启动服务 +echo 🚀 启动服务... +docker-compose up -d + +REM 等待服务启动 +echo ⏳ 等待服务启动... +timeout /t 5 /nobreak >nul + +REM 检查服务状态 +echo. +echo 📊 服务状态: +docker-compose ps + +REM 检查健康状态 +echo. +echo 🏥 健康检查: +curl -s http://localhost:8000/health >nul 2>&1 +if errorlevel 1 ( + echo ❌ 服务启动失败,请查看日志: + echo docker-compose logs +) else ( + echo ✅ 服务运行正常! + echo. + echo 🌐 访问地址: + echo - Web 界面: http://localhost:8000 + echo - API 文档: http://localhost:8000/docs + echo - 健康检查: http://localhost:8000/health + echo. + echo 📝 查看日志: + echo docker-compose logs -f + echo. + echo 🛑 停止服务: + echo docker-compose down +) + +echo. +echo ========================================== +echo 部署完成! +echo ========================================== +pause diff --git a/scripts/deploy.sh b/scripts/deploy.sh new file mode 100644 index 0000000..4b9e2eb --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,84 @@ +#!/bin/bash +# ========================================== +# Notion-AI Docker 部署脚本 +# ========================================== + +set -e # 遇到错误立即退出 + +echo "==========================================" +echo " Notion-AI Docker 部署脚本" +echo "==========================================" + +# 检查 Docker 是否安装 +if ! command -v docker &> /dev/null; then + echo "❌ Docker 未安装,请先安装 Docker" + exit 1 +fi + +# 检查 Docker Compose 是否安装 +if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then + echo "❌ Docker Compose 未安装,请先安装 Docker Compose" + exit 1 +fi + +# 检查 .env 文件是否存在 +if [ ! -f .env ]; then + echo "⚠️ .env 文件不存在,正在从 .env.example 创建..." + if [ -f .env.example ]; then + cp .env.example .env + echo "✅ 已创建 .env 文件" + echo "📝 请编辑 .env 文件,填入你的 Notion 账号信息" + echo " 编辑完成后,再次运行此脚本" + exit 0 + else + echo "❌ .env.example 文件不存在" + exit 1 + fi +fi + +# 创建必要的目录 +echo "📁 创建数据目录..." +mkdir -p data logs + +# 构建镜像 +echo "🔨 构建 Docker 镜像..." +docker-compose build --no-cache + +# 启动服务 +echo "🚀 启动服务..." +docker-compose up -d + +# 等待服务启动 +echo "⏳ 等待服务启动..." +sleep 5 + +# 检查服务状态 +echo "" +echo "📊 服务状态:" +docker-compose ps + +# 检查健康状态 +echo "" +echo "🏥 健康检查:" +if curl -s http://localhost:8000/health > /dev/null; then + echo "✅ 服务运行正常!" + echo "" + echo "🌐 访问地址:" + echo " - Web 界面: http://localhost:8000" + echo " - API 文档: http://localhost:8000/docs" + echo " - 健康检查: http://localhost:8000/health" + echo "" + echo "📝 查看日志:" + echo " docker-compose logs -f" + echo "" + echo "🛑 停止服务:" + echo " docker-compose down" +else + echo "❌ 服务启动失败,请查看日志:" + echo " docker-compose logs" +fi + +echo "" +echo "==========================================" +echo " 部署完成!" +echo "==========================================" diff --git a/scripts/extract_notion_info.js b/scripts/extract_notion_info.js new file mode 100644 index 0000000..5e34722 --- /dev/null +++ b/scripts/extract_notion_info.js @@ -0,0 +1,237 @@ +/** + * Notion 账号信息提取脚本(旧版手动备用流程) + * + * 推荐优先运行 `python login.py`。该登录脚本会自动打开临时 Chrome/Edge + * 调试窗口,并从本地浏览器会话中提取 token_v2 和账号/工作区字段。 + * + * 如果自动登录流程不可用,可以使用本手动脚本: + * 1. 浏览器登录 https://www.notion.so/ai + * 2. 确保左上角切换到你要提取的账号 + * 3. F12 → Application → Cookies → 复制 token_v2 的值 + * 4. F12 → Console → 粘贴本脚本 → 回车 + * 5. 如果有多个账号/工作区,按提示选择 + * 6. 把输出的 JSON 粘贴到 accounts.json,替换 YOUR_TOKEN_V2 + */ +(async () => { + try { + // ─── 第 1 步:获取所有可访问的用户和空间 ─── + // getSpaces 会返回当前 token 能看到的所有用户(含多账号) + let allUsers = {}; // user_id → {name, email} + let allSpaces = {}; // space_id → {name, plan, members} + let spaceViewMap = {}; // space_id → space_view_id + + // 尝试 getSpaces(返回更完整的多账号数据) + try { + const r1 = await fetch('/api/v3/getSpaces', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: '{}', credentials: 'include' + }); + const d1 = await r1.json(); + // getSpaces 返回 { "user_id_1": { space: {...}, ... }, "user_id_2": {...} } + if (d1 && typeof d1 === 'object' && !d1.recordMap) { + for (const [userId, userData] of Object.entries(d1)) { + if (!userData || typeof userData !== 'object') continue; + // 提取用户信息 + const nu = userData.notion_user; + if (nu) { + for (const [nuid, nuData] of Object.entries(nu)) { + const v = nuData?.value?.value || nuData?.value || nuData || {}; + allUsers[nuid] = { + name: v.given_name || v.name || v.family_name || '', + email: v.email || '' + }; + } + } + // 提取空间信息 + const sp = userData.space; + if (sp) { + for (const [sid, sData] of Object.entries(sp)) { + const v = sData?.value?.value || sData?.value || sData || {}; + if (!allSpaces[sid]) { + allSpaces[sid] = { + name: v.name || '', + plan: v.plan_type || v.subscription_tier || '' + }; + } + } + } + // 提取 space_view + const sv = userData.space_view; + if (sv) { + for (const [svid, svData] of Object.entries(sv)) { + const v = svData?.value?.value || svData?.value || svData || {}; + if (v.space_id) spaceViewMap[v.space_id] = svid; + } + } + } + } + } catch (e) { /* getSpaces 失败,fallback 到 loadUserContent */ } + + // fallback:loadUserContent + const r2 = await fetch('/api/v3/loadUserContent', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: '{}', credentials: 'include' + }); + const d2 = (await r2.json()).recordMap || {}; + + // 合并用户 + for (const [nuid, nuData] of Object.entries(d2.notion_user || {})) { + if (allUsers[nuid]) continue; + const v = nuData?.value?.value || nuData?.value || nuData || {}; + allUsers[nuid] = { + name: v.given_name || v.name || v.family_name || '', + email: v.email || '' + }; + } + // 合并空间 + for (const [sid, sData] of Object.entries(d2.space || {})) { + if (allSpaces[sid]) continue; + const v = sData?.value?.value || sData?.value || sData || {}; + allSpaces[sid] = { + name: v.name || '', + plan: v.plan_type || v.subscription_tier || '' + }; + } + // 合并 space_view + for (const [svid, svData] of Object.entries(d2.space_view || {})) { + const v = svData?.value?.value || svData?.value || svData || {}; + if (v.space_id && !spaceViewMap[v.space_id]) spaceViewMap[v.space_id] = svid; + } + + // 读取 cookie 中的 notion_user_id(当前 UI 上的活跃账号) + const cookieUserId = document.cookie.split(';') + .map(c => c.trim()) + .find(c => c.startsWith('notion_user_id=')) + ?.split('=')[1] || ''; + + const userList = Object.entries(allUsers); + const spaceList = Object.entries(allSpaces).map(([id, s]) => ({ + space_id: id, name: s.name, plan: s.plan, space_view_id: spaceViewMap[id] || '' + })); + + if (userList.length === 0) { + console.error('❌ 未找到任何用户信息,请确认已登录 Notion'); + return; + } + + // ─── 展示 & 选择用户 ─── + console.log('\n'); + console.log('%c═══════════════════════════════════════════════', 'color:#00a699'); + console.log('%c Notion 账号信息提取工具', 'font-size:15px;font-weight:bold;color:#00a699'); + console.log('%c═══════════════════════════════════════════════', 'color:#00a699'); + console.log(''); + + let chosenUserId, chosenUserName, chosenUserEmail; + + if (userList.length === 1) { + chosenUserId = userList[0][0]; + chosenUserName = userList[0][1].name; + chosenUserEmail = userList[0][1].email; + console.log(`%c👤 用户: ${chosenUserName || '(未知)'} ${chosenUserEmail ? '(' + chosenUserEmail + ')' : ''}`, 'font-size:13px'); + } else { + console.log(`%c👥 检测到 ${userList.length} 个 Notion 账号:`, 'font-size:13px;font-weight:bold'); + console.log(''); + userList.forEach(([uid, u], i) => { + const active = uid === cookieUserId ? ' ← 当前活跃' : ''; + console.log(`%c [${i}] ${u.name || '(未知)'} ${u.email ? '(' + u.email + ')' : ''}${active}`, 'font-size:13px'); + }); + console.log(''); + console.log('%c👆 请查看上方账号列表,3 秒后弹窗选择...', 'color:#ff9800;font-size:12px'); + + await new Promise(resolve => setTimeout(resolve, 3000)); + + const promptText = userList.map(([uid, u], i) => { + const active = uid === cookieUserId ? ' ← 当前' : ''; + return `[${i}] ${u.name || '(未知)'} ${u.email ? '(' + u.email + ')' : ''}${active}`; + }).join('\n'); + + const idx = prompt(`请选择要提取的账号:\n\n${promptText}\n\n输入编号 (0 ~ ${userList.length - 1}):`); + if (idx === null || idx.trim() === '') { + console.log('%c⚠️ 已取消', 'color:#ff9800'); + return; + } + const chosen = userList[parseInt(idx)]; + if (!chosen) { + console.error(`❌ 编号 "${idx}" 无效`); + return; + } + chosenUserId = chosen[0]; + chosenUserName = chosen[1].name; + chosenUserEmail = chosen[1].email; + } + + console.log(`%c✅ 选择用户: ${chosenUserName || chosenUserId.slice(0,8)} ${chosenUserEmail ? '(' + chosenUserEmail + ')' : ''}`, 'color:#00c853;font-size:13px'); + + // ─── 选择工作区 ─── + if (spaceList.length === 0) { + console.error('❌ 未找到任何工作区'); + return; + } + + console.log(''); + console.log(`%c📂 找到 ${spaceList.length} 个工作区:`, 'font-size:13px;font-weight:bold'); + console.log(''); + spaceList.forEach((s, i) => { + const label = s.name || `(ID: ${s.space_id.slice(0, 13)}...)`; + const planStr = s.plan ? ` 计划: ${s.plan}` : ''; + console.log(`%c [${i}] ${label}${planStr}`, 'font-size:13px'); + }); + + let chosenSpace; + if (spaceList.length === 1) { + chosenSpace = spaceList[0]; + console.log('%c🎯 只有一个工作区,自动选择', 'color:#2196f3;font-weight:bold'); + } else { + console.log(''); + console.log('%c👆 3 秒后弹窗选择工作区...', 'color:#ff9800;font-size:12px'); + await new Promise(resolve => setTimeout(resolve, 3000)); + + const promptText = spaceList.map((s, i) => { + const label = s.name || `ID: ${s.space_id.slice(0, 13)}...`; + return `[${i}] ${label}`; + }).join('\n'); + + const idx = prompt(`请选择有 AI 功能的工作区:\n\n${promptText}\n\n输入编号 (0 ~ ${spaceList.length - 1}):`); + if (idx === null || idx.trim() === '') { + console.log('%c⚠️ 已取消', 'color:#ff9800'); + return; + } + chosenSpace = spaceList[parseInt(idx)]; + if (!chosenSpace) { + console.error(`❌ 编号 "${idx}" 无效`); + return; + } + } + + // ─── 输出结果 ─── + const account = { + token_v2: 'YOUR_TOKEN_V2', + space_id: chosenSpace.space_id, + user_id: chosenUserId, + space_view_id: chosenSpace.space_view_id, + user_name: chosenUserName, + user_email: chosenUserEmail + }; + + const json = JSON.stringify(account, null, 2); + const spaceLabel = chosenSpace.name || chosenSpace.space_id.slice(0, 13) + '...'; + + console.log(''); + console.log('%c═══════════════════════════════════════════════', 'color:#00c853'); + console.log(`%c✅ 用户: ${chosenUserName || '(未知)'} 工作区: ${spaceLabel}`, 'color:#00c853;font-weight:bold;font-size:14px'); + console.log('%c═══════════════════════════════════════════════', 'color:#00c853'); + console.log(''); + console.log(json); + console.log(''); + console.log('%c⚠️ 下一步:把 YOUR_TOKEN_V2 替换为你复制的 token_v2 值', 'color:#ff9800;font-weight:bold'); + console.log('%c 然后粘贴到 accounts.json 数组中', 'color:#ff9800'); + console.log('%c ⚠️ 注意:token_v2 要用你选择的那个账号的!在 Cookies 里确认', 'color:#ff9800'); + + setTimeout(() => { + navigator.clipboard.writeText(json) + .then(() => console.log('%c📋 已自动复制到剪贴板', 'color:#00c853')) + .catch(() => console.log('%c📋 请手动选中上方 JSON 复制', 'color:#ff9800')); + }, 800); + + } catch (e) { console.error('❌ 提取失败:', e.message) } +})(); diff --git a/scripts/manage.sh b/scripts/manage.sh new file mode 100644 index 0000000..b44112e --- /dev/null +++ b/scripts/manage.sh @@ -0,0 +1,104 @@ +#!/bin/bash +# ========================================== +# Notion-AI 服务管理脚本 +# ========================================== + +case "$1" in + start) + echo "🚀 启动服务..." + docker-compose up -d + ;; + stop) + echo "🛑 停止服务..." + docker-compose down + ;; + restart) + echo "🔄 重启服务..." + docker-compose restart + ;; + status) + echo "📊 服务状态:" + docker-compose ps + echo "" + echo "🏥 健康检查:" + curl -s http://localhost:8000/health | jq . 2>/dev/null || curl -s http://localhost:8000/health + ;; + logs) + echo "📝 查看日志(Ctrl+C 退出):" + docker-compose logs -f + ;; + build) + echo "🔨 重新构建镜像..." + docker-compose build --no-cache + ;; + update) + echo "🔄 更新并重启服务..." + docker-compose down + docker-compose build --no-cache + docker-compose up -d + ;; + clean) + echo "🧹 清理容器和镜像..." + docker-compose down -v + docker system prune -f + ;; + backup) + echo "💾 备份数据库..." + BACKUP_DIR="backups/$(date +%Y%m%d_%H%M%S)" + mkdir -p "$BACKUP_DIR" + cp data/conversations.db "$BACKUP_DIR/" + echo "✅ 备份完成: $BACKUP_DIR" + ;; + restore) + if [ -z "$2" ]; then + echo "❌ 请指定备份目录,例如: ./manage.sh restore backups/20240306_120000" + exit 1 + fi + echo "📥 恢复数据库..." + cp "$2/conversations.db" data/ + echo "✅ 恢复完成,请重启服务: ./manage.sh restart" + ;; + shell) + echo "🐚 进入容器 Shell..." + docker-compose exec notion-opus /bin/bash + ;; + test) + echo "🧪 测试 API..." + echo "发送测试请求..." + curl -X POST http://localhost:8000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "claude-opus4.6", + "messages": [{"role": "user", "content": "Hello"}], + "stream": false + }' + ;; + *) + echo "==========================================" + echo " Notion-AI 服务管理脚本" + echo "==========================================" + echo "用法: ./manage.sh {command}" + echo "" + echo "命令:" + echo " start - 启动服务" + echo " stop - 停止服务" + echo " restart - 重启服务" + echo " status - 查看状态" + echo " logs - 查看日志" + echo " build - 重新构建镜像" + echo " update - 更新并重启服务" + echo " clean - 清理容器和镜像" + echo " backup - 备份数据库" + echo " restore - 恢复数据库 (需要指定备份目录)" + echo " shell - 进入容器 Shell" + echo " test - 测试 API" + echo "" + echo "示例:" + echo " ./manage.sh start" + echo " ./manage.sh logs" + echo " ./manage.sh backup" + echo " ./manage.sh restore backups/20240306_120000" + echo "==========================================" + exit 1 + ;; +esac diff --git a/tools/farm.py b/tools/farm.py new file mode 100644 index 0000000..cd84c05 --- /dev/null +++ b/tools/farm.py @@ -0,0 +1,347 @@ +# Notion Opus/GPT-6.1 free farm — FULL PIPELINE +# 1. Voidash mailbox 2. Signup + code 3. Onboarding 4. Model select + test message +# Usage: python farm.py N [model] +import asyncio, json, re, sys, time, random, string, os +import httpx +from playwright.async_api import async_playwright + +BASE = os.path.dirname(os.path.abspath(__file__)) +OUT = BASE + "/farm_accounts.jsonl" +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36" +VOIDASH_DOMAINS = ["voidash.bond"] +NOTION_SIGNUP = "https://www.notion.so/signup" +FIRSTS = ["alex", "maria", "peter", "laura", "stef", "anna", "tony", "nina", "eric", "sara", "luca", "jana", "tom", "lena", "paul", "kate"] + + +def voidash_create(): + domain = random.choice(VOIDASH_DOMAINS) + with httpx.Client(timeout=25, trust_env=False) as c: + r = c.post("https://api.voidash.com/api/v1/inboxes", json={"domain": domain}) + if r.status_code not in (200, 201): + return None, f"voidash {r.status_code}: {r.text[:100]}" + d = r.json() + return d["address"], d["session_key"] + + +def voidash_wait_code(session_key, deadline_s=240, since_ts=None): + t0 = time.time() + if since_ts is None: + since_ts = t0 + headers = {"Authorization": f"Bearer {session_key}"} + with httpx.Client(timeout=25, trust_env=False, headers=headers) as c: + while time.time() - t0 < deadline_s: + try: + r = c.get("https://api.voidash.com/api/v1/messages") + if r.status_code == 200: + msgs = r.json() + if isinstance(msgs, dict): + msgs = msgs.get("messages", msgs.get("data", [])) + for m in msgs: + try: + created = m.get("created_at") or "" + if created and since_ts: + from datetime import datetime, timezone + cts = datetime.fromisoformat(created.replace("Z", "+00:00")).timestamp() + if cts < since_ts - 120: + continue + except Exception: + pass + subj = (m.get("subject") or "").lower() + frm = json.dumps(m.get("from", {})).lower() + if "notion" in subj or "notion" in frm: + full_body = m.get("body") or m.get("text") or "" + if not full_body: + try: + r2 = c.get(f"https://api.voidash.com/api/v1/messages/{m['id']}") + full_body = r2.json().get("body") or r2.json().get("text") or "" + except Exception: + pass + lines = [l.strip() for l in full_body.splitlines() if l.strip()] + for l in lines[:4]: + if re.fullmatch(r'[A-Za-z0-9]{6,8}', l): + return l + m2 = re.search(r'\b([A-Za-z0-9]{6})\b', full_body[:200]) + if m2: + return m2.group(1) + except Exception as e: + print("voidash err:", str(e)[:120]) + time.sleep(6) + return None + + +async def farm_one(model="Opus"): + res = {"status": "error", "step": "init", "model": model} + # 1) mailbox + addr, key = voidash_create() + if not addr: + res["error"] = key + return res + res["email"] = addr + res["voidash_key"] = key + print("MAILBOX:", addr) + + async with async_playwright() as p: + browser = await p.chromium.launch(headless=True, args=["--no-sandbox"]) + ctx = await browser.new_context(user_agent=UA, viewport={"width": 1600, "height": 1000}) + page = await ctx.new_page() + try: + # ===== 2) signup ===== + await page.goto(NOTION_SIGNUP, wait_until="domcontentloaded", timeout=60000) + await page.wait_for_timeout(4000) + email_input = page.locator("input[type=email]").first + await email_input.fill(addr) + await page.wait_for_timeout(600) + cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont.count(): + await cont.click() + else: + await email_input.press("Enter") + await page.wait_for_timeout(5000) + body = (await page.inner_text("body")).lower() + if "invalid email domain" in body or "problem" in body: + res["error"] = "rejected: " + body[:150] + await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png") + return res + + # ===== 3) code ===== + if "verification" in body or "code" in body: + sent_ts = time.time() + code = await asyncio.to_thread(voidash_wait_code, key, 240, sent_ts) + if not code: + res["error"] = "otp-not-found" + await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png") + return res + res["otp"] = code + print("CODE:", code) + code_input = page.locator("input[autocomplete=one-time-code], input[inputmode=numeric], input[name=code]").first + if await code_input.count(): + await code_input.fill(code) + else: + inputs = page.locator("input") + cnt = await inputs.count() + filled = False + for j in range(cnt): + inp = inputs.nth(j) + t = await inp.get_attribute("type") or "" + ph = (await inp.get_attribute("placeholder") or "").lower() + if t not in ("email", "password") and "mail" not in ph: + await inp.fill(code) + filled = True + break + if not filled: + cells = page.locator("input[maxlength=1]") + cc = await cells.count() + for j, ch in enumerate(code): + if j < cc: + await cells.nth(j).fill(ch) + await page.wait_for_timeout(600) + cont2 = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont2.count(): + await cont2.click() + await page.wait_for_timeout(7000) + + # password (если есть) + body = (await page.inner_text("body")).lower() + pw_input = page.locator("input[type=password]").first + if "password" in body and await pw_input.count(): + pw = "Not!" + ''.join(random.choices(string.ascii_letters + string.digits, k=10)) + res["password"] = pw + await pw_input.fill(pw) + await page.wait_for_timeout(400) + cont3 = page.get_by_role("button", name=re.compile("Continue|Sign up|Create", re.I)).first + if await cont3.count(): + await cont3.click() + else: + await pw_input.press("Enter") + await page.wait_for_timeout(7000) + + # ===== 4) onboarding ===== + for attempt in range(15): + body = (await page.inner_text("body")).lower() + if "customize your profile" in body or "your name" in body: + name_inputs = page.locator("input[type=text], input:not([type])") + cnt = await name_inputs.count() + for j in range(min(cnt, 1)): + await name_inputs.nth(j).fill(random.choice(FIRSTS).capitalize() + " " + random.choice(FIRSTS).capitalize()) + cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont.count(): + await cont.click() + for _ in range(10): + await page.wait_for_timeout(1500) + b2 = (await page.inner_text("body")).lower() + if "customize your profile" not in b2 and "your name" not in b2: + break + continue + if "how do you want to use" in body: + opt = page.get_by_text(re.compile("for personal|for myself", re.I)).first + if await opt.count(): + await opt.click() + await page.wait_for_timeout(2000) + cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont.count(): + await cont.click() + await page.wait_for_timeout(3000) + continue + if "start with your real work" in body or "connect email" in body: + btn = page.get_by_role("button", name=re.compile("Start from scratch", re.I)).first + if await btn.count(): + await btn.click() + # ждём смены экрана + for _ in range(10): + await page.wait_for_timeout(1500) + b2 = (await page.inner_text("body")).lower() + if "start with your real work" not in b2: + break + continue + if "create" in body and "workspace" in body: + btn = page.get_by_role("button", name=re.compile("Create new workspace", re.I)).first + if await btn.count(): + await btn.click() + await page.wait_for_timeout(4000) + continue + if "desktop" in body and ("skip" in body or "faster" in body): + skip = page.get_by_role("button", name=re.compile("skip for now|skip", re.I)).first + if await skip.count(): + await skip.click() + await page.wait_for_timeout(3000) + continue + if "/onboarding" not in page.url: + break + # generic continue — только кликабельные кнопки без disabled + cont = page.locator('button:enabled, [role=button]:not([aria-disabled="true"])').filter(has_text=re.compile(r"^\s*(Continue|Next|Get started)\s*$", re.I)).first + if await cont.count(): + await cont.click() + await page.wait_for_timeout(3000) + else: + break + + res["post_onboarding_url"] = page.url + print("POST-ONBOARDING:", page.url) + + # ===== 5) model select + test ===== + # Если после онбординга мы уже на /chat — НЕ делаем goto (перезагрузка убивает чат-сессию) + if "/chat" not in page.url: + await page.goto("https://app.notion.com/chat", wait_until="domcontentloaded", timeout=60000) + try: + await page.locator('[aria-label="Choose AI model"]').first.wait_for(state="visible", timeout=45000) + except Exception: + # fallback: перезагрузка + повторное ожидание + try: + await page.goto("https://app.notion.com/chat", wait_until="domcontentloaded", timeout=60000) + await page.locator('[aria-label="Choose AI model"]').first.wait_for(state="visible", timeout=45000) + except Exception: + res["error"] = "chat/model button missing" + await ctx.storage_state(path=f"{BASE}/state_{addr.replace('@', '_at_').replace('.', '_')}.json") + res["state_path"] = f"{BASE}/state_{addr.replace('@', '_at_').replace('.', '_')}.json" + res["status"] = "registered-no-chat" + await browser.close() + return res + await page.wait_for_timeout(2000) + await page.locator('[aria-label="Choose AI model"]').first.click() + await page.wait_for_timeout(2500) + items = page.locator('[role=menuitem]') + cnt = await items.count() + target = None + for j in range(cnt): + t = await items.nth(j).inner_text() + if model.lower() in t.lower(): + target = items.nth(j) + break + if target is None: + res["error"] = f"model {model} not in menu" + else: + await target.click() + await page.wait_for_timeout(2000) + print("MODEL SELECTED:", model) + # test message + chat_box = page.locator('[contenteditable=true]').first + await chat_box.click() + await chat_box.fill("Hello! Which model are you? Answer in one short sentence.") + await page.wait_for_timeout(500) + submit = page.locator('[aria-label="Submit AI message"]').first + if await submit.count(): + await submit.click() + else: + await chat_box.press("Enter") + # wait response + for i in range(40): + await page.wait_for_timeout(2500) + body = (await page.inner_text("body")).lower() + if "working on your request" not in body and "connecting the details" not in body: + if "hello! which model" in body: + break + body_full = await page.inner_text("body") + # extract reply: текст после нашего промпта + try: + idx = body_full.lower().rfind("hello! which model") + reply = body_full[idx + 200:idx + 600].strip() + res["ai_reply"] = reply[:300] + except Exception: + pass + res["model_active"] = model + res["final_url"] = page.url + state_path = f"{BASE}/state_{addr.replace('@', '_at_').replace('.', '_')}.json" + await ctx.storage_state(path=state_path) + res["state_path"] = state_path + if "signup" not in page.url and "login" not in page.url and "appeals" not in page.url: + res["status"] = "ok" + else: + res["status"] = "incomplete" + await page.screenshot(path=f"{BASE}/final_{int(time.time())}.png") + except Exception as e: + res["error"] = str(e)[:300] + try: + await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png") + except Exception: + pass + finally: + await browser.close() + return res + + +async def main(): + if len(sys.argv) > 1 and sys.argv[1] == "--export": + export_pool() + return + n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + model = sys.argv[2] if len(sys.argv) > 2 else "Opus" + for i in range(n): + print(f"=== farm {i+1}/{n} model={model} ===") + res = await farm_one(model) + with open(OUT, "a", encoding="utf-8") as f: + f.write(json.dumps(res, ensure_ascii=False) + "\n") + print("RESULT:", json.dumps(res, ensure_ascii=False)[:700]) + if res.get("status") != "ok" and i + 1 < n: + print("-> continuing to next account") + + +if __name__ == "__main__": + asyncio.run(main()) + + +def export_pool(): + """Конвертирует farm_accounts.jsonl → accounts.json для app/ сервера.""" + accounts = [] + if not os.path.exists(OUT): + print("farm_accounts.jsonl не найден — сначала запусти ферму") + return + with open(OUT, encoding="utf-8") as f: + for line in f: + try: + rec = json.loads(line) + except Exception: + continue + if rec.get("status") != "ok": + continue + accounts.append({ + "token_v2": rec.get("token_v2") or "", + "space_id": rec.get("space_id") or "", + "user_id": rec.get("user_id") or "", + "space_view_id": rec.get("space_view_id") or "", + "user_name": rec.get("user_name") or "", + "user_email": rec.get("email") or "", + }) + out_path = os.path.join(os.path.dirname(BASE), "accounts.json") + with open(out_path, "w", encoding="utf-8") as f: + json.dump(accounts, f, ensure_ascii=False, indent=2) + print(f"export: {len(accounts)} аккаунтов -> {out_path}") diff --git a/tools/mail_provider.py b/tools/mail_provider.py new file mode 100644 index 0000000..b9cede1 --- /dev/null +++ b/tools/mail_provider.py @@ -0,0 +1,106 @@ +# Test mail.tm for Notion signup (fresh unique inboxes) +import asyncio, json, re, random, string, time +from playwright.async_api import async_playwright +import httpx + +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36" +BASE = os.path.dirname(os.path.abspath(__file__)) + +def mailtm_create(): + firsts = ["alex", "maria", "peter", "laura", "stef", "anna", "tony", "nina", "eric", "sara", "luca", "jana", "tom", "lena", "paul", "kate"] + with httpx.Client(timeout=20, trust_env=False) as c: + r = c.get("https://api.mail.tm/domains") + domain = r.json()["hydra:member"][0]["domain"] + addr = random.choice(firsts) + random.choice(firsts) + str(random.randint(100, 999)) + "@" + domain + pw = ''.join(random.choices(string.ascii_letters + string.digits, k=12)) + r = c.post("https://api.mail.tm/accounts", json={"address": addr, "password": pw}) + if r.status_code not in (200, 201): + return None, None, None, r.text + # token + r2 = c.post("https://api.mail.tm/token", json={"address": addr, "password": pw}) + tok = r2.json().get("token") + return addr, pw, tok, "ok" + +def mailtm_wait_code(tok, deadline_s=200): + t0 = time.time() + headers = {"Authorization": f"Bearer {tok}"} + with httpx.Client(timeout=20, trust_env=False, headers=headers) as c: + while time.time() - t0 < deadline_s: + try: + r = c.get("https://api.mail.tm/messages") + msgs = r.json().get("hydra:member", []) + for m in msgs: + if "notion" in (m.get("from", {}).get("address", "") + m.get("subject", "")).lower(): + # тело письма + r2 = c.get(f"https://api.mail.tm/messages/{m['id']}") + d = r2.json() + text = (d.get("text") or "") + " " + (d.get("subject") or "") + mm = re.search(r'\b([A-Za-z0-9]{6})\b', (d.get("text") or "")[:300]) + if not mm: + lines = [l.strip() for l in (d.get("text") or "").splitlines() if l.strip()] + for l in lines[:5]: + if re.fullmatch(r'[A-Za-z0-9]{6,8}', l): + return l + if mm: + return mm.group(1) + except Exception as e: + print("mailtm err:", str(e)[:100]) + time.sleep(5) + return None + +async def main(): + addr, pw, tok, st = mailtm_create() + if not addr: + print("MAILTM FAIL:", st) + return + print("MAILBOX:", addr) + async with async_playwright() as p: + browser = await p.chromium.launch(headless=True, args=["--no-sandbox"]) + ctx = await browser.new_context(user_agent=UA, viewport={"width": 1366, "height": 900}) + page = await ctx.new_page() + await page.goto("https://www.notion.so/signup", wait_until="domcontentloaded", timeout=60000) + await page.wait_for_timeout(4000) + email_input = page.locator("input[type=email]").first + await email_input.fill(addr) + await page.wait_for_timeout(600) + cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont.count(): + await cont.click() + await page.wait_for_timeout(6000) + body = (await page.inner_text("body")).lower() + if "problem" in body: + print("REJECTED (problem signing up)") + await page.screenshot(path=f"{BASE}/mailtm_rejected.png") + elif "verification" in body or "code" in body: + print("CODE SENT — waiting IMAP-less...") + code = mailtm_wait_code(tok) + print("CODE:", code) + if code: + code_input = page.locator("input[autocomplete=one-time-code], input[inputmode=numeric], input[name=code]").first + if await code_input.count(): + await code_input.fill(code) + else: + inputs = page.locator("input") + cnt = await inputs.count() + for j in range(cnt): + inp = inputs.nth(j) + t = await inp.get_attribute("type") or "" + if t not in ("email", "password"): + await inp.fill(code) + break + await page.wait_for_timeout(600) + cont2 = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont2.count(): + await cont2.click() + await page.wait_for_timeout(8000) + body2 = (await page.inner_text("body")).lower() + print("AFTER CODE URL:", page.url) + print("AFTER CODE BODY:", body2[:300]) + await page.screenshot(path=f"{BASE}/mailtm_after_code.png") + await ctx.storage_state(path=f"{BASE}/state_mailtm_test.json") + else: + print("UNKNOWN STATE:", body[:300]) + await page.screenshot(path=f"{BASE}/mailtm_unknown.png") + await browser.close() + +asyncio.run(main()) diff --git a/tools/notion_reg.py b/tools/notion_reg.py new file mode 100644 index 0000000..1ba193f --- /dev/null +++ b/tools/notion_reg.py @@ -0,0 +1,267 @@ +# Notion autoreg FINAL: Voidash inbox -> Notion signup -> code -> onboarding -> session +# Usage: python notion_reg.py N +import asyncio, json, re, sys, time, random, string, os +import httpx +from playwright.async_api import async_playwright + +BASE = os.path.dirname(os.path.abspath(__file__)) +OUT = BASE + "/accounts.jsonl" +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36" +VOIDASH_DOMAINS = ["voidash.bond"] +NOTION_SIGNUP = "https://www.notion.so/signup" + +FIRSTS = ["alex", "maria", "peter", "laura", "stef", "anna", "tony", "nina", "eric", "sara", "luca", "jana", "tom", "lena", "paul", "kate"] + + +def voidash_create(): + """Создать ящик Voidash. Возвращает (address, session_key) или (None, err).""" + domain = random.choice(VOIDASH_DOMAINS) + with httpx.Client(timeout=25, trust_env=False) as c: + r = c.post("https://api.voidash.com/api/v1/inboxes", json={"domain": domain}) + if r.status_code not in (200, 201): + return None, f"voidash {r.status_code}: {r.text[:100]}" + d = r.json() + return d["address"], d["session_key"] + + +def voidash_wait_code(session_key, deadline_s=240, since_ts=None): + """Ждать код Notion в Voidash inbox. Возвращает код или None.""" + t0 = time.time() + if since_ts is None: + since_ts = t0 + headers = {"Authorization": f"Bearer {session_key}"} + with httpx.Client(timeout=25, trust_env=False, headers=headers) as c: + while time.time() - t0 < deadline_s: + try: + r = c.get("https://api.voidash.com/api/v1/messages") + if r.status_code == 200: + msgs = r.json() + if isinstance(msgs, dict): + msgs = msgs.get("messages", msgs.get("data", [])) + for m in msgs: + try: + created = m.get("created_at") or m.get("received_at") or "" + if created and since_ts: + # iso timestamp + from datetime import datetime, timezone + cts = datetime.fromisoformat(created.replace("Z", "+00:00")).timestamp() + if cts < since_ts - 120: + continue + except Exception: + pass + subj = (m.get("subject") or "").lower() + frm = json.dumps(m.get("from", {})).lower() + body_preview = (m.get("body") or m.get("text") or m.get("body_preview") or "")[:200] + if "notion" in subj or "notion" in frm: + full_body = m.get("body") or m.get("text") or "" + if not full_body: + # fetch single message + try: + r2 = c.get(f"https://api.voidash.com/api/v1/messages/{m['id']}") + full_body = r2.json().get("body") or r2.json().get("text") or "" + except Exception: + pass + text = subj + "\n" + full_body + m2 = re.search(r'(?:code is|code:)\s*[:\s]*([A-Za-z0-9]{5,8})\b', text, re.I) + if not m2: + lines = [l.strip() for l in full_body.splitlines() if l.strip()] + for l in lines[:4]: + if re.fullmatch(r'[A-Za-z0-9]{6,8}', l): + return l + if not m2: + m2 = re.search(r'\b([A-Za-z0-9]{6})\b', full_body[:200]) + if m2: + return m2.group(1) + except Exception as e: + print("voidash err:", str(e)[:120]) + time.sleep(6) + return None + + +async def main(): + n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + for i in range(n): + print(f"=== reg {i+1}/{n} ===") + res = await register_one() + with open(OUT, "a", encoding="utf-8") as f: + f.write(json.dumps(res, ensure_ascii=False) + "\n") + print("RESULT:", json.dumps(res, ensure_ascii=False)[:700]) + + +async def register_one(): + res = {"status": "error", "step": "init"} + # 1) mailbox + addr, key = voidash_create() + if not addr: + res["error"] = key + return res + res["email"] = addr + res["voidash_key"] = key + print("MAILBOX:", addr) + + async with async_playwright() as p: + browser = await p.chromium.launch(headless=True, args=["--no-sandbox"]) + ctx = await browser.new_context(user_agent=UA, viewport={"width": 1366, "height": 900}) + page = await ctx.new_page() + try: + await page.goto(NOTION_SIGNUP, wait_until="domcontentloaded", timeout=60000) + await page.wait_for_timeout(4000) + # 2) email + email_input = page.locator("input[type=email]").first + await email_input.fill(addr) + await page.wait_for_timeout(600) + cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont.count(): + await cont.click() + else: + await email_input.press("Enter") + res["step"] = "email-submitted" + await page.wait_for_timeout(5000) + body = (await page.inner_text("body")).lower() + if "invalid email domain" in body or "problem" in body: + res["error"] = "rejected: " + body[:150] + await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png") + return res + + # 3) verification code + if "verification" in body or "code" in body: + res["step"] = "await-otp" + print("waiting for code...") + sent_ts = time.time() + code = await asyncio.to_thread(voidash_wait_code, key, 240, sent_ts) + if not code: + res["error"] = "otp-not-found" + await page.screenshot(path=f"{BASE}/err_{int(time.time())}.pxng" if False else f"{BASE}/err_{int(time.time())}.png") + return res + res["otp"] = code + print("CODE:", code) + code_input = page.locator("input[autocomplete=one-time-code], input[inputmode=numeric], input[name=code]").first + if await code_input.count(): + await code_input.fill(code) + else: + inputs = page.locator("input") + cnt = await inputs.count() + filled = False + for j in range(cnt): + inp = inputs.nth(j) + t = await inp.get_attribute("type") or "" + ph = (await inp.get_attribute("placeholder") or "").lower() + if t not in ("email", "password") and "mail" not in ph: + await inp.fill(code) + filled = True + break + if not filled: + cells = page.locator("input[maxlength=1]") + cc = await cells.count() + for j, ch in enumerate(code): + if j < cc: + await cells.nth(j).fill(ch) + await page.wait_for_timeout(600) + cont2 = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont2.count(): + await cont2.click() + await page.wait_for_timeout(7000) + res["step"] = "code-submitted" + + # 4) password (если требуется) + body = (await page.inner_text("body")).lower() + pw_input = page.locator("input[type=password]").first + if "password" in body and await pw_input.count(): + pw = "Not!" + ''.join(random.choices(string.ascii_letters + string.digits, k=10)) + res["password"] = pw + res["step"] = "password-step" + await pw_input.fill(pw) + await page.wait_for_timeout(400) + cont3 = page.get_by_role("button", name=re.compile("Continue|Sign up|Create", re.I)).first + if await cont3.count(): + await cont3.click() + else: + await pw_input.press("Enter") + await page.wait_for_timeout(7000) + + # 5) workspace + onboarding loop + for attempt in range(12): + body = (await page.inner_text("body")).lower() + if "customize your profile" in body or "your name" in body: + res["step"] = f"profile-{attempt}" + await handle_profile(page) + await page.wait_for_timeout(3000) + continue + if "create" in body and "workspace" in body: + res["step"] = f"workspace-{attempt}" + btn = page.get_by_role("button", name=re.compile("Create new workspace", re.I)).first + if await btn.count(): + await btn.click() + await page.wait_for_timeout(4000) + continue + if "what should we call" in body or "what would you like" in body or "name your" in body or "getting started" in body: + res["step"] = f"onboarding-{attempt}" + await handle_onboarding(page) + await page.wait_for_timeout(3000) + continue + break + + res["final_url"] = page.url + res["body_final"] = (await page.inner_text("body")).lower()[:300] + state_path = f"{BASE}/state_{addr.replace('@', '_at_').replace('.', '_')}.json" + await ctx.storage_state(path=state_path) + res["state_path"] = state_path + if "signup" not in page.url and "login" not in page.url and "appeals" not in page.url: + res["status"] = "ok" + else: + res["status"] = "incomplete" + await page.screenshot(path=f"{BASE}/final_{int(time.time())}.png") + except Exception as e: + res["error"] = str(e)[:300] + try: + await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png") + except Exception: + pass + finally: + await browser.close() + return res + + +async def handle_profile(page): + # "Customize your profile" — "Your name" input + Continue + name_inputs = page.locator("input[type=text], input:not([type]), input[name=name], input[placeholder*='name' i]") + cnt = await name_inputs.count() + for j in range(min(cnt, 1)): + await name_inputs.nth(j).fill(random.choice(FIRSTS).capitalize() + " " + random.choice(FIRSTS).capitalize()) + cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first + if await cont.count(): + await cont.click() + await page.wait_for_timeout(3000) + + +async def handle_onboarding(page): + text_inputs = page.locator("input[type=text], input:not([type])") + cnt = await text_inputs.count() + filled = 0 + for j in range(min(cnt, 2)): + inp = text_inputs.nth(j) + try: + ph = (await inp.get_attribute("placeholder") or "").lower() + except Exception: + ph = "" + if "name" in ph or "call" in ph: + await inp.fill("Alex") + filled += 1 + elif "workspace" in ph or "team" in ph: + await inp.fill("My Workspace") + filled += 1 + elif filled == 0: + await inp.fill("Alex") + filled += 1 + radios = page.locator("input[type=radio]") + rc = await radios.count() + if rc: + await radios.first.check() + cont = page.get_by_role("button", name=re.compile("Continue|Next|Get started|Create", re.I)).first + if await cont.count(): + await cont.click() + await page.wait_for_timeout(2500) + + +if __name__ == "__main__": + asyncio.run(main())