diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..57d717be2d7a4eaf562f7705cbba17e0d59ba8dd --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +__pycache__ +*.pyc +*.pyo +*.pyd +.Python +.env +.env.* +.git +.gitignore +.logs +logs +/data +/data/* +/data/tmp +/data/tmp/* +/tests diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..9f7a3c01b149169085b0962c2ff6f6e13e141296 --- /dev/null +++ b/.env.example @@ -0,0 +1,49 @@ +# Grok2API environment example +# +# 用法: +# 1. 复制为 .env 后按需修改 +# 2. 启动期 / 部署期变量放这里 +# 3. 常规运行时配置优先改 ${DATA_DIR}/config.toml + + +# ==================== 基础运行 ==================== +TZ=Asia/Shanghai +LOG_LEVEL=INFO +# 写入本地文件日志 +LOG_FILE_ENABLED=true +# 账号目录增量同步间隔(秒) +ACCOUNT_SYNC_INTERVAL=30 + + +# ==================== Web 服务 / Docker Compose ==================== +SERVER_HOST=0.0.0.0 +SERVER_PORT=8000 +SERVER_WORKERS=1 + +# Docker Compose 宿主机映射端口 +HOST_PORT=8000 + + +# ==================== 账号存储(启动期) ==================== +# 可选:local | redis | mysql | postgresql +ACCOUNT_STORAGE=local + +# redis: Redis DSN(ACCOUNT_STORAGE=redis 时必填) +# ACCOUNT_REDIS_URL=redis://:password@host:6379/0 + +# mysql: SQLAlchemy DSN +# ACCOUNT_MYSQL_URL=mysql+aiomysql://user:password@127.0.0.1:3306/grok2api + +# postgresql: SQLAlchemy DSN +# ACCOUNT_POSTGRESQL_URL=postgresql+asyncpg://user:password@127.0.0.1:5432/grok2api + +# SQL 连接池(mysql / postgresql 模式,以下均为默认值,无需改动即可生效) +# ACCOUNT_SQL_POOL_SIZE=5 +# ACCOUNT_SQL_MAX_OVERFLOW=10 +# ACCOUNT_SQL_POOL_TIMEOUT=30 +# ACCOUNT_SQL_POOL_RECYCLE=1800 + + +# ==================== 可选:本地数据 / 日志目录 ==================== +DATA_DIR=./data +LOG_DIR=./logs diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000000000000000000000000000000000..de32320ceadaf431de26915795a05e0c89dbdcb3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,39 @@ +name: Bug +description: 反馈缺陷或异常行为 +title: "bug: " +labels: [bug] +body: + - type: textarea + id: description + attributes: + label: 问题描述 + placeholder: 发生了什么,和预期行为有何不同? + validations: + required: true + + - type: textarea + id: steps + attributes: + label: 复现步骤 + placeholder: | + 1. 启动服务,配置为 xxx + 2. 调用 xxx 接口 + 3. 报错 / 出现异常行为 + validations: + required: true + + - type: input + id: version + attributes: + label: 版本 + placeholder: v1.x.x 或 commit hash + validations: + required: true + + - type: textarea + id: logs + attributes: + label: 相关日志 + render: shell + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..d561c41e75e0e1dbd7bf98a16bc66ef60c014c30 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: 文档与使用说明 + url: https://blog.cheny.me/blog/posts/grok2api + about: 提交 Issue 前请先查看文档,很多常见问题已有说明。 diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 0000000000000000000000000000000000000000..b7740d94cb3f53d554fbd76e81058cdc547d6894 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,20 @@ +name: Feature +description: 新功能或现有功能增强建议 +title: "feat: " +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: 背景 / 痛点 + placeholder: 当前有什么不足?这个需求的使用场景是什么? + validations: + required: true + + - type: textarea + id: solution + attributes: + label: 期望行为 + placeholder: 希望如何工作?有没有参考实现? + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml new file mode 100644 index 0000000000000000000000000000000000000000..0728c13f33f65edb611c77a1b0c9524bc3b179cb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.yml @@ -0,0 +1,20 @@ +name: Question +description: 使用疑问或行为确认 +title: "question: " +labels: [question] +body: + - type: textarea + id: question + attributes: + label: 问题 + validations: + required: true + + - type: textarea + id: context + attributes: + label: 上下文(配置 / 日志) + description: 相关配置请脱敏,日志请贴关键部分。 + render: shell + validations: + required: false diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000000000000000000000000000000000..383b55f4750b79ce9220010437165f85918d14dc --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,11 @@ +## Summary + + + +## Testing + + + +## Related + + diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000000000000000000000000000000000000..c049c517911462eabf24f727a88471d7f782765f --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,63 @@ +name: Build Docker Image + +on: + push: + branches: + - main + tags: + - 'v*' + pull_request: + branches: + - main + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + build-and-push: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + id-token: write + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to Container Registry + if: github.event_name != 'pull_request' + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=raw,value=latest,enable=${{ github.ref_type == 'branch' }} + type=ref,event=tag + type=semver,pattern={{version}} + + - name: Build and push Docker image + uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/amd64,linux/arm64 + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + pull: true \ No newline at end of file diff --git a/.github/workflows/pr-meta.yml b/.github/workflows/pr-meta.yml new file mode 100644 index 0000000000000000000000000000000000000000..9ff791648b650df2d19cfb8a824ccf5b9cc8eb75 --- /dev/null +++ b/.github/workflows/pr-meta.yml @@ -0,0 +1,16 @@ +name: PR + +on: + pull_request: + types: [opened, edited, synchronize, reopened] + +permissions: + pull-requests: read + +jobs: + title: + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/privoxy.yml b/.github/workflows/privoxy.yml new file mode 100644 index 0000000000000000000000000000000000000000..5470b3cd84cf6c7d7f24a98c06c01c8e6212f3b3 --- /dev/null +++ b/.github/workflows/privoxy.yml @@ -0,0 +1,39 @@ +name: Build Privoxy-WARP Image + +on: + push: + branches: [main] + paths: + - Dockerfile.privoxy + workflow_dispatch: + +jobs: + build-and-push: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GHCR + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push privoxy-warp + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile.privoxy + platforms: linux/amd64,linux/arm64 + push: true + tags: ghcr.io/${{ github.repository_owner }}/privoxy-warp:latest diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml new file mode 100644 index 0000000000000000000000000000000000000000..b507a611f65549efb92d49c3a989b1fcb37a9699 --- /dev/null +++ b/.github/workflows/security.yml @@ -0,0 +1,63 @@ +name: Security + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: "0 3 * * 1" + +permissions: + contents: read + +jobs: + gitleaks: + name: Gitleaks Secret Scanner + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # 针对 PR:使用原生逻辑 + - name: Setup PR commits & Run Gitleaks + if: github.event_name == 'pull_request' + run: | + git fetch --no-tags --prune --depth=1 origin \ + "+${{ github.event.pull_request.base.sha }}:refs/remotes/origin/pr-base" + git remote add pr-head "https://github.com/${{ github.event.pull_request.head.repo.full_name }}.git" + git fetch --no-tags --prune --depth=1 pr-head \ + "+${{ github.event.pull_request.head.sha }}:refs/remotes/pr-head/current" + + docker run --rm \ + -v "$PWD:/repo" \ + -w /repo \ + zricethezav/gitleaks:v8.24.3 \ + detect --source . --redact -v --exit-code=2 \ + --log-opts="--no-merges refs/remotes/origin/pr-base..refs/remotes/pr-head/current" + + # 针对 Push 和 Schedule:使用官方 Action + - name: Run Gitleaks Action + if: github.event_name != 'pull_request' + uses: gitleaks/gitleaks-action@v2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITLEAKS_ENABLE_UPLOAD_ARTIFACT: true + GITLEAKS_ENABLE_SUMMARY: true + continue-on-error: true + + pip-audit: + name: Python Dependency Audit + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install uv + uses: astral-sh/setup-uv@v3 + - name: Export requirements + run: uv export --frozen --no-dev --format requirements-txt -o /tmp/req.txt + - name: Run pip-audit + run: | + uvx pip-audit -r /tmp/req.txt --progress-spinner off \ + --ignore-vuln PYSEC-2026-161 + echo "Dependency audit passed" \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e94a37e418e3abe2ce18a11ea68a572c997a865f --- /dev/null +++ b/.gitignore @@ -0,0 +1,55 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# Virtual Environment +.venv/ +venv/ +ENV/ +env/ + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store + +# Environment Variables +.env + +# Logs +logs/ +*.log + +# Data +data/ +app/data/ + +# Testing +.pytest_cache/ +.coverage +htmlcov/ + +# Project specific +.ace-tool/ diff --git a/.python-version b/.python-version new file mode 100644 index 0000000000000000000000000000000000000000..24ee5b1be9961e38a503c8e764b7385dbb6ba124 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.13 diff --git a/Dockerfile b/Dockerfile index 88a8a0f74d395a4c2d1e941e091f9a78e8e817c5..a48752ae00ed6b39834f064255ff105d216b356c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,44 +1,77 @@ -FROM python:3.11-slim - -# 设置环境变量,强制修改路径与端口以适配 Hugging Face -# 🌟 关键修改:将 DATA_DIR 指向 HF 的永久存储卷 /data -ENV TZ=Asia/Shanghai \ - LOG_LEVEL=INFO \ - ACCOUNT_STORAGE=local \ - DATA_DIR=/data \ - LOG_DIR=/app/grok2api/logs \ - PORT=7860 - -# ---- 如果你的 Python 代码支持读取环境变量,请在这里定义(移到 CMD 前面) ---- -ENV APP_BASE_URL="https://lifevta-grok2api.hf.space/" -ENV ENABLE_WEBUI="true" -ENV TEMPORARY_SESSIONS="false" -ENV CONVERSATION_MEMORY="true" -ENV CONDENSED_REASONING="true" -ENV DYNAMIC_STATSIG="true" -ENV ALLOW_NSFW_GENERATION="true" -# ---------------------------------------------------------------------- - -# 安装基础系统依赖 -RUN apt-get update && apt-get install -y --no-install-recommends \ - git \ - curl \ +# ── Builder ─────────────────────────────────────────────────────────────────── +FROM python:3.13-alpine AS builder + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + UV_PROJECT_ENVIRONMENT=/opt/venv + +ENV PATH="$UV_PROJECT_ENVIRONMENT/bin:$PATH" + +# Rust/Cargo are required to compile curl-cffi wheels on musl/Alpine. +# If upstream ever ships musl wheels, remove cargo + rust to speed up builds. +RUN apk add --no-cache \ + ca-certificates \ + build-base \ + linux-headers \ + libffi-dev \ + openssl-dev \ + curl-dev \ + cargo \ + rust + +WORKDIR /app + +# Pin uv to a minor version for reproducible builds. +# Bump manually when you want to pick up a newer uv release. +COPY --from=ghcr.io/astral-sh/uv:0.6 /uv /uvx /bin/ + +COPY pyproject.toml uv.lock ./ + +RUN uv sync --frozen --no-dev --no-install-project \ + && find /opt/venv -type d \ + \( -name "__pycache__" -o -name "tests" -o -name "test" -o -name "testing" \) \ + -prune -exec rm -rf {} + \ + && find /opt/venv -type f -name "*.pyc" -delete \ + && find /opt/venv -type f -name "*.so" -exec strip --strip-unneeded {} + 2>/dev/null; true \ + && rm -rf /root/.cache /tmp/uv-cache + +# ── Runtime ─────────────────────────────────────────────────────────────────── +FROM python:3.13-alpine + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + TZ=Asia/Shanghai \ + VIRTUAL_ENV=/opt/venv \ + SERVER_HOST=0.0.0.0 \ + SERVER_PORT=8000 \ + SERVER_WORKERS=1 + +ENV PATH="$VIRTUAL_ENV/bin:$PATH" + +RUN apk add --no-cache \ + tzdata \ ca-certificates \ - build-essential \ - && rm -rf /var/lib/apt/lists/* + libffi \ + openssl \ + libgcc \ + libstdc++ \ + libcurl + +WORKDIR /app + +COPY --from=builder /opt/venv /opt/venv -# 克隆目标仓库到独立目录 -RUN git clone --depth=1 https://github.com/jiujiu532/grok2api.git /app/grok2api -WORKDIR /app/grok2api +COPY pyproject.toml config.defaults.toml ./ +COPY app ./app +COPY scripts ./scripts -# 安装 uv 包管理器并同步项目依赖 -RUN pip install --no-cache-dir uv && uv sync +RUN mkdir -p /app/data /app/logs \ + && chmod +x /app/scripts/entrypoint.sh /app/scripts/init_storage.sh -# 创建日志文件夹并赋权(/data 目录由 HF 自动管理权限,无需手动 mkdir) -RUN mkdir -p /app/grok2api/logs && chmod -R 777 /app/grok2api +EXPOSE 8000 -# 显式暴露 Hugging Face 规定的 7860 端口 -EXPOSE 7860 +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD ["sh", "-c", "wget -qO /dev/null http://127.0.0.1:${SERVER_PORT}/health || exit 1"] -# 启动命令 -CMD ["uv", "run", "granian", "--interface", "asgi", "--host", "0.0.0.0", "--port", "7860", "app.main:app"] \ No newline at end of file +ENTRYPOINT ["/app/scripts/entrypoint.sh"] +CMD ["sh", "-c", "exec granian --interface asgi --host ${SERVER_HOST} --port ${SERVER_PORT} --workers ${SERVER_WORKERS} app.main:app"] diff --git a/Dockerfile.privoxy b/Dockerfile.privoxy new file mode 100644 index 0000000000000000000000000000000000000000..4232e8be4a9cc9a203cd020e4d8826c056623b8e --- /dev/null +++ b/Dockerfile.privoxy @@ -0,0 +1,9 @@ +FROM alpine:latest + +RUN apk add --no-cache privoxy && \ + echo "listen-address 0.0.0.0:8118" >> /etc/privoxy/config && \ + echo "forward-socks5 / warp-proxy:1080 ." >> /etc/privoxy/config + +EXPOSE 8118 + +CMD ["privoxy", "--no-daemon", "--user", "privoxy", "/etc/privoxy/config"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..16c55bbbc3577f8e13af37b54d23fe310492a170 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Chenyme + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 3d412c7127864cb201cc5dd3bba59c5fe6eee622..3da931308d47b7c107a3f3701eebe54ab7d42483 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,459 @@ +
+ +Grok2API + +

Grok Web 能力的 OpenAI 兼容网关

+ +

多账号池、智能选号、自动维护

+ +

+将 grok.com 与 console.x.ai 的聊天、图像、视频能力,
+以 OpenAI / Anthropic 兼容 API 统一对外提供。 +

+ +

+Python +FastAPI +Docker +License +

+ +

+核心特性 · +部署指南 · +模型列表 · +账号配置 · +API 端点 · +常见问题 +

+ +
+ +> [!NOTE] +> 本项目仅供学习与研究交流。请务必遵守 Grok 的使用条款及当地法律法规,不得用于非法用途。 + +本仓库基于上游 [chenyme/grok2api](https://github.com/chenyme/grok2api) 二次开发,新增多账号池管理、Console 免费模型、配额轮换、防封部署等能力。欢迎 PR 和 Fork,二开请保留原作者与前端标识。 + +--- + +## 核心特性 + +| 能力 | 说明 | +| :-- | :-- | +| OpenAI 兼容 | `/v1/chat/completions`、`/v1/responses`、`/v1/images/generations`、`/v1/videos` | +| Anthropic 兼容 | `/v1/messages`(Claude SDK 直接对接) | +| 多账号池 | basic / super / heavy 三级池,自动负载均衡与配额同步 | +| 免费账号 | 支持 `console.x.ai` SSO Token,`*-console` 模型零成本使用 | +| 媒体生成 | 文生图、图像编辑、文生视频、图生视频,本地缓存与代理链接 | +| 防封内置 | `x-statsig-id` 兼容修复,WARP + FlareSolverr 一键部署 | +| 管理后台 | Admin 配置、账号管理、Web Chat、Masonry 画廊、ChatKit 语音 | + +--- + +## 部署指南 + +本项目提供两种部署方式: + +| 方式 | 说明 | 适用场景 | +| :-- | :-- | :-- | +| **标准版** | 仅 grok2api,直连 Grok | IP 干净、无 Cloudflare 拦截 | +| **防封版** | grok2api + WARP + Privoxy + FlareSolverr | IP 被 Cloudflare 拦截、需要稳定访问 | + +> [!TIP] +> 当前版本已内置 403 兼容修复,标准版可直接验证。仍遇 403 时再切防封版。 + +--- + +### 标准版部署 + +**Docker Compose(推荐):** + +```bash +git clone https://github.com/jiujiu532/grok2api +cd grok2api/grok2api-main/grok2api-main +cp .env.example .env +docker compose up -d +``` + +查看日志: + +```bash +docker compose logs -f grok2api +``` + +**Docker 单容器:** + +```bash +docker run -d --name grok2api \ + -p 8000:8000 \ + -e TZ=Asia/Shanghai \ + -e LOG_LEVEL=INFO \ + -e ACCOUNT_STORAGE=local \ + -v $(pwd)/data:/app/data \ + -v $(pwd)/logs:/app/logs \ + --restart unless-stopped \ + ghcr.io/jiujiu532/grok2api:latest +``` + +Windows PowerShell: + +```powershell +docker run -d ` + --name grok2api ` + -p 8000:8000 ` + -e TZ=Asia/Shanghai ` + -e LOG_LEVEL=INFO ` + -e ACCOUNT_STORAGE=local ` + -v ${PWD}/data:/app/data ` + -v ${PWD}/logs:/app/logs ` + --restart unless-stopped ` + ghcr.io/jiujiu532/grok2api:latest +``` + +--- + +### 防封版部署 + +> **前置要求**:服务器需支持 `NET_ADMIN` + `SYS_MODULE` 权限(KVM/XEN 虚拟化均支持,OpenVZ/LXC 不支持)。 + +```bash +git clone https://github.com/jiujiu532/grok2api +cd grok2api/grok2api-main/grok2api-main +docker compose -f docker-compose.warp.yml up -d +``` + +防封版自动启动以下服务: + +| 服务 | 说明 | +| :-- | :-- | +| `warp-proxy` | Cloudflare WARP 出口代理,提供干净 IP | +| `privoxy` | HTTP 代理,将流量转发到 WARP | +| `flaresolverr` | 自动解 Cloudflare 挑战,获取 cf_clearance | +| `init-config` | 初始化容器,自动写入代理配置 | +| `grok2api` | 主服务 | + +启动后代理配置已自动完成,进入 Admin 后台添加账号即可使用。 + --- -title: Grok2API -emoji: ⚡ -colorFrom: blue -colorTo: indigo -sdk: docker -pinned: false -storage: small + +
+升级 / 回滚 / 卸载 / 迁移 + +### 升级 + +无论标准版还是防封版,升级时只需更新 `grok2api` 主镜像,防封组件不需要更新。 + +**标准版升级:** + +```bash +docker pull ghcr.io/jiujiu532/grok2api:latest +docker compose up -d --no-deps grok2api +``` + +**防封版升级(只更新主服务,不动 WARP/FlareSolverr):** + +```bash +docker pull ghcr.io/jiujiu532/grok2api:latest +docker compose -f docker-compose.warp.yml up -d --no-deps grok2api +``` + +> `--no-deps` 确保只重启 grok2api,WARP/Privoxy/FlareSolverr 继续运行不中断。 +> +> `./data/` 中的配置(`config.toml`)和数据库(`accounts.db`)挂载在 volume 中,升级不会覆盖。 + +### 回滚 + +```bash +# 查看可用版本:https://github.com/jiujiu532/grok2api/pkgs/container/grok2api +docker pull ghcr.io/jiujiu532/grok2api: + +# 标准版回滚 +docker compose up -d --no-deps grok2api + +# 防封版回滚 +docker compose -f docker-compose.warp.yml up -d --no-deps grok2api +``` + +### 卸载 + +**标准版卸载:** + +```bash +cd grok2api/grok2api-main/grok2api-main +docker compose down +# 如需删除数据(不可恢复): +rm -rf ./data ./logs +``` + +**防封版卸载:** + +```bash +cd grok2api/grok2api-main/grok2api-main +docker compose -f docker-compose.warp.yml down +# 如需删除数据(不可恢复): +rm -rf ./data ./logs +``` + +### 从标准版迁移到防封版 + +数据完全保留,无需重新配置: + +```bash +# 停止标准版 +docker compose down + +# 用防封版启动(自动检测已有配置,不覆盖) +docker compose -f docker-compose.warp.yml up -d +``` + +
+ --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file +### 本地源码部署 + +前置:Python 3.13+、[uv](https://docs.astral.sh/uv/getting-started/installation/) + +```bash +git clone https://github.com/jiujiu532/grok2api +cd grok2api/grok2api-main/grok2api-main +cp .env.example .env && uv sync +uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app +``` + +--- + +### 首次启动 + +访问 `http://localhost:8000/admin/login`,默认密码 `grok2api`,进入后设置: + +1. `app.app_key` — Admin 密码 +2. `app.api_key` — API 鉴权密钥(留空不鉴权) +3. `app.app_url` — 公网地址(图片/视频链接需要) + +> 配置保存即时生效,无需重启。 + +--- + +## 模型列表 + +### Chat( grok.com) + +basic表示free账号,spuer和heavy 为付费 + +| 模型名 | mode | 账号等级 | 备注 | +| :-- | :-- | :-- | :-- | +| `grok-4.20-fast` / `grok-4.3-fast` | fast | basic(优先高等级) | +| `grok-4.20-auto` | auto | super | +| `grok-4.20-expert` | expert | super | +| `grok-4.20-heavy` | heavy | heavy | | +| `grok-4.3-beta` | grok-420-computer-use-sa | super | +| `grok-4.20-multi-agent-0309` | heavy | heavy | +| `grok-4.20-0309-non-reasoning` | fast | basic | +| `grok-4.20-0309` | auto | super | +| `grok-4.20-0309-reasoning` | expert | super | +| `grok-4.20-0309-non-reasoning-super` | fast | super | +| `grok-4.20-0309-super` | auto | super | +| `grok-4.20-0309-reasoning-super` | expert | super | +| `grok-4.20-0309-non-reasoning-heavy` | fast | heavy | +| `grok-4.20-0309-heavy` | auto | heavy | +| `grok-4.20-0309-reasoning-heavy` | expert | heavy | + +### Chat( console.x.ai) + +通过 SSO Token 免费访问,不消耗付费额度。所有免费模型使用 **basic** 等级账号。 + +| 模型名 | reasoning effort | 账号等级 | +| :-- | :-- | :-- | +| `grok-4.3-console` | 用户传入(默认 medium) | basic | +| `grok-4.3-low` | low(固定) | basic | +| `grok-4.3-medium` | medium(固定) | basic | +| `grok-4.3-high` | high(固定) | basic | +| `grok-4.20-0309-console` | 默认 | basic | +| `grok-4.20-0309-reasoning-console` | 固定 reasoning | basic | +| `grok-4.20-0309-non-reasoning-console` | 无 reasoning | basic | +| `grok-4.20-multi-agent-console` | 用户传入(默认 medium) | basic| +| `grok-4.20-multi-agent-low` | low(固定)→ 4 agents | basic| +| `grok-4.20-multi-agent-medium` | medium(固定)→ 4 agents | basic| +| `grok-4.20-multi-agent-high` | high(固定)→ 16 agents | basic | +| `grok-4.20-multi-agent-xhigh` | xhigh(固定)→ 16 agents | basic| +| `grok-build-console` | 默认 | basic | + +**Console 配额**:30 次 / 15 分钟窗口,采用延迟恢复轮换策略(消耗至剩余 15 次时启动计时器,评分机制自动轮换到其他账号)。后台每 30 秒巡检并自动重置过期配额。 + +### Image / Video( grok.com) + +| 模型名 | 能力 | 账号等级 | +| :-- | :-- | :-- | +| `grok-imagine-image-lite` | 文生图 | basic | +| `grok-imagine-image` / `image-pro` | 文生图 | super | +| `grok-imagine-image-edit` | 图像编辑 | super | +| `grok-imagine-video` | 文生视频 | super | + +--- + + + +## 账号配置 + +| 类型 | 等级 | 适用模型 | +| :-- | :-- | :-- | +| 付费账号(x.ai 官方) | super / heavy | `grok-4.20-*`、`grok-4.3-beta`、`grok-4.3-fast` | +| 免费账号(console.x.ai SSO) | basic | 所有 `*-console` / `*-low` / `*-medium` / `*-high` / `*-xhigh` | + +**免费账号获取方式**: + +1. 浏览器 F12 打开开发者工具 +2. 访问 `https://console.x.ai/` +3. Network 面板找任意请求,Cookie 中复制 `sso` 值 +4. Admin 后台 → 账号管理 → 添加账号,粘贴 token + +> SSO Token 属于敏感凭证,请勿写入代码或提交到版本库。 + +--- + +## API 端点 + +| 端点 | 说明 | +| :-- | :-- | +| `GET /v1/models` | 列出可用模型 | +| `POST /v1/chat/completions` | 聊天 / 图像 / 视频统一入口 | +| `POST /v1/responses` | OpenAI Responses API | +| `POST /v1/messages` | Anthropic Messages API | +| `POST /v1/images/generations` | 图像生成 | +| `POST /v1/images/edits` | 图像编辑 | +| `POST /v1/videos` | 异步视频任务 | +| `GET /v1/videos/{id}` / `{id}/content` | 查询 / 下载视频 | + +--- + +## 环境变量 + +| 变量名 | 说明 | 默认值 | +| :-- | :-- | :-- | +| `TZ` | 时区 | `Asia/Shanghai` | +| `LOG_LEVEL` | 日志级别 | `INFO` | +| `LOG_FILE_ENABLED` | 写入本地文件日志 | `true` | +| `SERVER_HOST` | 监听地址 | `0.0.0.0` | +| `SERVER_PORT` | 监听端口 | `8000` | +| `SERVER_WORKERS` | Granian worker 数量 | `1` | +| `HOST_PORT` | Compose 宿主机映射端口 | `8000` | +| `DATA_DIR` | 本地数据根目录 | `./data` | +| `LOG_DIR` | 本地日志目录 | `./logs` | +| `ACCOUNT_STORAGE` | 存储后端:`local` / `redis` / `mysql` / `postgresql` | `local` | +| `ACCOUNT_SYNC_INTERVAL` | 增量同步间隔(秒) | `30` | +| `ACCOUNT_SYNC_ACTIVE_INTERVAL` | 活跃同步间隔(秒) | `3` | +| `ACCOUNT_LOCAL_PATH` | SQLite 路径 | `${DATA_DIR}/accounts.db` | +| `ACCOUNT_REDIS_URL` | Redis DSN | `""` | +| `ACCOUNT_MYSQL_URL` | MySQL DSN | `""` | +| `ACCOUNT_POSTGRESQL_URL` | PostgreSQL DSN | `""` | +| `ACCOUNT_SQL_POOL_SIZE` | 连接池核心连接数 | `5` | +| `ACCOUNT_SQL_MAX_OVERFLOW` | 连接池最大溢出 | `10` | +| `ACCOUNT_SQL_POOL_TIMEOUT` | 等待空闲连接超时(秒) | `30` | +| `ACCOUNT_SQL_POOL_RECYCLE` | 连接最大复用时间(秒) | `1800` | + +运行时配置支持 `GROK_` 前缀覆盖,如 `GROK_APP_API_KEY` 覆盖 `app.api_key`。 + +--- + +## 调用示例 + +```bash +# 付费账号对话 +curl http://localhost:8000/v1/chat/completions \ + -H "Authorization: Bearer $API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"model":"grok-4.20-auto","stream":true,"messages":[{"role":"user","content":"你好"}]}' + +# 免费账号对话 +curl http://localhost:8000/v1/chat/completions \ + -H "Authorization: Bearer $API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"model":"grok-4.3-console","stream":true,"messages":[{"role":"user","content":"你好"}]}' +``` + +--- + +## 常见问题 + +| 问题 | 解决方案 | +| :-- | :-- | +| Admin 打不开 | 确认端口映射和防火墙:`docker compose ps` | +| 图片/视频链接 403 | 设置 `app.app_url` 为公网地址(含 `https://`) | +| Cloudflare 拦截 | 更换代理,或者切换防封版部署,再或者手动配置 `proxy.clearance.mode` | +| 多 Worker 冲突 | 无冲突,调度器通过文件锁选举 leader | + +--- + +## 更新日志 + +### v0.1.7 + +**新功能** + +- 🔌 **Console 原生工具调用支持**([PR#24](https://github.com/jiujiu532/grok2api/pull/24),感谢 @daoguademeng) + - Console 模型支持 OpenAI 兼容的 `tools` / `tool_choice` 参数 + - 客户端 function tools(如 bash、read)可稳定产出 `tool_calls` + - Grok 内置工具(web_search、x_search 等 19 个)保持内部语义,不泄露为客户端 tool_calls + - 支持多轮 tool-call 上下文(assistant tool_calls + tool result 正确转换) + - 新增 738 行回归测试覆盖核心逻辑 + +**优化** + +- 🔧 **Console 配额参数调整**:恢复周期从 15 分钟改为 30 分钟,轮换阈值从 15 改为 20,降低单号负载 +- 💓 **SSE 心跳保活**:所有流式接口在数据开始前发送心跳注释,防止思考期间连接超时 +- ⚡ **TXT 导入异步化**:大批量导入不再阻塞,接口立即返回,刷新在后台进行 +- 🔒 **依赖安全升级**:cryptography 48.0.1+、starlette 1.1.0+、python-multipart 0.0.31+ + +**修复** + +- 🐛 修复 NSFW 初始化时生日已锁定的 429 报错([PR#25](https://github.com/jiujiu532/grok2api/pull/25),感谢 @Xaihi-nun) +- 🐛 修复批量刷新结果未区分异常与临时失败的问题 + +### v0.1.5 (2025-06-13) + +**优化** + +- 🔧 **批量刷新结果优化**:刷新账户时区分"凭证失效(异常)"和"临时失败(网络波动)"两种状态 + - 前端提示更清晰:`刷新完成:成功 906,异常 40,临时失败 54` + - 后端性能优化:批量查询失败账户状态(从 N 次数据库查询降为 1 次) + - 异常账户自动进入"异常"筛选组,临时失败不影响账户状态 + +- 🎯 **导入账户交互改进**(基于 [PR#13](https://github.com/jiujiu532/grok2api/pull/13)) + - 新增/导入弹窗中加入"导入后自动开启 NSFW"复选框(默认不勾选) + - 工具栏按钮互斥显示:勾选账号时显示批量操作按钮,未勾选显示全局按钮 + - 去除全局配置 `account.auto_nsfw_on_import`,改为每次导入时手动选择 + +- ⚙️ **并发数限制调整** + - 批量操作硬限制从 50 调整为 80 + - 配置页并发数输入框添加 `min: 1, max: 80` 强制限制 + - 防止用户输入超出范围的并发值导致后端压力过大 + +**修复** + +- 🐛 修复配置页数字输入框 `min/max` 属性未生效的问题 +- 🐛 补充 `tokens.py` 缺失的 `Query` 导入(导致服务启动失败) +- 🐛 补充翻译文件中缺失的 `autoNsfwOnImport` 和 `autoNsfwHint` 键 + +--- + +## 致谢 + +- 上游:[chenyme/grok2api](https://github.com/chenyme/grok2api) +- DeepWiki:[chenyme/grok2api](https://deepwiki.com/chenyme/grok2api) +- 项目文档:[blog.cheny.me](https://blog.cheny.me/blog/posts/grok2api) +- 社区:[Linux.do](https://linux.do) + +--- + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=jiujiu532/grok2api&type=Date)](https://star-history.com/#jiujiu532/grok2api&Date) + +--- + +
+ +**MIT License** + +
diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/control/__init__.py b/app/control/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/control/account/__init__.py b/app/control/account/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..36623fb052644fa9be79663c9248e5d589ff7b06 --- /dev/null +++ b/app/control/account/__init__.py @@ -0,0 +1,37 @@ +"""Account control-plane domain — public exports.""" + +from .enums import AccountStatus, FeedbackKind, QuotaSource +from .models import ( + AccountChangeSet, + AccountMutationResult, + AccountPage, + AccountQuotaSet, + AccountRecord, + AccountUsageStats, + QuotaWindow, + RuntimeSnapshot, +) +from .commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery +from .repository import AccountRepository +from .state_machine import AccountFeedback, StatePolicy, apply_feedback, clear_failures, derive_status, is_selectable, is_manageable +from .quota_defaults import BASIC_QUOTA_DEFAULTS, SUPER_QUOTA_DEFAULTS, default_quota_set +from .refresh import AccountRefreshService, RefreshResult +from .runtime import get_refresh_service, set_refresh_service +from .scheduler import AccountRefreshScheduler, get_account_refresh_scheduler +from .backends.factory import create_repository + +__all__ = [ + "AccountStatus", "FeedbackKind", "QuotaSource", + "QuotaWindow", "AccountQuotaSet", "AccountUsageStats", + "AccountRecord", "AccountMutationResult", "AccountPage", + "AccountChangeSet", "RuntimeSnapshot", + "AccountUpsert", "AccountPatch", "ListAccountsQuery", "BulkReplacePoolCommand", + "AccountRepository", + "AccountFeedback", "StatePolicy", "apply_feedback", "clear_failures", + "derive_status", "is_selectable", "is_manageable", + "BASIC_QUOTA_DEFAULTS", "SUPER_QUOTA_DEFAULTS", "default_quota_set", + "AccountRefreshService", "RefreshResult", + "get_refresh_service", "set_refresh_service", + "AccountRefreshScheduler", "get_account_refresh_scheduler", + "create_repository", +] diff --git a/app/control/account/backends/__init__.py b/app/control/account/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/control/account/backends/factory.py b/app/control/account/backends/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..7b6f91cacedc88d4de050ba2e938f22602301c0d --- /dev/null +++ b/app/control/account/backends/factory.py @@ -0,0 +1,138 @@ +"""Account repository factory — selects the backend from startup env.""" + +import os +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit, urlunsplit + +from app.platform.paths import data_path +from ..repository import AccountRepository + +_SUPPORTED_BACKENDS = {"local", "redis", "mysql", "postgresql"} + + +def create_repository() -> AccountRepository: + """Instantiate the configured account storage backend. + + Startup env: ``ACCOUNT_STORAGE`` (default: ``"local"``) + + Supported values: + ``local`` — SQLite (default, single-process) + ``redis`` — Redis hash + sorted-set layout + ``mysql`` — MySQL via aiomysql / SQLAlchemy + ``postgresql`` — PostgreSQL via asyncpg / SQLAlchemy + """ + backend = get_repository_backend() + + if backend == "local": + return _make_local() + if backend == "redis": + return _make_redis() + if backend == "mysql": + return _make_sql("mysql") + if backend == "postgresql": + return _make_sql("postgresql") + + raise ValueError(f"Unknown account storage backend: {backend!r}") + + +def describe_repository_target() -> tuple[str, str]: + """Return current storage backend and a log-safe target description.""" + backend = get_repository_backend() + + if backend == "local": + return "local", str(_resolve_local_db_path()) + if backend == "redis": + return "redis", _redact_url(_get_required_env("ACCOUNT_REDIS_URL")) + if backend == "mysql": + return "mysql", _redact_url(_get_env("ACCOUNT_MYSQL_URL")) + if backend == "postgresql": + return "postgresql", _redact_url(_get_env("ACCOUNT_POSTGRESQL_URL")) + return backend, "" + + +# --------------------------------------------------------------------------- +# Backend constructors +# --------------------------------------------------------------------------- + +def get_repository_backend() -> str: + """Return the configured account storage backend from startup env.""" + backend = _get_env("ACCOUNT_STORAGE", "local").lower() + if backend not in _SUPPORTED_BACKENDS: + raise ValueError(f"Unknown account storage backend: {backend!r}") + return backend + + +def _get_env(name: str, default: str = "") -> str: + value = os.getenv(name) + if value is None: + return default + value = value.strip() + return value or default + + +def _get_required_env(name: str) -> str: + value = _get_env(name) + if not value: + raise ValueError(f"Missing required env: {name}") + return value + + +def _resolve_local_db_path() -> Path: + path_str = _get_env("ACCOUNT_LOCAL_PATH", str(data_path("accounts.db"))) + db_path = Path(path_str) + if not db_path.is_absolute(): + db_path = Path(__file__).resolve().parents[4] / db_path + return db_path + + +def _redact_url(url: Any) -> str: + raw = str(url or "").strip() + if not raw: + return "" + try: + parts = urlsplit(raw) + except Exception: + return raw + if not parts.scheme: + return raw + hostname = parts.hostname or "" + if parts.port: + hostname = f"{hostname}:{parts.port}" + if parts.username: + auth = f"{parts.username}:***@" + elif parts.password: + auth = "***@" + else: + auth = "" + return urlunsplit((parts.scheme, f"{auth}{hostname}", parts.path, parts.query, parts.fragment)) + + +def _make_local() -> AccountRepository: + from .local import LocalAccountRepository + + return LocalAccountRepository(_resolve_local_db_path()) + + +def _make_redis() -> AccountRepository: + from redis.asyncio import Redis + from .redis import RedisAccountRepository + + url = _get_required_env("ACCOUNT_REDIS_URL") + r = Redis.from_url(url, decode_responses=False) + return RedisAccountRepository(r) + + +def _make_sql(dialect: str) -> AccountRepository: + from .sql import SqlAccountRepository, create_mysql_engine, create_pgsql_engine + + if dialect == "mysql": + url = _get_env("ACCOUNT_MYSQL_URL") + engine = create_mysql_engine(url) + else: + url = _get_env("ACCOUNT_POSTGRESQL_URL") + engine = create_pgsql_engine(url) + return SqlAccountRepository(engine, dialect=dialect, dispose_engine=False) + + +__all__ = ["create_repository", "describe_repository_target", "get_repository_backend"] diff --git a/app/control/account/backends/local.py b/app/control/account/backends/local.py new file mode 100644 index 0000000000000000000000000000000000000000..e649ec1bccba9623943d93f57a3c2aa2056bae33 --- /dev/null +++ b/app/control/account/backends/local.py @@ -0,0 +1,688 @@ +"""SQLite account repository (WAL mode, single-process default backend).""" + +import asyncio +import json +import sqlite3 +from contextlib import closing +from pathlib import Path +from typing import Any + +from app.platform.runtime.clock import now_ms +from ..commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery +from ..enums import AccountStatus +from ..models import ( + AccountChangeSet, + AccountMutationResult, + AccountPage, + AccountRecord, + RuntimeSnapshot, +) +from ..quota_defaults import default_quota_set, BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_WINDOW_SECONDS + +_TBL = "accounts" +_META = "account_meta" + + +class LocalAccountRepository: + """SQLite-backed account repository.""" + + def __init__(self, db_path: Path) -> None: + self._path = Path(db_path) + self._lock = asyncio.Lock() + + # ------------------------------------------------------------------ + # Internal helpers + # ------------------------------------------------------------------ + + def _connect(self) -> sqlite3.Connection: + conn = sqlite3.connect(self._path, check_same_thread=False) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA synchronous=NORMAL") + conn.execute("PRAGMA busy_timeout=5000") + conn.execute("PRAGMA foreign_keys=ON") + return conn + + def _init_sync(self) -> None: + self._path.parent.mkdir(parents=True, exist_ok=True) + with closing(self._connect()) as conn: + conn.executescript(f""" + CREATE TABLE IF NOT EXISTS {_META} ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + INSERT OR IGNORE INTO {_META} VALUES ('revision', '0'); + + CREATE TABLE IF NOT EXISTS {_TBL} ( + token TEXT NOT NULL PRIMARY KEY, + pool TEXT NOT NULL DEFAULT 'basic', + status TEXT NOT NULL DEFAULT 'active', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + tags TEXT NOT NULL DEFAULT '[]', + quota_auto TEXT NOT NULL DEFAULT '{{}}', + quota_fast TEXT NOT NULL DEFAULT '{{}}', + quota_expert TEXT NOT NULL DEFAULT '{{}}', + quota_heavy TEXT NOT NULL DEFAULT '{{}}', + quota_grok_4_3 TEXT NOT NULL DEFAULT '{{}}', + quota_console TEXT NOT NULL DEFAULT '{{}}', + usage_use_count INTEGER NOT NULL DEFAULT 0, + usage_fail_count INTEGER NOT NULL DEFAULT 0, + usage_sync_count INTEGER NOT NULL DEFAULT 0, + last_use_at INTEGER, + last_fail_at INTEGER, + last_fail_reason TEXT, + last_sync_at INTEGER, + last_clear_at INTEGER, + state_reason TEXT, + deleted_at INTEGER, + ext TEXT NOT NULL DEFAULT '{{}}', + revision INTEGER NOT NULL DEFAULT 0 + ); + CREATE INDEX IF NOT EXISTS idx_acc_revision + ON {_TBL} (revision); + CREATE INDEX IF NOT EXISTS idx_acc_pool_status + ON {_TBL} (pool, status); + CREATE INDEX IF NOT EXISTS idx_acc_deleted + ON {_TBL} (deleted_at) WHERE deleted_at IS NOT NULL; + """) + self._ensure_column_sync(conn, "quota_grok_4_3", "TEXT NOT NULL DEFAULT '{}'") + self._ensure_column_sync(conn, "quota_console", "TEXT NOT NULL DEFAULT '{}'") + conn.commit() + + @staticmethod + def _ensure_column_sync(conn: sqlite3.Connection, name: str, ddl: str) -> None: + cols = {row[1] for row in conn.execute(f"PRAGMA table_info({_TBL})").fetchall()} + if name not in cols: + conn.execute(f"ALTER TABLE {_TBL} ADD COLUMN {name} {ddl}") + + def _bump_revision(self, conn: sqlite3.Connection) -> int: + conn.execute( + f"UPDATE {_META} SET value = CAST(value AS INTEGER) + 1 WHERE key = 'revision'" + ) + row = conn.execute( + f"SELECT CAST(value AS INTEGER) FROM {_META} WHERE key = 'revision'" + ).fetchone() + return int(row[0]) + + def _get_revision_sync(self, conn: sqlite3.Connection) -> int: + row = conn.execute( + f"SELECT CAST(value AS INTEGER) FROM {_META} WHERE key = 'revision'" + ).fetchone() + return int(row[0]) if row else 0 + + @staticmethod + def _row_to_record(row: sqlite3.Row) -> AccountRecord: + d = dict(row) + d["tags"] = json.loads(d.get("tags") or "[]") + heavy_raw = d.pop("quota_heavy", "{}") or "{}" + grok_4_3_raw = d.pop("quota_grok_4_3", "{}") or "{}" + console_raw = d.pop("quota_console", "{}") or "{}" + heavy_dict = json.loads(heavy_raw) + grok_4_3_dict = json.loads(grok_4_3_raw) + console_dict = json.loads(console_raw) + d["quota"] = { + "auto": json.loads(d.pop("quota_auto", "{}") or "{}"), + "fast": json.loads(d.pop("quota_fast", "{}") or "{}"), + "expert": json.loads(d.pop("quota_expert", "{}") or "{}"), + **({"heavy": heavy_dict} if heavy_dict else {}), + **({"grok_4_3": grok_4_3_dict} if grok_4_3_dict else {}), + **({"console": console_dict} if console_dict else {}), + } + d["ext"] = json.loads(d.get("ext") or "{}") + return AccountRecord.model_validate(d) + + @staticmethod + def _record_to_row(record: AccountRecord, revision: int) -> dict[str, Any]: + qs = record.quota_set() + return { + "token": record.token, + "pool": record.pool, + "status": record.status.value, + "created_at": record.created_at, + "updated_at": record.updated_at, + "tags": json.dumps(record.tags), + "quota_auto": json.dumps(qs.auto.to_dict()), + "quota_fast": json.dumps(qs.fast.to_dict()), + "quota_expert": json.dumps(qs.expert.to_dict()), + "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "quota_grok_4_3": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}", + "quota_console": json.dumps(qs.console.to_dict()) if qs.console else "{}", + "usage_use_count": record.usage_use_count, + "usage_fail_count": record.usage_fail_count, + "usage_sync_count": record.usage_sync_count, + "last_use_at": record.last_use_at, + "last_fail_at": record.last_fail_at, + "last_fail_reason": record.last_fail_reason, + "last_sync_at": record.last_sync_at, + "last_clear_at": record.last_clear_at, + "state_reason": record.state_reason, + "deleted_at": record.deleted_at, + "ext": json.dumps(record.ext), + "revision": revision, + } + + def _upsert_sync( + self, + conn: sqlite3.Connection, + items: list[AccountUpsert], + revision: int, + ) -> int: + ts = now_ms() + + # 按 pool 缓存配额 JSON,避免重复计算(同一 pool 的配额完全相同) + _quota_json_cache: dict[str, dict[str, str]] = {} + + def _get_quota_json(pool: str) -> dict[str, str]: + cached = _quota_json_cache.get(pool) + if cached is not None: + return cached + qs = default_quota_set(pool) + result = { + "qa": json.dumps(qs.auto.to_dict()), + "qf": json.dumps(qs.fast.to_dict()), + "qe": json.dumps(qs.expert.to_dict()), + "qh": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "qg": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}", + "qc": json.dumps(qs.console.to_dict()) if qs.console else "{}", + } + _quota_json_cache[pool] = result + return result + + # 批量准备参数 + rows: list[tuple] = [] + for item in items: + # 轻量 token 清洗(API 层 _sanitize 已做过完整清洗,此处仅做安全兜底) + token = str(item.token or "").strip() + if token.startswith("sso="): + token = token[4:] + token = token.encode("ascii", errors="ignore").decode("ascii").strip() + if not token: + continue + pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic" + q = _get_quota_json(pool) + rows.append(( + token, pool, ts, ts, + json.dumps(item.tags), + q["qa"], q["qf"], q["qe"], q["qh"], q["qg"], q["qc"], + json.dumps(item.ext), + revision, + )) + + if not rows: + return 0 + + # 批量插入(1 次 executemany 代替 N 次 execute) + conn.executemany( + f""" + INSERT INTO {_TBL} ( + token, pool, status, created_at, updated_at, + tags, quota_auto, quota_fast, quota_expert, quota_heavy, quota_grok_4_3, quota_console, + usage_use_count, usage_fail_count, usage_sync_count, + ext, revision + ) VALUES ( + ?, ?, 'active', ?, ?, + ?, ?, ?, ?, ?, ?, ?, + 0, 0, 0, ?, ? + ) + ON CONFLICT(token) DO UPDATE SET + pool = excluded.pool, + status = 'active', + deleted_at = NULL, + updated_at = excluded.updated_at, + tags = excluded.tags, + quota_console = excluded.quota_console, + ext = excluded.ext, + revision = excluded.revision + """, + rows, + ) + return len(rows) + + def _patch_sync( + self, + conn: sqlite3.Connection, + patches: list[AccountPatch], + revision: int, + ) -> int: + ts = now_ms() + count = 0 + for patch in patches: + # Fetch current record. + row = conn.execute( + f"SELECT * FROM {_TBL} WHERE token = ?", (patch.token,) + ).fetchone() + if row is None: + continue + record = self._row_to_record(row) + qs = record.quota_set() + + sets: dict[str, Any] = {"updated_at": ts, "revision": revision} + + if patch.pool is not None: + sets["pool"] = patch.pool + if patch.status is not None: + sets["status"] = patch.status.value + if patch.state_reason is not None: + sets["state_reason"] = patch.state_reason + if patch.last_use_at is not None: + sets["last_use_at"] = patch.last_use_at + if patch.last_fail_at is not None: + sets["last_fail_at"] = patch.last_fail_at + if patch.last_fail_reason is not None: + sets["last_fail_reason"] = patch.last_fail_reason + if patch.last_sync_at is not None: + sets["last_sync_at"] = patch.last_sync_at + if patch.last_clear_at is not None: + sets["last_clear_at"] = patch.last_clear_at + + # Usage counters (delta). + if patch.usage_use_delta is not None: + sets["usage_use_count"] = max(0, record.usage_use_count + patch.usage_use_delta) + if patch.usage_fail_delta is not None: + sets["usage_fail_count"] = max(0, record.usage_fail_count + patch.usage_fail_delta) + if patch.usage_sync_delta is not None: + sets["usage_sync_count"] = max(0, record.usage_sync_count + patch.usage_sync_delta) + + # Quota windows. + if patch.quota_auto is not None: + sets["quota_auto"] = json.dumps(patch.quota_auto) + if patch.quota_fast is not None: + sets["quota_fast"] = json.dumps(patch.quota_fast) + if patch.quota_expert is not None: + sets["quota_expert"] = json.dumps(patch.quota_expert) + if patch.quota_heavy is not None: + sets["quota_heavy"] = json.dumps(patch.quota_heavy) + if patch.quota_grok_4_3 is not None: + sets["quota_grok_4_3"] = json.dumps(patch.quota_grok_4_3) + if patch.quota_console is not None: + sets["quota_console"] = json.dumps(patch.quota_console) + + # Tags — use set arithmetic to avoid O(n×m) membership tests. + tag_set: set[str] = set(record.tags) + if patch.tags is not None: + tag_set = set(patch.tags) + if patch.add_tags: + tag_set.update(patch.add_tags) + if patch.remove_tags: + tag_set.difference_update(patch.remove_tags) + sets["tags"] = json.dumps(sorted(tag_set)) + + # ext merge. + ext = dict(record.ext) + if patch.ext_merge: + ext.update(patch.ext_merge) + if patch.clear_failures: + for k in ("cooldown_until", "cooldown_reason", "disabled_at", + "disabled_reason", "expired_at", "expired_reason", + "forbidden_strikes", "console_429_count"): + ext.pop(k, None) + sets["status"] = AccountStatus.ACTIVE.value + sets["usage_fail_count"] = 0 + sets["last_fail_at"] = None + sets["last_fail_reason"] = None + sets["state_reason"] = None + sets["ext"] = json.dumps(ext) + + col_sql = ", ".join(f"{k} = :{k}" for k in sets) + conn.execute( + f"UPDATE {_TBL} SET {col_sql} WHERE token = :_token", + {**sets, "_token": patch.token}, + ) + count += conn.execute("SELECT changes()").fetchone()[0] + return count + + # ------------------------------------------------------------------ + # Public API + # ------------------------------------------------------------------ + + async def initialize(self) -> None: + async with self._lock: + await asyncio.to_thread(self._init_sync) + + async def get_revision(self) -> int: + def _sync() -> int: + with closing(self._connect()) as conn: + return self._get_revision_sync(conn) + return await asyncio.to_thread(_sync) + + async def runtime_snapshot(self) -> RuntimeSnapshot: + def _sync() -> RuntimeSnapshot: + with closing(self._connect()) as conn: + rev = self._get_revision_sync(conn) + rows = conn.execute( + f"SELECT * FROM {_TBL} WHERE deleted_at IS NULL" + ).fetchall() + return RuntimeSnapshot( + revision=rev, + items=[self._row_to_record(r) for r in rows], + ) + return await asyncio.to_thread(_sync) + + async def scan_changes( + self, + since_revision: int, + *, + limit: int = 5000, + ) -> AccountChangeSet: + def _sync() -> AccountChangeSet: + with closing(self._connect()) as conn: + rev = self._get_revision_sync(conn) + rows = conn.execute( + f"SELECT * FROM {_TBL} WHERE revision > ? ORDER BY revision LIMIT ?", + (since_revision, limit), + ).fetchall() + items: list[AccountRecord] = [] + deleted: list[str] = [] + batch_max_rev = 0 + for row in rows: + r = self._row_to_record(row) + if r.revision > batch_max_rev: + batch_max_rev = r.revision + if r.is_deleted(): + deleted.append(r.token) + else: + items.append(r) + has_more = len(rows) == limit + return AccountChangeSet( + revision=rev, + batch_max_revision=batch_max_rev, + items=items, + deleted_tokens=deleted, + has_more=has_more, + ) + return await asyncio.to_thread(_sync) + + async def upsert_accounts( + self, + items: list[AccountUpsert], + ) -> AccountMutationResult: + if not items: + return AccountMutationResult() + + def _sync() -> AccountMutationResult: + with closing(self._connect()) as conn: + rev = self._bump_revision(conn) + count = self._upsert_sync(conn, items, rev) + conn.commit() + return AccountMutationResult(upserted=count, revision=rev) + + async with self._lock: + return await asyncio.to_thread(_sync) + + async def patch_accounts( + self, + patches: list[AccountPatch], + ) -> AccountMutationResult: + if not patches: + return AccountMutationResult() + + def _sync() -> AccountMutationResult: + with closing(self._connect()) as conn: + rev = self._bump_revision(conn) + count = self._patch_sync(conn, patches, rev) + conn.commit() + return AccountMutationResult(patched=count, revision=rev) + + async with self._lock: + return await asyncio.to_thread(_sync) + + async def delete_accounts( + self, + tokens: list[str], + ) -> AccountMutationResult: + if not tokens: + return AccountMutationResult() + + def _sync() -> AccountMutationResult: + ts = now_ms() + with closing(self._connect()) as conn: + rev = self._bump_revision(conn) + conn.executemany( + f"UPDATE {_TBL} SET deleted_at = ?, updated_at = ?, revision = ? " + f"WHERE token = ? AND deleted_at IS NULL", + [(ts, ts, rev, t) for t in tokens], + ) + count = conn.execute("SELECT changes()").fetchone()[0] + conn.commit() + return AccountMutationResult(deleted=count, revision=rev) + + async with self._lock: + return await asyncio.to_thread(_sync) + + async def get_accounts( + self, + tokens: list[str], + ) -> list[AccountRecord]: + if not tokens: + return [] + + def _sync() -> list[AccountRecord]: + with closing(self._connect()) as conn: + placeholders = ",".join("?" * len(tokens)) + rows = conn.execute( + f"SELECT * FROM {_TBL} WHERE token IN ({placeholders})", + tokens, + ).fetchall() + return [self._row_to_record(r) for r in rows] + + return await asyncio.to_thread(_sync) + + async def list_accounts( + self, + query: ListAccountsQuery, + ) -> AccountPage: + def _sync() -> AccountPage: + with closing(self._connect()) as conn: + where_parts: list[str] = [] + params: list[Any] = [] + + if not query.include_deleted: + where_parts.append("deleted_at IS NULL") + if query.pool: + where_parts.append("pool = ?") + params.append(query.pool) + if query.status: + where_parts.append("status = ?") + params.append(query.status.value) + + where_sql = ("WHERE " + " AND ".join(where_parts)) if where_parts else "" + order_dir = "DESC" if query.sort_desc else "ASC" + # Allow only known column names to prevent injection. + safe_sort = query.sort_by if query.sort_by in { + "updated_at", "created_at", "last_use_at", "token", + "usage_use_count", "usage_fail_count", + } else "updated_at" + order_sql = f"ORDER BY {safe_sort} {order_dir}" + + total = conn.execute( + f"SELECT COUNT(*) FROM {_TBL} {where_sql}", params + ).fetchone()[0] + + offset = (query.page - 1) * query.page_size + rows = conn.execute( + f"SELECT * FROM {_TBL} {where_sql} {order_sql} " + f"LIMIT ? OFFSET ?", + params + [query.page_size, offset], + ).fetchall() + items = [self._row_to_record(r) for r in rows] + total_pages = max(1, (total + query.page_size - 1) // query.page_size) + rev = self._get_revision_sync(conn) + return AccountPage( + items=items, + total=total, + page=query.page, + page_size=query.page_size, + total_pages=total_pages, + revision=rev, + ) + + return await asyncio.to_thread(_sync) + + async def replace_pool( + self, + command: BulkReplacePoolCommand, + ) -> AccountMutationResult: + def _sync() -> AccountMutationResult: + ts = now_ms() + with closing(self._connect()) as conn: + rev = self._bump_revision(conn) + # Soft-delete all existing accounts in the pool. + conn.execute( + f"UPDATE {_TBL} SET deleted_at = ?, updated_at = ?, revision = ? " + f"WHERE pool = ? AND deleted_at IS NULL", + (ts, ts, rev, command.pool), + ) + deleted = conn.execute("SELECT changes()").fetchone()[0] + # Bump revision again for upserts. + rev = self._bump_revision(conn) + upserted = self._upsert_sync(conn, command.upserts, rev) + conn.commit() + return AccountMutationResult( + upserted=upserted, deleted=deleted, revision=rev + ) + + async with self._lock: + return await asyncio.to_thread(_sync) + + async def reset_expired_console_windows(self) -> int: + """Batch-reset exhausted + expired console quotas via direct SQL. + + 处理两种异常情况: + 1. 老条件:remaining<=0 且 (reset_at IS NULL 或已过期) → 正常配额耗尽恢复 + 2. 新条件 (M6):reset_at 已过期(即使 remaining>0)→ 异常数据归位 + (来源:人工 patch、迁移数据、M1 历史副作用等) + """ + def _sync() -> int: + with closing(self._connect()) as conn: + now = now_ms() + # 先查有多少需要重置的 + count = conn.execute( + f""" + SELECT COUNT(*) FROM {_TBL} + WHERE status = 'active' + AND deleted_at IS NULL + AND ( + ( + CAST(json_extract(quota_console, '$.remaining') AS INTEGER) <= 0 + AND ( + json_extract(quota_console, '$.reset_at') IS NULL + OR CAST(json_extract(quota_console, '$.reset_at') AS INTEGER) < ? + ) + ) + OR + ( + json_extract(quota_console, '$.reset_at') IS NOT NULL + AND CAST(json_extract(quota_console, '$.reset_at') AS INTEGER) < ? + ) + ) + """, + (now, now), + ).fetchone()[0] + if count == 0: + return 0 + + # 从 quota_defaults.py 动态读取,不硬编码 + reset_json = json.dumps({ + "remaining": BASIC_CONSOLE_LIMIT, + "total": BASIC_CONSOLE_LIMIT, + "window_seconds": BASIC_CONSOLE_WINDOW_SECONDS, + "reset_at": None, + "synced_at": now, + "source": 0, + }) + rev = self._bump_revision(conn) + conn.execute( + f""" + UPDATE {_TBL} + SET quota_console = ?, revision = ?, updated_at = ? + WHERE status = 'active' + AND deleted_at IS NULL + AND ( + ( + CAST(json_extract(quota_console, '$.remaining') AS INTEGER) <= 0 + AND ( + json_extract(quota_console, '$.reset_at') IS NULL + OR CAST(json_extract(quota_console, '$.reset_at') AS INTEGER) < ? + ) + ) + OR + ( + json_extract(quota_console, '$.reset_at') IS NOT NULL + AND CAST(json_extract(quota_console, '$.reset_at') AS INTEGER) < ? + ) + ) + """, + (reset_json, rev, now, now, now), + ) + affected = conn.execute("SELECT changes()").fetchone()[0] + conn.commit() + return affected + + async with self._lock: + return await asyncio.to_thread(_sync) + + async def recover_console_expired_accounts(self) -> int: + """Auto-recover console 429 EXPIRED accounts with successful history. + + Conditions: + - status = 'expired' + - state_reason = 'console_429_threshold_exceeded' + - usage_use_count > 5 + - ext.expired_at <= now - 1 hour + """ + def _sync() -> int: + with closing(self._connect()) as conn: + now = now_ms() + recovery_threshold = now - 3600 * 1000 + + # 查询符合条件的账号 token 和 ext + rows = conn.execute( + f""" + SELECT token, ext FROM {_TBL} + WHERE status = 'expired' + AND deleted_at IS NULL + AND state_reason = 'console_429_threshold_exceeded' + AND usage_use_count > 5 + AND CAST(json_extract(ext, '$.expired_at') AS INTEGER) <= ? + """, + (recovery_threshold,), + ).fetchall() + + if not rows: + return 0 + + rev = self._bump_revision(conn) + for row in rows: + token, ext_raw = row + try: + ext = json.loads(ext_raw) if ext_raw else {} + except (ValueError, TypeError): + ext = {} + # 清理 EXPIRED 相关字段 + for k in ("expired_at", "expired_reason", + "console_429_count", "console_429_last_at"): + ext.pop(k, None) + conn.execute( + f""" + UPDATE {_TBL} + SET status = 'active', + state_reason = NULL, + ext = ?, + revision = ?, + updated_at = ? + WHERE token = ? + """, + (json.dumps(ext), rev, now, token), + ) + conn.commit() + return len(rows) + + async with self._lock: + return await asyncio.to_thread(_sync) + + async def close(self) -> None: + """No-op for SQLite — connections are opened and closed per operation.""" + + +__all__ = ["LocalAccountRepository"] diff --git a/app/control/account/backends/redis.py b/app/control/account/backends/redis.py new file mode 100644 index 0000000000000000000000000000000000000000..817bb11fb3a3bbfd060b680ebe0dfdfd39559965 --- /dev/null +++ b/app/control/account/backends/redis.py @@ -0,0 +1,594 @@ +"""Redis account repository. + +Layout: + accounts:rev — STRING global revision counter + accounts:record: — HASH flattened AccountRecord fields + accounts:pool: — SET token members per pool (live) + accounts:revision_log — ZSET token → revision (for scan_changes) +""" + +import json +from typing import Any + +from app.platform.runtime.clock import now_ms +from ..commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery +from ..enums import AccountStatus +from ..models import ( + AccountChangeSet, + AccountMutationResult, + AccountPage, + AccountRecord, + RuntimeSnapshot, +) +from redis.asyncio import Redis + +from ..quota_defaults import default_quota_set + +_KEY_REV = "accounts:rev" +_KEY_RECORD = "accounts:record:{token}" +_KEY_POOL = "accounts:pool:{pool}" +_KEY_REV_LOG = "accounts:revision_log" + + +def _record_key(token: str) -> str: + return f"accounts:record:{token}" + + +def _pool_key(pool: str) -> str: + return f"accounts:pool:{pool}" + + +class RedisAccountRepository: + """Redis-backed account repository. + + Requires redis-py >= 5 with async support. + """ + + def __init__(self, redis: "Redis") -> None: + self._r = redis + + # ------------------------------------------------------------------ + # Serialisation helpers + # ------------------------------------------------------------------ + + @staticmethod + def _to_hash(record: AccountRecord, revision: int) -> dict[str, str]: + qs = record.quota_set() + return { + "pool": record.pool, + "status": record.status.value, + "created_at": str(record.created_at), + "updated_at": str(record.updated_at), + "tags": json.dumps(record.tags), + "quota_auto": json.dumps(qs.auto.to_dict()), + "quota_fast": json.dumps(qs.fast.to_dict()), + "quota_expert": json.dumps(qs.expert.to_dict()), + "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "quota_grok_4_3": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}", + "quota_console": json.dumps(qs.console.to_dict()) if qs.console else "{}", + "usage_use_count": str(record.usage_use_count), + "usage_fail_count": str(record.usage_fail_count), + "usage_sync_count": str(record.usage_sync_count), + "last_use_at": str(record.last_use_at or ""), + "last_fail_at": str(record.last_fail_at or ""), + "last_fail_reason": record.last_fail_reason or "", + "last_sync_at": str(record.last_sync_at or ""), + "last_clear_at": str(record.last_clear_at or ""), + "state_reason": record.state_reason or "", + "deleted_at": str(record.deleted_at or ""), + "ext": json.dumps(record.ext), + "revision": str(revision), + } + + @staticmethod + def _from_hash(token: str, h: dict[bytes | str, bytes | str]) -> AccountRecord: + def _s(k: str) -> str: + v = h.get(k) or h.get(k.encode()) + return v.decode() if isinstance(v, bytes) else (v or "") + + def _i(k: str) -> int | None: + v = _s(k) + return int(v) if v else None + + return AccountRecord.model_validate({ + "token": token, + "pool": _s("pool") or "basic", + "status": _s("status") or "active", + "created_at": _i("created_at") or now_ms(), + "updated_at": _i("updated_at") or now_ms(), + "tags": json.loads(_s("tags") or "[]"), + "quota": { + "auto": json.loads(_s("quota_auto") or "{}"), + "fast": json.loads(_s("quota_fast") or "{}"), + "expert": json.loads(_s("quota_expert") or "{}"), + **({ + "heavy": json.loads(_s("quota_heavy")) + } if _s("quota_heavy") and _s("quota_heavy") != "{}" else {}), + **({ + "grok_4_3": json.loads(_s("quota_grok_4_3")) + } if _s("quota_grok_4_3") and _s("quota_grok_4_3") != "{}" else {}), + **({ + "console": json.loads(_s("quota_console")) + } if _s("quota_console") and _s("quota_console") != "{}" else {}), + }, + "usage_use_count": int(_s("usage_use_count") or 0), + "usage_fail_count": int(_s("usage_fail_count") or 0), + "usage_sync_count": int(_s("usage_sync_count") or 0), + "last_use_at": _i("last_use_at"), + "last_fail_at": _i("last_fail_at"), + "last_fail_reason": _s("last_fail_reason") or None, + "last_sync_at": _i("last_sync_at"), + "last_clear_at": _i("last_clear_at"), + "state_reason": _s("state_reason") or None, + "deleted_at": _i("deleted_at"), + "ext": json.loads(_s("ext") or "{}"), + "revision": int(_s("revision") or 0), + }) + + # ------------------------------------------------------------------ + # Revision management + # ------------------------------------------------------------------ + + async def _bump_revision(self) -> int: + return int(await self._r.incr(_KEY_REV)) + + # ------------------------------------------------------------------ + # Public API + # ------------------------------------------------------------------ + + async def initialize(self) -> None: + await self._r.setnx(_KEY_REV, "0") + + async def get_revision(self) -> int: + v = await self._r.get(_KEY_REV) + return int(v) if v else 0 + + async def runtime_snapshot(self) -> RuntimeSnapshot: + rev = await self.get_revision() + # Scan all record keys. + keys: list[str] = [] + async for k in self._r.scan_iter("accounts:record:*"): + keys.append(k.decode() if isinstance(k, bytes) else k) + + items: list[AccountRecord] = [] + for key in keys: + token = key.split(":", 2)[-1] + h = await self._r.hgetall(key) + if not h: + continue + record = self._from_hash(token, h) + if not record.is_deleted(): + items.append(record) + return RuntimeSnapshot(revision=rev, items=items) + + async def scan_changes( + self, + since_revision: int, + *, + limit: int = 5000, + ) -> AccountChangeSet: + rev = await self.get_revision() + # Tokens whose revision > since_revision; 带分数以便提取本批最大 revision。 + entries = await self._r.zrangebyscore( + _KEY_REV_LOG, + since_revision + 1, + "+inf", + withscores=True, + start=0, + num=limit, + ) + tokens: list[tuple[str, int]] = [] + batch_max_rev = 0 + for entry in entries: + tok, score = entry + tok_s = tok.decode() if isinstance(tok, bytes) else tok + score_i = int(score) + if score_i > batch_max_rev: + batch_max_rev = score_i + tokens.append((tok_s, score_i)) + items: list[AccountRecord] = [] + deleted: list[str] = [] + for token, _score in tokens: + h = await self._r.hgetall(_record_key(token)) + if not h: + deleted.append(token) + continue + record = self._from_hash(token, h) + if record.is_deleted(): + deleted.append(token) + else: + items.append(record) + return AccountChangeSet( + revision=rev, + batch_max_revision=batch_max_rev, + items=items, + deleted_tokens=deleted, + has_more=len(entries) == limit, + ) + + async def upsert_accounts( + self, + items: list[AccountUpsert], + ) -> AccountMutationResult: + if not items: + return AccountMutationResult() + rev = await self._bump_revision() + count = 0 + for item in items: + try: + token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token + except ValueError: + continue + pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic" + qs = default_quota_set(pool) + ts = now_ms() + record = AccountRecord( + token = token, + pool = pool, + tags = item.tags, + ext = item.ext, + quota = qs.to_dict(), + created_at = ts, + updated_at = ts, + ) + key = _record_key(token) + await self._r.hset(key, mapping=self._to_hash(record, rev)) + await self._r.sadd(_pool_key(pool), token) + await self._r.zadd(_KEY_REV_LOG, {token: rev}) + count += 1 + return AccountMutationResult(upserted=count, revision=rev) + + async def patch_accounts( + self, + patches: list[AccountPatch], + ) -> AccountMutationResult: + if not patches: + return AccountMutationResult() + rev = await self._bump_revision() + count = 0 + ts = now_ms() + for patch in patches: + key = _record_key(patch.token) + h = await self._r.hgetall(key) + if not h: + continue + record = self._from_hash(patch.token, h) + qs = record.quota_set() + + updates: dict[str, str] = { + "updated_at": str(ts), + "revision": str(rev), + } + if patch.status is not None: + updates["status"] = patch.status.value + if patch.state_reason is not None: + updates["state_reason"] = patch.state_reason + if patch.last_use_at is not None: + updates["last_use_at"] = str(patch.last_use_at) + if patch.last_fail_at is not None: + updates["last_fail_at"] = str(patch.last_fail_at) + if patch.last_fail_reason is not None: + updates["last_fail_reason"] = patch.last_fail_reason + if patch.last_sync_at is not None: + updates["last_sync_at"] = str(patch.last_sync_at) + if patch.last_clear_at is not None: + updates["last_clear_at"] = str(patch.last_clear_at) + if patch.pool is not None: + updates["pool"] = patch.pool + if patch.quota_auto is not None: + updates["quota_auto"] = json.dumps(patch.quota_auto) + if patch.quota_fast is not None: + updates["quota_fast"] = json.dumps(patch.quota_fast) + if patch.quota_expert is not None: + updates["quota_expert"] = json.dumps(patch.quota_expert) + if patch.quota_heavy is not None: + updates["quota_heavy"] = json.dumps(patch.quota_heavy) + if patch.quota_grok_4_3 is not None: + updates["quota_grok_4_3"] = json.dumps(patch.quota_grok_4_3) + if patch.quota_console is not None: + updates["quota_console"] = json.dumps(patch.quota_console) + + # Usage counters. + if patch.usage_use_delta is not None: + updates["usage_use_count"] = str(max(0, record.usage_use_count + patch.usage_use_delta)) + if patch.usage_fail_delta is not None: + updates["usage_fail_count"] = str(max(0, record.usage_fail_count + patch.usage_fail_delta)) + if patch.usage_sync_delta is not None: + updates["usage_sync_count"] = str(max(0, record.usage_sync_count + patch.usage_sync_delta)) + + # Tags. + tags = list(record.tags) + if patch.tags is not None: + tags = patch.tags + if patch.add_tags: + for t in patch.add_tags: + if t not in tags: + tags.append(t) + if patch.remove_tags: + tags = [t for t in tags if t not in patch.remove_tags] + updates["tags"] = json.dumps(tags) + + # ext. + ext = dict(record.ext) + if patch.ext_merge: + ext.update(patch.ext_merge) + if patch.clear_failures: + for k in ("cooldown_until", "cooldown_reason", "disabled_at", + "disabled_reason", "expired_at", "expired_reason", + "forbidden_strikes", "console_429_count"): + ext.pop(k, None) + updates["status"] = AccountStatus.ACTIVE.value + updates["usage_fail_count"] = "0" + updates["last_fail_at"] = "" + updates["last_fail_reason"] = "" + updates["state_reason"] = "" + updates["ext"] = json.dumps(ext) + + await self._r.hset(key, mapping=updates) + await self._r.zadd(_KEY_REV_LOG, {patch.token: rev}) + count += 1 + return AccountMutationResult(patched=count, revision=rev) + + async def delete_accounts( + self, + tokens: list[str], + ) -> AccountMutationResult: + if not tokens: + return AccountMutationResult() + rev = await self._bump_revision() + ts = now_ms() + count = 0 + for token in tokens: + key = _record_key(token) + exists = await self._r.hget(key, "deleted_at") + if exists and exists not in (b"", b"None", None): + continue # Already deleted. + h = await self._r.hgetall(key) + if not h: + continue + pool = (h.get(b"pool") or h.get("pool") or b"basic") + if isinstance(pool, bytes): + pool = pool.decode() + await self._r.hset(key, mapping={ + "deleted_at": str(ts), + "updated_at": str(ts), + "revision": str(rev), + }) + await self._r.srem(_pool_key(pool), token) + await self._r.zadd(_KEY_REV_LOG, {token: rev}) + count += 1 + return AccountMutationResult(deleted=count, revision=rev) + + async def get_accounts( + self, + tokens: list[str], + ) -> list[AccountRecord]: + if not tokens: + return [] + results: list[AccountRecord] = [] + # Pipeline keeps batch maintenance from doing one network round trip per token. + async with self._r.pipeline() as pipe: + for token in tokens: + pipe.hgetall(_record_key(token)) + hashes = await pipe.execute() + for token, h in zip(tokens, hashes, strict=True): + if h: + results.append(self._from_hash(token, h)) + return results + + async def list_accounts( + self, + query: ListAccountsQuery, + ) -> AccountPage: + # Full scan — Redis is not optimised for filtered listing. + all_records: list[AccountRecord] = [] + async for key in self._r.scan_iter("accounts:record:*"): + token = (key.decode() if isinstance(key, bytes) else key).split(":", 2)[-1] + h = await self._r.hgetall(key) + if not h: + continue + r = self._from_hash(token, h) + if not query.include_deleted and r.is_deleted(): + continue + if query.pool and r.pool != query.pool: + continue + if query.status and r.status != query.status: + continue + all_records.append(r) + + # Sort. + sort_key = query.sort_by + all_records.sort( + key=lambda r: getattr(r, sort_key, 0) or 0, + reverse=query.sort_desc, + ) + total = len(all_records) + start = (query.page - 1) * query.page_size + items = all_records[start : start + query.page_size] + total_pages = max(1, (total + query.page_size - 1) // query.page_size) + rev = await self.get_revision() + return AccountPage( + items=items, + total=total, + page=query.page, + page_size=query.page_size, + total_pages=total_pages, + revision=rev, + ) + + async def replace_pool( + self, + command: BulkReplacePoolCommand, + ) -> AccountMutationResult: + existing = await self._r.smembers(_pool_key(command.pool)) + tokens = [ + (t.decode() if isinstance(t, bytes) else t) for t in existing + ] + deleted_result = await self.delete_accounts(tokens) + upserted_result = await self.upsert_accounts(command.upserts) + return AccountMutationResult( + upserted=upserted_result.upserted, + deleted=deleted_result.deleted, + revision=upserted_result.revision, + ) + + async def reset_expired_console_windows(self) -> int: + """Python 实现 console 窗口过期重置(Redis 无 SQL)。 + + 与 SQL 后端 (local.py / sql.py) 语义一致: + 1. 老条件:remaining<=0 且 (reset_at IS NULL 或已过期) → 配额耗尽恢复 + 2. 新条件 (M6):reset_at 已过期(即使 remaining>0)→ 异常数据归位 + 仅处理 status='active' 且未删除的账号。 + """ + from ..quota_defaults import BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_WINDOW_SECONDS + + now = now_ms() + reset_payload = { + "remaining": BASIC_CONSOLE_LIMIT, + "total": BASIC_CONSOLE_LIMIT, + "window_seconds": BASIC_CONSOLE_WINDOW_SECONDS, + "reset_at": None, + "synced_at": now, + "source": 0, + } + reset_json = json.dumps(reset_payload) + + # 扫描所有账号 hash key + keys: list[str] = [] + async for k in self._r.scan_iter("accounts:record:*"): + keys.append(k.decode() if isinstance(k, bytes) else k) + if not keys: + return 0 + + # 找出符合重置条件的账号 + to_reset: list[str] = [] + for key in keys: + h = await self._r.hgetall(key) + if not h: + continue + + def _bget(k: str) -> str: + v = h.get(k) or h.get(k.encode()) + return v.decode() if isinstance(v, bytes) else (v or "") + + status = _bget("status") + deleted = _bget("deleted_at") + if status != "active" or deleted: + continue + qc_raw = _bget("quota_console") + if not qc_raw or qc_raw == "{}": + continue + try: + qc = json.loads(qc_raw) + except (ValueError, TypeError): + continue + remaining = int(qc.get("remaining") or 0) + reset_at = qc.get("reset_at") + reset_at_int = int(reset_at) if reset_at is not None else None + + cond_old = remaining <= 0 and (reset_at_int is None or reset_at_int < now) + cond_new = reset_at_int is not None and reset_at_int < now + if cond_old or cond_new: + token = key.split(":", 2)[-1] + to_reset.append(token) + + if not to_reset: + return 0 + + # 批量写入 + 记录 revision + rev = await self._bump_revision() + for token in to_reset: + await self._r.hset(_record_key(token), mapping={ + "quota_console": reset_json, + "revision": str(rev), + "updated_at": str(now), + }) + await self._r.zadd(_KEY_REV_LOG, {token: rev}) + return len(to_reset) + + async def recover_console_expired_accounts(self) -> int: + """Auto-recover console 429 EXPIRED accounts with successful history. + + Conditions: + - status = 'expired' + - state_reason = 'console_429_threshold_exceeded' + - usage_use_count > 5 + - ext.expired_at <= now - 1 hour + """ + now = now_ms() + recovery_threshold = now - 3600 * 1000 + + # 扫描所有账号 + keys: list[str] = [] + async for k in self._r.scan_iter("accounts:record:*"): + keys.append(k.decode() if isinstance(k, bytes) else k) + if not keys: + return 0 + + to_recover: list[tuple[str, dict]] = [] + for key in keys: + h = await self._r.hgetall(key) + if not h: + continue + + def _bget(k: str) -> str: + v = h.get(k) or h.get(k.encode()) + return v.decode() if isinstance(v, bytes) else (v or "") + + status = _bget("status") + deleted = _bget("deleted_at") + state_reason = _bget("state_reason") + if ( + status != "expired" + or deleted + or state_reason != "console_429_threshold_exceeded" + ): + continue + try: + use_count = int(_bget("usage_use_count") or 0) + except (ValueError, TypeError): + continue + if use_count <= 5: + continue + ext_raw = _bget("ext") + try: + ext = json.loads(ext_raw) if ext_raw else {} + except (ValueError, TypeError): + ext = {} + expired_at = ext.get("expired_at") + if expired_at is None: + continue + try: + expired_at_int = int(expired_at) + except (ValueError, TypeError): + continue + if expired_at_int > recovery_threshold: + continue + # 清理 EXPIRED 相关字段 + for k in ("expired_at", "expired_reason", + "console_429_count", "console_429_last_at"): + ext.pop(k, None) + token = key.split(":", 2)[-1] + to_recover.append((token, ext)) + + if not to_recover: + return 0 + + rev = await self._bump_revision() + for token, ext in to_recover: + await self._r.hset(_record_key(token), mapping={ + "status": "active", + "state_reason": "", + "ext": json.dumps(ext), + "revision": str(rev), + "updated_at": str(now), + }) + await self._r.zadd(_KEY_REV_LOG, {token: rev}) + return len(to_recover) + + async def close(self) -> None: + """Close the underlying Redis connection pool.""" + await self._r.aclose() + + +__all__ = ["RedisAccountRepository"] diff --git a/app/control/account/backends/sql.py b/app/control/account/backends/sql.py new file mode 100644 index 0000000000000000000000000000000000000000..fd4673f8f1f8c7852fb1cebfbe2b046160293ae0 --- /dev/null +++ b/app/control/account/backends/sql.py @@ -0,0 +1,1094 @@ +"""Shared SQLAlchemy-based backend for MySQL and PostgreSQL. + +Both dialects share the same table schema and query logic; +only the DDL fragments and upsert syntax differ. +""" + +import json +import os +import ssl +from threading import Lock +from typing import Any +from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse + +import asyncio + +import sqlalchemy as sa +from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine + +from app.platform.runtime.clock import now_ms +from ..commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery +from ..enums import AccountStatus +from ..models import ( + AccountChangeSet, + AccountMutationResult, + AccountPage, + AccountRecord, + RuntimeSnapshot, +) +from ..quota_defaults import default_quota_set, BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_WINDOW_SECONDS + +_TBL_ACCOUNTS = "accounts" +_TBL_META = "account_meta" + +metadata = sa.MetaData() + +accounts_table = sa.Table( + _TBL_ACCOUNTS, + metadata, + sa.Column("token", sa.String(512), primary_key=True), + sa.Column("pool", sa.Text, nullable=False, default="basic"), + sa.Column("status", sa.Text, nullable=False, default="active"), + sa.Column("created_at", sa.BigInteger, nullable=False), + sa.Column("updated_at", sa.BigInteger, nullable=False), + sa.Column("tags", sa.Text, nullable=False, default="[]"), + sa.Column("quota_auto", sa.Text, nullable=False, default="{}"), + sa.Column("quota_fast", sa.Text, nullable=False, default="{}"), + sa.Column("quota_expert", sa.Text, nullable=False, default="{}"), + sa.Column("quota_heavy", sa.Text, nullable=False, default="{}"), + sa.Column("quota_grok_4_3", sa.Text, nullable=False, default="{}"), + sa.Column("quota_console", sa.Text, nullable=False, default="{}"), + sa.Column("usage_use_count", sa.Integer, nullable=False, default=0), + sa.Column("usage_fail_count", sa.Integer, nullable=False, default=0), + sa.Column("usage_sync_count", sa.Integer, nullable=False, default=0), + sa.Column("last_use_at", sa.BigInteger), + sa.Column("last_fail_at", sa.BigInteger), + sa.Column("last_fail_reason", sa.Text), + sa.Column("last_sync_at", sa.BigInteger), + sa.Column("last_clear_at", sa.BigInteger), + sa.Column("state_reason", sa.Text), + sa.Column("deleted_at", sa.BigInteger), + sa.Column("ext", sa.Text, nullable=False, default="{}"), + sa.Column("revision", sa.BigInteger, nullable=False, default=0), +) + +meta_table = sa.Table( + _TBL_META, + metadata, + sa.Column("key", sa.String(128), primary_key=True), + sa.Column("value", sa.Text, nullable=False), +) + +_SQL_SSL_MODE_PARAM_KEYS = ("sslmode", "ssl-mode", "ssl") +_PG_SSL_CERT_PARAM_KEYS = ("sslrootcert", "sslcert", "sslkey") +_PG_SSL_UNSUPPORTED_PARAM_KEYS = ( + "sslcrl", + "sslpassword", + "sslnegotiation", + "ssl_min_protocol_version", + "ssl_max_protocol_version", +) +_PG_SSL_QUERY_PARAM_KEYS = ( + *_SQL_SSL_MODE_PARAM_KEYS, + *_PG_SSL_CERT_PARAM_KEYS, + *_PG_SSL_UNSUPPORTED_PARAM_KEYS, +) +_MYSQL_SSL_CERT_PARAM_KEYS = ("ssl-ca", "ssl-capath", "ssl-cert", "ssl-key") +_MYSQL_SSL_OPTIONAL_PARAM_KEYS = ("ssl-check-hostname", "ssl-cipher") +_MYSQL_SSL_QUERY_PARAM_KEYS = ( + *_SQL_SSL_MODE_PARAM_KEYS, + *_MYSQL_SSL_CERT_PARAM_KEYS, + *_MYSQL_SSL_OPTIONAL_PARAM_KEYS, +) +_SSL_BOOL_TRUE = {"1", "true", "yes", "on"} +_SSL_BOOL_FALSE = {"0", "false", "no", "off"} + +_PG_SSL_MODE_ALIASES: dict[str, str] = { + "disable": "disable", + "disabled": "disable", + "false": "disable", + "0": "disable", + "no": "disable", + "off": "disable", + "prefer": "prefer", + "preferred": "prefer", + "allow": "allow", + "require": "require", + "required": "require", + "true": "require", + "1": "require", + "yes": "require", + "on": "require", + "verify-ca": "verify-ca", + "verify_ca": "verify-ca", + "verify-full": "verify-full", + "verify_full": "verify-full", + "verify-identity": "verify-full", + "verify_identity": "verify-full", +} + +_MYSQL_SSL_MODE_ALIASES: dict[str, str] = { + "disable": "disabled", + "disabled": "disabled", + "false": "disabled", + "0": "disabled", + "no": "disabled", + "off": "disabled", + "prefer": "preferred", + "preferred": "preferred", + "allow": "preferred", + "require": "required", + "required": "required", + "true": "required", + "1": "required", + "yes": "required", + "on": "required", + "verify-ca": "verify_ca", + "verify_ca": "verify_ca", + "verify-full": "verify_identity", + "verify_full": "verify_identity", + "verify-identity": "verify_identity", + "verify_identity": "verify_identity", +} + +_ENGINE_CACHE_LOCK = Lock() +_ENGINE_CACHE: dict[tuple[str, str, str], AsyncEngine] = {} +_ENGINE_KEYS_BY_ID: dict[int, set[tuple[str, str, str]]] = {} + + +def _normalize_sql_url(dialect: str, url: str) -> str: + """Rewrite SQL URLs to the async SQLAlchemy dialect form.""" + if not url or "://" not in url: + return url + if dialect == "mysql": + if url.startswith("mysql://"): + return f"mysql+aiomysql://{url[len('mysql://') :]}" + if url.startswith("mariadb://"): + return f"mysql+aiomysql://{url[len('mariadb://') :]}" + if url.startswith("mariadb+aiomysql://"): + return f"mysql+aiomysql://{url[len('mariadb+aiomysql://') :]}" + return url + if url.startswith("postgres://"): + return f"postgresql+asyncpg://{url[len('postgres://') :]}" + if url.startswith("postgresql://"): + return f"postgresql+asyncpg://{url[len('postgresql://') :]}" + if url.startswith("pgsql://"): + return f"postgresql+asyncpg://{url[len('pgsql://') :]}" + return url + + +def _get_env_int(name: str, default: int, *, minimum: int = 0) -> int: + raw = os.getenv(name, "").strip() + if not raw: + return default + try: + return max(minimum, int(raw)) + except ValueError: + return default + + +def _normalize_ssl_mode(dialect: str, raw_mode: str) -> str: + if not raw_mode: + raise ValueError("SSL mode cannot be empty") + + mode = raw_mode.strip().lower().replace(" ", "") + if dialect == "mysql": + canonical = _MYSQL_SSL_MODE_ALIASES.get(mode) + else: + canonical = _PG_SSL_MODE_ALIASES.get(mode) + if not canonical: + raise ValueError(f"Unsupported SSL mode {raw_mode!r} for SQL dialect {dialect!r}") + return canonical + + +def _has_ssl_options(options: dict[str, str], keys: tuple[str, ...]) -> bool: + return any(options.get(key) for key in keys) + + +def _parse_ssl_bool(name: str, raw_value: str | None) -> bool | None: + if raw_value is None: + return None + + value = raw_value.strip().lower() + if not value: + return None + if value in _SSL_BOOL_TRUE: + return True + if value in _SSL_BOOL_FALSE: + return False + raise ValueError(f"Unsupported boolean value {raw_value!r} for SQL SSL option {name!r}") + + +def _extract_sql_ssl_options( + dialect: str, + url: str, +) -> tuple[str, dict[str, str]]: + parsed = urlparse(url) + ssl_query_keys = _PG_SSL_QUERY_PARAM_KEYS if dialect == "postgresql" else _MYSQL_SSL_QUERY_PARAM_KEYS + ssl_options: dict[str, str] = {} + filtered_query_items: list[tuple[str, str]] = [] + ssl_param_keys = {key.lower() for key in ssl_query_keys} + for key, value in parse_qsl(parsed.query, keep_blank_values=True): + key_lower = key.lower() + if key_lower in ssl_param_keys: + normalized_value = value.strip() + if key_lower not in ssl_options: + ssl_options[key_lower] = normalized_value + continue + filtered_query_items.append((key, value)) + + cleaned_url = urlunparse( + parsed._replace(query=urlencode(filtered_query_items, doseq=True)) + ) + return cleaned_url, ssl_options + + +def _resolve_ssl_mode(dialect: str, ssl_options: dict[str, str]) -> str | None: + raw_ssl_mode = next( + (ssl_options.get(key) for key in _SQL_SSL_MODE_PARAM_KEYS if ssl_options.get(key)), + None, + ) + if raw_ssl_mode: + return _normalize_ssl_mode(dialect, raw_ssl_mode) + + if ssl_options: + if dialect == "postgresql": + raise ValueError("PostgreSQL SSL URL parameters require sslmode to be set explicitly") + raise ValueError("MySQL SSL URL parameters require ssl-mode to be set explicitly") + return None + + +def _validate_pg_ssl_options(mode: str | None, ssl_options: dict[str, str]) -> None: + unsupported = [ + key for key in _PG_SSL_UNSUPPORTED_PARAM_KEYS + if ssl_options.get(key) + ] + if unsupported: + joined = ", ".join(sorted(unsupported)) + raise ValueError(f"Unsupported PostgreSQL SSL URL parameter(s): {joined}") + if mode == "disable" and _has_ssl_options(ssl_options, _PG_SSL_CERT_PARAM_KEYS): + raise ValueError("PostgreSQL SSL certificate parameters cannot be used with sslmode=disable") + if mode in {"allow", "prefer"} and _has_ssl_options(ssl_options, _PG_SSL_CERT_PARAM_KEYS): + raise ValueError("PostgreSQL sslmode=allow/prefer is not supported with certificate URL parameters") + + +def _build_pg_ssl_context(mode: str, ssl_options: dict[str, str]) -> ssl.SSLContext: + sslrootcert = ssl_options.get("sslrootcert") or None + sslcert = ssl_options.get("sslcert") or None + sslkey = ssl_options.get("sslkey") or None + + ctx = ssl.create_default_context(cafile=sslrootcert) + if mode == "require": + ctx.check_hostname = False + if not sslrootcert: + ctx.verify_mode = ssl.CERT_NONE + elif mode == "verify-ca": + ctx.check_hostname = False + else: + ctx.check_hostname = True + + if sslcert: + ctx.load_cert_chain(certfile=sslcert, keyfile=sslkey or None) + elif sslkey: + raise ValueError("PostgreSQL sslkey requires sslcert") + return ctx + + +def _build_mysql_ssl_context(mode: str, ssl_options: dict[str, str]) -> ssl.SSLContext | None: + if mode == "disabled": + if _has_ssl_options(ssl_options, _MYSQL_SSL_CERT_PARAM_KEYS): + raise ValueError("MySQL SSL certificate parameters cannot be used with ssl-mode=disabled") + return None + if mode == "preferred": + raise ValueError("MySQL ssl-mode=allow/prefer is not supported by aiomysql") + + ssl_ca = ssl_options.get("ssl-ca") or None + ssl_capath = ssl_options.get("ssl-capath") or None + ssl_cert = ssl_options.get("ssl-cert") or None + ssl_key = ssl_options.get("ssl-key") or None + ssl_check_hostname = _parse_ssl_bool("ssl-check-hostname", ssl_options.get("ssl-check-hostname")) + ssl_cipher = ssl_options.get("ssl-cipher") or None + + ctx = ssl.create_default_context(cafile=ssl_ca, capath=ssl_capath) + if mode in ("preferred", "required"): + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + elif mode == "verify_ca": + ctx.check_hostname = False + else: + ctx.check_hostname = True + + if ssl_check_hostname is not None: + if mode == "required" and ssl_check_hostname: + raise ValueError("MySQL ssl-check-hostname=true requires ssl-mode=verify_identity") + ctx.check_hostname = ssl_check_hostname + if ssl_cipher: + ctx.set_ciphers(ssl_cipher) + if ssl_cert: + ctx.load_cert_chain(certfile=ssl_cert, keyfile=ssl_key or None) + elif ssl_key: + raise ValueError("MySQL ssl-key requires ssl-cert") + return ctx + + +def _build_sql_connect_args( + dialect: str, + ssl_options: dict[str, str], +) -> dict[str, Any] | None: + mode = _resolve_ssl_mode(dialect, ssl_options) + if not mode: + return None + + if dialect == "mysql": + ctx = _build_mysql_ssl_context(mode, ssl_options) + return {"ssl": ctx} if ctx is not None else None + + _validate_pg_ssl_options(mode, ssl_options) + if mode == "disable": + return None + # asyncpg does not accept ssl= as a plain string (e.g. "require"). + # Always build a proper ssl.SSLContext so the driver can use it directly. + return {"ssl": _build_pg_ssl_context(mode, ssl_options)} + + +def _prepare_sql_url_and_connect_args( + dialect: str, + url: str, +) -> tuple[str, dict[str, Any] | None]: + """Strip SSL query params from the URL and translate them to connect_args.""" + normalized_url = _normalize_sql_url(dialect, url) + if "://" not in normalized_url: + return normalized_url, None + + cleaned_url, ssl_options = _extract_sql_ssl_options(dialect, normalized_url) + return cleaned_url, _build_sql_connect_args(dialect, ssl_options) + + +def _is_serverless() -> bool: + """Detect common serverless environments (Vercel, AWS Lambda, etc.).""" + return bool( + os.getenv("VERCEL") + or os.getenv("AWS_LAMBDA_FUNCTION_NAME") + or os.getenv("FUNCTIONS_WORKER_RUNTIME") # Azure Functions + ) + + +def _sql_engine_kwargs(connect_args: dict[str, Any] | None) -> dict[str, Any]: + # In serverless environments each function instance is short-lived and may + # run concurrently. Keep pools small to avoid exhausting DB connections. + serverless = _is_serverless() + kwargs: dict[str, Any] = { + "pool_size": _get_env_int("ACCOUNT_SQL_POOL_SIZE", 1 if serverless else 5, minimum=1), + "max_overflow": _get_env_int("ACCOUNT_SQL_MAX_OVERFLOW", 2 if serverless else 10, minimum=0), + "pool_timeout": _get_env_int("ACCOUNT_SQL_POOL_TIMEOUT", 30, minimum=1), + "pool_recycle": _get_env_int("ACCOUNT_SQL_POOL_RECYCLE", 1800, minimum=0), + "pool_pre_ping": True, + "pool_use_lifo": True, + } + if connect_args: + kwargs["connect_args"] = connect_args + return kwargs + + +def _get_or_create_engine( + cache_key: tuple[str, str, str], + normalized_url: str, + connect_args: dict[str, Any] | None, +) -> AsyncEngine: + with _ENGINE_CACHE_LOCK: + engine = _ENGINE_CACHE.get(cache_key) + if engine is not None: + return engine + + engine = create_async_engine(normalized_url, **_sql_engine_kwargs(connect_args)) + _ENGINE_CACHE[cache_key] = engine + _ENGINE_KEYS_BY_ID.setdefault(id(engine), set()).add(cache_key) + return engine + + +def _evict_cached_engine(engine: AsyncEngine) -> None: + with _ENGINE_CACHE_LOCK: + for key in _ENGINE_KEYS_BY_ID.pop(id(engine), set()): + if _ENGINE_CACHE.get(key) is engine: + _ENGINE_CACHE.pop(key, None) + + +def _row_to_record(row: Any) -> AccountRecord: + d = dict(row._mapping) + d["tags"] = json.loads(d.get("tags") or "[]") + heavy_raw = d.pop("quota_heavy", "{}") or "{}" + grok_4_3_raw = d.pop("quota_grok_4_3", "{}") or "{}" + console_raw = d.pop("quota_console", "{}") or "{}" + heavy_dict = json.loads(heavy_raw) + grok_4_3_dict = json.loads(grok_4_3_raw) + console_dict = json.loads(console_raw) + d["quota"] = { + "auto": json.loads(d.pop("quota_auto", "{}") or "{}"), + "fast": json.loads(d.pop("quota_fast", "{}") or "{}"), + "expert": json.loads(d.pop("quota_expert", "{}") or "{}"), + **({"heavy": heavy_dict} if heavy_dict else {}), + **({"grok_4_3": grok_4_3_dict} if grok_4_3_dict else {}), + **({"console": console_dict} if console_dict else {}), + } + d["ext"] = json.loads(d.get("ext") or "{}") + return AccountRecord.model_validate(d) + + +class SqlAccountRepository: + """Async SQLAlchemy-based repository for MySQL / PostgreSQL.""" + + def __init__( + self, + engine: AsyncEngine, + *, + dialect: str = "mysql", + dispose_engine: bool = True, + ) -> None: + self._engine = engine + self._dialect = dialect # "mysql" | "postgresql" + self._session = async_sessionmaker(engine, expire_on_commit=False) + self._dispose_engine = dispose_engine + self._initialized = False + self._init_lock = asyncio.Lock() + + # ------------------------------------------------------------------ + # Revision helpers (run inside a transaction) + # ------------------------------------------------------------------ + + async def _bump_revision(self, conn: Any) -> int: + await conn.execute( + meta_table.update() + .where(meta_table.c.key == "revision") + .values(value=sa.cast( + sa.cast(meta_table.c.value, sa.BigInteger) + 1, sa.Text + )) + ) + row = await conn.execute( + sa.select(meta_table.c.value).where(meta_table.c.key == "revision") + ) + return int(row.scalar()) + + async def _get_revision(self, conn: Any) -> int: + row = await conn.execute( + sa.select(meta_table.c.value).where(meta_table.c.key == "revision") + ) + v = row.scalar() + return int(v) if v else 0 + + # ------------------------------------------------------------------ + # Upsert — dialect-specific + # ------------------------------------------------------------------ + + def _build_upsert(self, row: dict[str, Any]): + if self._dialect == "postgresql": + from sqlalchemy.dialects.postgresql import insert + stmt = insert(accounts_table).values(**row) + # On conflict, update all columns except token and created_at. + update_cols = {k: stmt.excluded[k] for k in row if k not in ("token", "created_at")} + return stmt.on_conflict_do_update(index_elements=["token"], set_=update_cols) + else: + # MySQL + from sqlalchemy.dialects.mysql import insert + stmt = insert(accounts_table).values(**row) + update_cols = {k: stmt.inserted[k] for k in row if k not in ("token", "created_at")} + return stmt.on_duplicate_key_update(**update_cols) + + # ------------------------------------------------------------------ + # Public API + # ------------------------------------------------------------------ + + async def _ensure_initialized(self) -> None: + """Idempotent: create tables + seed revision row if not already done. + + Safe to call on every request — short-circuits after first success so + repeated calls cost only an asyncio lock check. This allows the + repository to self-initialise even when the ASGI lifespan is not + executed (e.g. Vercel serverless cold-starts). + """ + if self._initialized: + return + async with self._init_lock: + if self._initialized: + return + await self._do_initialize() + self._initialized = True + + async def _do_initialize(self) -> None: + async with self._engine.begin() as conn: + await conn.run_sync(metadata.create_all) + await self._ensure_columns(conn) + # Seed revision row. + if self._dialect == "postgresql": + from sqlalchemy.dialects.postgresql import insert as pg_insert + await conn.execute( + pg_insert(meta_table) + .values(key="revision", value="0") + .on_conflict_do_nothing() + ) + else: + from sqlalchemy.dialects.mysql import insert as my_insert + await conn.execute( + my_insert(meta_table) + .values(key="revision", value="0") + .on_duplicate_key_update(value="0") + ) + + async def _ensure_columns(self, conn: Any) -> None: + """Idempotent ALTER TABLE migrations for columns added after the initial schema.""" + existing = await self._table_columns(conn, _TBL_ACCOUNTS) + if "quota_grok_4_3" not in existing: + if self._dialect == "mysql": + await conn.exec_driver_sql( + f"ALTER TABLE {_TBL_ACCOUNTS} " + f"ADD COLUMN quota_grok_4_3 TEXT" + ) + await conn.exec_driver_sql( + f"UPDATE {_TBL_ACCOUNTS} " + f"SET quota_grok_4_3 = '{{}}' " + f"WHERE quota_grok_4_3 IS NULL" + ) + await conn.exec_driver_sql( + f"ALTER TABLE {_TBL_ACCOUNTS} " + f"MODIFY COLUMN quota_grok_4_3 TEXT NOT NULL" + ) + else: + await conn.exec_driver_sql( + f"ALTER TABLE {_TBL_ACCOUNTS} " + f"ADD COLUMN quota_grok_4_3 TEXT NOT NULL DEFAULT '{{}}'" + ) + if "quota_console" not in existing: + if self._dialect == "mysql": + await conn.exec_driver_sql( + f"ALTER TABLE {_TBL_ACCOUNTS} " + f"ADD COLUMN quota_console TEXT" + ) + await conn.exec_driver_sql( + f"UPDATE {_TBL_ACCOUNTS} " + f"SET quota_console = '{{}}' " + f"WHERE quota_console IS NULL" + ) + await conn.exec_driver_sql( + f"ALTER TABLE {_TBL_ACCOUNTS} " + f"MODIFY COLUMN quota_console TEXT NOT NULL" + ) + else: + await conn.exec_driver_sql( + f"ALTER TABLE {_TBL_ACCOUNTS} " + f"ADD COLUMN quota_console TEXT NOT NULL DEFAULT '{{}}'" + ) + + async def _table_columns(self, conn: Any, table: str) -> set[str]: + if self._dialect == "postgresql": + rows = await conn.execute( + sa.text( + "SELECT column_name FROM information_schema.columns " + "WHERE table_name = :t" + ), + {"t": table}, + ) + else: + rows = await conn.execute( + sa.text( + "SELECT COLUMN_NAME FROM information_schema.columns " + "WHERE table_schema = DATABASE() AND table_name = :t" + ), + {"t": table}, + ) + return {str(r[0]).lower() for r in rows.fetchall()} + + async def initialize(self) -> None: + await self._ensure_initialized() + + async def get_revision(self) -> int: + await self._ensure_initialized() + async with self._engine.connect() as conn: + return await self._get_revision(conn) + + async def runtime_snapshot(self) -> RuntimeSnapshot: + await self._ensure_initialized() + async with self._engine.connect() as conn: + rev = await self._get_revision(conn) + rows = (await conn.execute( + sa.select(accounts_table).where(accounts_table.c.deleted_at.is_(None)) + )).fetchall() + return RuntimeSnapshot(revision=rev, items=[_row_to_record(r) for r in rows]) + + async def scan_changes( + self, + since_revision: int, + *, + limit: int = 5000, + ) -> AccountChangeSet: + await self._ensure_initialized() + async with self._engine.connect() as conn: + rev = await self._get_revision(conn) + rows = (await conn.execute( + sa.select(accounts_table) + .where(accounts_table.c.revision > since_revision) + .order_by(accounts_table.c.revision) + .limit(limit) + )).fetchall() + items: list[AccountRecord] = [] + deleted: list[str] = [] + batch_max_rev = 0 + for row in rows: + r = _row_to_record(row) + if r.revision > batch_max_rev: + batch_max_rev = r.revision + if r.is_deleted(): + deleted.append(r.token) + else: + items.append(r) + return AccountChangeSet( + revision=rev, + batch_max_revision=batch_max_rev, + items=items, + deleted_tokens=deleted, + has_more=len(rows) == limit, + ) + + async def upsert_accounts( + self, + items: list[AccountUpsert], + ) -> AccountMutationResult: + if not items: + return AccountMutationResult() + await self._ensure_initialized() + async with self._engine.begin() as conn: + rev = await self._bump_revision(conn) + ts = now_ms() + count = 0 + for item in items: + try: + token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token + except Exception: + continue + pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic" + qs = default_quota_set(pool) + row = { + "token": token, + "pool": pool, + "status": "active", + "created_at": ts, + "updated_at": ts, + "deleted_at": None, # clear soft-delete on re-import + "tags": json.dumps(item.tags), + "quota_auto": json.dumps(qs.auto.to_dict()), + "quota_fast": json.dumps(qs.fast.to_dict()), + "quota_expert": json.dumps(qs.expert.to_dict()), + "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "quota_grok_4_3": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}", + "quota_console": json.dumps(qs.console.to_dict()) if qs.console else "{}", + "usage_use_count": 0, + "usage_fail_count": 0, + "usage_sync_count": 0, + "ext": json.dumps(item.ext), + "revision": rev, + } + await conn.execute(self._build_upsert(row)) + count += 1 + return AccountMutationResult(upserted=count, revision=rev) + + async def patch_accounts( + self, + patches: list[AccountPatch], + ) -> AccountMutationResult: + if not patches: + return AccountMutationResult() + await self._ensure_initialized() + async with self._engine.begin() as conn: + rev = await self._bump_revision(conn) + ts = now_ms() + count = 0 + for patch in patches: + # S3 修复:SELECT FOR UPDATE 锁行,避免多个并发 patch_accounts + # 在 read-modify-write 期间互相覆盖(JSON 列 / tags / ext 的 lost-update)。 + # 数值列改用原子表达式 col=col+delta,无需依赖 Python 端计算。 + # SQLite 在 SQL 后端不走这条路径(用 local.py 的 asyncio.Lock 串行化)。 + row = (await conn.execute( + sa.select(accounts_table) + .where(accounts_table.c.token == patch.token) + .with_for_update() + )).fetchone() + if row is None: + continue + record = _row_to_record(row) + + updates: dict[str, Any] = {"updated_at": ts, "revision": rev} + if patch.pool is not None: + updates["pool"] = patch.pool + if patch.status is not None: + updates["status"] = patch.status.value + if patch.state_reason is not None: + updates["state_reason"] = patch.state_reason + if patch.last_use_at is not None: + updates["last_use_at"] = patch.last_use_at + if patch.last_fail_at is not None: + updates["last_fail_at"] = patch.last_fail_at + if patch.last_fail_reason is not None: + updates["last_fail_reason"] = patch.last_fail_reason + if patch.last_sync_at is not None: + updates["last_sync_at"] = patch.last_sync_at + if patch.last_clear_at is not None: + updates["last_clear_at"] = patch.last_clear_at + if patch.quota_auto is not None: + updates["quota_auto"] = json.dumps(patch.quota_auto) + if patch.quota_fast is not None: + updates["quota_fast"] = json.dumps(patch.quota_fast) + if patch.quota_expert is not None: + updates["quota_expert"] = json.dumps(patch.quota_expert) + if patch.quota_heavy is not None: + updates["quota_heavy"] = json.dumps(patch.quota_heavy) + if patch.quota_grok_4_3 is not None: + updates["quota_grok_4_3"] = json.dumps(patch.quota_grok_4_3) + if patch.quota_console is not None: + updates["quota_console"] = json.dumps(patch.quota_console) + # S3 修复:数值列使用原子表达式 GREATEST(0, col+delta), + # 而不是基于 SELECT 出的旧值在 Python 中算新值。 + # GREATEST 在 MySQL/PostgreSQL 上均原生支持。 + if patch.usage_use_delta is not None: + delta = int(patch.usage_use_delta) + updates["usage_use_count"] = sa.text( + f"GREATEST(0, usage_use_count + {delta})" + ) + if patch.usage_fail_delta is not None: + delta = int(patch.usage_fail_delta) + updates["usage_fail_count"] = sa.text( + f"GREATEST(0, usage_fail_count + {delta})" + ) + if patch.usage_sync_delta is not None: + delta = int(patch.usage_sync_delta) + updates["usage_sync_count"] = sa.text( + f"GREATEST(0, usage_sync_count + {delta})" + ) + + tags = list(record.tags) + if patch.tags is not None: + tags = patch.tags + if patch.add_tags: + for t in patch.add_tags: + if t not in tags: + tags.append(t) + if patch.remove_tags: + tags = [t for t in tags if t not in patch.remove_tags] + updates["tags"] = json.dumps(tags) + + ext = dict(record.ext) + if patch.ext_merge: + ext.update(patch.ext_merge) + if patch.clear_failures: + for k in ("cooldown_until", "cooldown_reason", "disabled_at", + "disabled_reason", "expired_at", "expired_reason", + "forbidden_strikes", "console_429_count"): + ext.pop(k, None) + updates["status"] = AccountStatus.ACTIVE.value + updates["usage_fail_count"] = 0 + updates["last_fail_at"] = None + updates["last_fail_reason"] = None + updates["state_reason"] = None + updates["ext"] = json.dumps(ext) + + await conn.execute( + accounts_table.update() + .where(accounts_table.c.token == patch.token) + .values(**updates) + ) + count += 1 + return AccountMutationResult(patched=count, revision=rev) + + async def delete_accounts( + self, + tokens: list[str], + ) -> AccountMutationResult: + if not tokens: + return AccountMutationResult() + await self._ensure_initialized() + async with self._engine.begin() as conn: + rev = await self._bump_revision(conn) + ts = now_ms() + result = await conn.execute( + accounts_table.update() + .where( + accounts_table.c.token.in_(tokens), + accounts_table.c.deleted_at.is_(None), + ) + .values(deleted_at=ts, updated_at=ts, revision=rev) + ) + return AccountMutationResult(deleted=result.rowcount, revision=rev) + + async def get_accounts( + self, + tokens: list[str], + ) -> list[AccountRecord]: + if not tokens: + return [] + await self._ensure_initialized() + async with self._engine.connect() as conn: + rows = (await conn.execute( + sa.select(accounts_table).where(accounts_table.c.token.in_(tokens)) + )).fetchall() + return [_row_to_record(r) for r in rows] + + async def list_accounts( + self, + query: ListAccountsQuery, + ) -> AccountPage: + await self._ensure_initialized() + async with self._engine.connect() as conn: + stmt = sa.select(accounts_table) + if not query.include_deleted: + stmt = stmt.where(accounts_table.c.deleted_at.is_(None)) + if query.pool: + stmt = stmt.where(accounts_table.c.pool == query.pool) + if query.status: + stmt = stmt.where(accounts_table.c.status == query.status.value) + + total_row = (await conn.execute( + sa.select(sa.func.count()).select_from(stmt.subquery()) + )).scalar() + total = int(total_row or 0) + + sort_col = getattr(accounts_table.c, query.sort_by, accounts_table.c.updated_at) + if query.sort_desc: + stmt = stmt.order_by(sort_col.desc()) + else: + stmt = stmt.order_by(sort_col.asc()) + offset = (query.page - 1) * query.page_size + stmt = stmt.limit(query.page_size).offset(offset) + + rows = (await conn.execute(stmt)).fetchall() + rev = await self._get_revision(conn) + return AccountPage( + items=[_row_to_record(r) for r in rows], + total=total, + page=query.page, + page_size=query.page_size, + total_pages=max(1, (total + query.page_size - 1) // query.page_size), + revision=rev, + ) + + async def replace_pool( + self, + command: BulkReplacePoolCommand, + ) -> AccountMutationResult: + await self._ensure_initialized() + async with self._engine.begin() as conn: + rev = await self._bump_revision(conn) + ts = now_ms() + del_result = await conn.execute( + accounts_table.update() + .where( + accounts_table.c.pool == command.pool, + accounts_table.c.deleted_at.is_(None), + ) + .values(deleted_at=ts, updated_at=ts, revision=rev) + ) + deleted = del_result.rowcount + + upserted_result = await self.upsert_accounts(command.upserts) + return AccountMutationResult( + upserted=upserted_result.upserted, + deleted=deleted, + revision=upserted_result.revision, + ) + + async def reset_expired_console_windows(self) -> int: + """Batch-reset exhausted + expired console quotas via direct SQL. + + 处理两种异常情况: + 1. 老条件:remaining<=0 且 (reset_at IS NULL 或已过期) → 正常配额耗尽恢复 + 2. 新条件 (M6):reset_at 已过期(即使 remaining>0)→ 异常数据归位 + """ + import json as _json + now = now_ms() + + if self._dialect == "postgresql": + count_sql = sa.text( + "SELECT COUNT(*) FROM accounts" + " WHERE status = 'active'" + " AND deleted_at IS NULL" + " AND (" + " (" + " (quota_console->>'remaining')::int <= 0" + " AND (" + " quota_console->>'reset_at' IS NULL" + " OR (quota_console->>'reset_at')::bigint < :now" + " )" + " )" + " OR (" + " quota_console->>'reset_at' IS NOT NULL" + " AND (quota_console->>'reset_at')::bigint < :now" + " )" + " )" + ) + update_sql = sa.text( + "UPDATE accounts" + " SET quota_console = :reset_json, revision = :rev, updated_at = :now" + " WHERE status = 'active'" + " AND deleted_at IS NULL" + " AND (" + " (" + " (quota_console->>'remaining')::int <= 0" + " AND (" + " quota_console->>'reset_at' IS NULL" + " OR (quota_console->>'reset_at')::bigint < :now" + " )" + " )" + " OR (" + " quota_console->>'reset_at' IS NOT NULL" + " AND (quota_console->>'reset_at')::bigint < :now" + " )" + " )" + ) + else: + # MySQL + count_sql = sa.text( + "SELECT COUNT(*) FROM accounts" + " WHERE status = 'active'" + " AND deleted_at IS NULL" + " AND (" + " (" + " CAST(JSON_EXTRACT(quota_console, '$.remaining') AS SIGNED) <= 0" + " AND (" + " JSON_EXTRACT(quota_console, '$.reset_at') IS NULL" + " OR CAST(JSON_EXTRACT(quota_console, '$.reset_at') AS SIGNED) < :now" + " )" + " )" + " OR (" + " JSON_EXTRACT(quota_console, '$.reset_at') IS NOT NULL" + " AND CAST(JSON_EXTRACT(quota_console, '$.reset_at') AS SIGNED) < :now" + " )" + " )" + ) + update_sql = sa.text( + "UPDATE accounts" + " SET quota_console = :reset_json, revision = :rev, updated_at = :now" + " WHERE status = 'active'" + " AND deleted_at IS NULL" + " AND (" + " (" + " CAST(JSON_EXTRACT(quota_console, '$.remaining') AS SIGNED) <= 0" + " AND (" + " JSON_EXTRACT(quota_console, '$.reset_at') IS NULL" + " OR CAST(JSON_EXTRACT(quota_console, '$.reset_at') AS SIGNED) < :now" + " )" + " )" + " OR (" + " JSON_EXTRACT(quota_console, '$.reset_at') IS NOT NULL" + " AND CAST(JSON_EXTRACT(quota_console, '$.reset_at') AS SIGNED) < :now" + " )" + " )" + ) + + async with self._session() as session: + async with session.begin(): + result = await session.execute(count_sql, {"now": now}) + count = result.scalar() or 0 + if count == 0: + return 0 + + reset_json = _json.dumps({ + "remaining": BASIC_CONSOLE_LIMIT, + "total": BASIC_CONSOLE_LIMIT, + "window_seconds": BASIC_CONSOLE_WINDOW_SECONDS, + "reset_at": None, + "synced_at": now, + "source": 0, + }) + rev = await self._bump_revision(session) + result = await session.execute(update_sql, { + "reset_json": reset_json, + "rev": rev, + "now": now, + }) + return result.rowcount or count + + async def recover_console_expired_accounts(self) -> int: + """Auto-recover console 429 EXPIRED accounts with successful history. + + Conditions: + - status = 'expired' + - state_reason = 'console_429_threshold_exceeded' + - usage_use_count > 5 + - ext.expired_at <= now - 1 hour + """ + import json as _json + now = now_ms() + recovery_threshold = now - 3600 * 1000 + + if self._dialect == "postgresql": + select_sql = sa.text( + "SELECT token, ext FROM accounts" + " WHERE status = 'expired'" + " AND deleted_at IS NULL" + " AND state_reason = 'console_429_threshold_exceeded'" + " AND usage_use_count > 5" + " AND (ext->>'expired_at')::bigint <= :threshold" + ) + else: + # MySQL + select_sql = sa.text( + "SELECT token, ext FROM accounts" + " WHERE status = 'expired'" + " AND deleted_at IS NULL" + " AND state_reason = 'console_429_threshold_exceeded'" + " AND usage_use_count > 5" + " AND CAST(JSON_EXTRACT(ext, '$.expired_at') AS SIGNED) <= :threshold" + ) + + update_sql = sa.text( + "UPDATE accounts" + " SET status = 'active'," + " state_reason = NULL," + " ext = :ext_json," + " revision = :rev," + " updated_at = :now" + " WHERE token = :token" + ) + + async with self._session() as session: + async with session.begin(): + rows = (await session.execute( + select_sql, {"threshold": recovery_threshold} + )).fetchall() + + if not rows: + return 0 + + rev = await self._bump_revision(session) + count = 0 + for row in rows: + token = row[0] + ext_raw = row[1] + try: + ext = _json.loads(ext_raw) if ext_raw else {} + except (ValueError, TypeError): + ext = {} + for k in ("expired_at", "expired_reason", + "console_429_count", "console_429_last_at"): + ext.pop(k, None) + await session.execute(update_sql, { + "ext_json": _json.dumps(ext), + "rev": rev, + "now": now, + "token": token, + }) + count += 1 + return count + + async def close(self) -> None: + """Dispose the SQLAlchemy connection pool.""" + if self._dispose_engine: + _evict_cached_engine(self._engine) + await self._engine.dispose() + + +def _engine_cache_key(dialect: str, normalized_url: str, connect_args: dict[str, Any] | None) -> tuple[str, str, str]: + """Build a stable cache key from the normalized URL and connect args.""" + args_key = str(sorted(connect_args.items(), key=lambda kv: kv[0])) if connect_args else "" + return (dialect, normalized_url, args_key) + + +def create_mysql_engine(url: str) -> AsyncEngine: + """Create an async SQLAlchemy engine for MySQL.""" + normalized_url, connect_args = _prepare_sql_url_and_connect_args("mysql", (url or "").strip()) + return _get_or_create_engine(_engine_cache_key("mysql", normalized_url, connect_args), normalized_url, connect_args) + + +def create_pgsql_engine(url: str) -> AsyncEngine: + """Create an async SQLAlchemy engine for PostgreSQL.""" + normalized_url, connect_args = _prepare_sql_url_and_connect_args("postgresql", (url or "").strip()) + return _get_or_create_engine(_engine_cache_key("postgresql", normalized_url, connect_args), normalized_url, connect_args) + + +__all__ = ["SqlAccountRepository", "create_mysql_engine", "create_pgsql_engine"] diff --git a/app/control/account/commands.py b/app/control/account/commands.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7529f6bde50d22ecab03ba6772cef1aa7426fd --- /dev/null +++ b/app/control/account/commands.py @@ -0,0 +1,81 @@ +"""Command / query objects for the account control plane.""" + +from typing import Any + +from pydantic import BaseModel, Field + +from .enums import AccountStatus + + +class AccountUpsert(BaseModel): + """Create-or-replace command for a single account. + + Only ``token`` is required; all other fields use safe defaults. + """ + + token: str + pool: str = "basic" + tags: list[str] = Field(default_factory=list) + ext: dict[str, Any] = Field(default_factory=dict) + + +class AccountPatch(BaseModel): + """Partial update — only supplied fields are written. + + Fields left as ``None`` are **not** modified in the backend. + """ + + token: str + pool: str | None = None # update pool type when inferred + status: AccountStatus | None = None + tags: list[str] | None = None + add_tags: list[str] | None = None + remove_tags: list[str] | None = None + # Per-mode quota patches (raw dicts matching QuotaWindow.to_dict()). + quota_auto: dict[str, Any] | None = None + quota_fast: dict[str, Any] | None = None + quota_expert: dict[str, Any] | None = None + quota_heavy: dict[str, Any] | None = None + quota_grok_4_3: dict[str, Any] | None = None + quota_console: dict[str, Any] | None = None + # Usage counters — delta values (added to existing counts). + usage_use_delta: int | None = None + usage_fail_delta: int | None = None + usage_sync_delta: int | None = None + # Timestamp overrides (set absolute values). + last_use_at: int | None = None + last_fail_at: int | None = None + last_fail_reason: str | None = None + last_sync_at: int | None = None + last_clear_at: int | None = None + state_reason: str | None = None + ext_merge: dict[str, Any] | None = None + clear_failures: bool = False + + +class ListAccountsQuery(BaseModel): + """Query parameters for paginated account listing.""" + + page: int = Field(default=1, ge=1) + page_size: int = Field(default=50, ge=1, le=2000) + pool: str | None = None + status: AccountStatus | None = None + tags: list[str] = Field(default_factory=list) + include_deleted: bool = False + sort_by: str = "updated_at" # field name + sort_desc: bool = True + + +class BulkReplacePoolCommand(BaseModel): + """Replace all accounts in a pool atomically.""" + + pool: str + upserts: list[AccountUpsert] = Field(default_factory=list) + + +__all__ = [ + "AccountUpsert", + "AccountPatch", + "ListAccountsQuery", + "BulkReplacePoolCommand", +] diff --git a/app/control/account/enums.py b/app/control/account/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..c6252849e17baaab72a6af3a5aa9ef4d133d8d2f --- /dev/null +++ b/app/control/account/enums.py @@ -0,0 +1,39 @@ +"""Control-plane account enumerations.""" + +from enum import IntEnum, StrEnum + + +class AccountStatus(StrEnum): + """Persistent lifecycle status of an account record.""" + + ACTIVE = "active" + COOLING = "cooling" + EXPIRED = "expired" + DISABLED = "disabled" + + +class QuotaSource(IntEnum): + """Reliability of a stored QuotaWindow value. + + Integer values are stored in the quota JSON payload. + """ + + DEFAULT = 0 # Never synced; using built-in default. + REAL = 1 # Retrieved from upstream rate-limits API. + ESTIMATED = 2 # Locally decremented after a failed API call. + + +class FeedbackKind(StrEnum): + """Classification of the outcome of a single upstream request.""" + + SUCCESS = "success" + UNAUTHORIZED = "unauthorized" # 401 — token invalid / expired + FORBIDDEN = "forbidden" # 403 — account suspended / CF challenge + RATE_LIMITED = "rate_limited" # 429 — quota exhausted + SERVER_ERROR = "server_error" # 5xx — upstream fault + DISABLE = "disable" # operator-initiated disable + DELETE = "delete" # operator-initiated delete + RESTORE = "restore" # operator-initiated restore + + +__all__ = ["AccountStatus", "QuotaSource", "FeedbackKind"] diff --git a/app/control/account/invalid_credentials.py b/app/control/account/invalid_credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..fa6826233aa7fdba94f62a829559a3cb4c796984 --- /dev/null +++ b/app/control/account/invalid_credentials.py @@ -0,0 +1,82 @@ +"""Shared handling for upstream invalid-credential failures.""" + +from typing import TYPE_CHECKING + +from app.platform.errors import UpstreamError +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_ms + +from .commands import AccountPatch +from .enums import AccountStatus, FeedbackKind + +if TYPE_CHECKING: + from .repository import AccountRepository + + +async def mark_account_invalid_credentials( + repo: "AccountRepository", + token: str, + exc: BaseException, + *, + source: str, +) -> bool: + """Mark *token* as invalid when *exc* matches Grok invalid credentials.""" + from app.dataplane.reverse.protocol.xai_usage import is_invalid_credentials_error + + if not is_invalid_credentials_error(exc): + return False + + record = next(iter(await repo.get_accounts([token])), None) + reason = "invalid_credentials" + ts = now_ms() + ext = record.ext if record is not None else {} + + await repo.patch_accounts( + [ + AccountPatch( + token=token, + status=AccountStatus.EXPIRED, + last_fail_at=ts, + last_fail_reason=reason, + state_reason=reason, + ext_merge={ + **ext, + "expired_at": ts, + "expired_reason": reason, + }, + ) + ] + ) + logger.info( + "account expired from {}: token={}... status={} upstream_status={}", + source, + token[:10], + AccountStatus.EXPIRED, + getattr(exc, "status", None) if isinstance(exc, UpstreamError) else None, + ) + return True + + +def feedback_kind_for_error(exc: BaseException | None) -> FeedbackKind: + """Map an upstream exception to the appropriate account feedback kind.""" + if exc is None: + return FeedbackKind.SERVER_ERROR + # Check for known blocked/invalid body markers first — these override + # the generic status-code mapping so that e.g. a 403 with "blocked-user" + # body is treated as an account-level credential failure, not a generic + # FORBIDDEN that only lowers health. + from app.dataplane.reverse.protocol.xai_usage import is_invalid_credentials_error + + if is_invalid_credentials_error(exc): + return FeedbackKind.UNAUTHORIZED + status = getattr(exc, "status", 0) + if status == 429: + return FeedbackKind.RATE_LIMITED + if status == 401: + return FeedbackKind.UNAUTHORIZED + if status == 403: + return FeedbackKind.FORBIDDEN + return FeedbackKind.SERVER_ERROR + + +__all__ = ["mark_account_invalid_credentials", "feedback_kind_for_error"] diff --git a/app/control/account/models.py b/app/control/account/models.py new file mode 100644 index 0000000000000000000000000000000000000000..dc7367e595aac88af19d6d1b034e3c570727a6ae --- /dev/null +++ b/app/control/account/models.py @@ -0,0 +1,347 @@ +"""Control-plane account models — persistent record shape.""" + +from dataclasses import dataclass +from typing import Any + +from pydantic import BaseModel, Field, field_validator + +from app.platform.runtime.clock import now_ms +from .enums import AccountStatus, QuotaSource + + +# --------------------------------------------------------------------------- +# QuotaWindow +# --------------------------------------------------------------------------- + + +@dataclass(slots=True) +class QuotaWindow: + """Rate-limit window for one mode (auto / fast / expert). + + ``remaining`` — queries remaining in the current window. + ``total`` — total queries per window. + ``window_seconds`` — window duration in seconds. + ``reset_at`` — ms timestamp when the window resets; None = unknown. + ``synced_at`` — ms timestamp of last upstream sync; None = never. + ``source`` — reliability of this value. + """ + + remaining: int + total: int + window_seconds: int + reset_at: int | None + synced_at: int | None + source: QuotaSource + + def is_exhausted(self) -> bool: + return self.remaining <= 0 + + def is_window_expired(self, now: int) -> bool: + """Return True if the reset timestamp has passed.""" + return self.reset_at is not None and now >= self.reset_at + + def to_dict(self) -> dict[str, Any]: + return { + "remaining": self.remaining, + "total": self.total, + "window_seconds": self.window_seconds, + "reset_at": self.reset_at, + "synced_at": self.synced_at, + "source": int(self.source), + } + + @classmethod + def from_dict(cls, d: dict[str, Any]) -> "QuotaWindow": + return cls( + remaining=int(d.get("remaining", 0)), + total=int(d.get("total", 0)), + window_seconds=int(d.get("window_seconds", 0)), + reset_at=d.get("reset_at"), + synced_at=d.get("synced_at"), + source=QuotaSource(int(d.get("source", 0))), + ) + + +# --------------------------------------------------------------------------- +# AccountQuotaSet +# --------------------------------------------------------------------------- + + +@dataclass(slots=True) +class AccountQuotaSet: + """Quota set — one window per mode (auto / fast / expert / heavy / grok_4_3). + + ``heavy`` is ``None`` for basic and super accounts. + ``grok_4_3`` is ``None`` for basic accounts (super/heavy only). + """ + + auto: QuotaWindow + fast: QuotaWindow + expert: QuotaWindow + heavy: QuotaWindow | None = None # heavy-pool accounts only + grok_4_3: QuotaWindow | None = None # super/heavy accounts only + console: QuotaWindow | None = None # basic pool console models (console.x.ai) + + def get(self, mode_id: int) -> QuotaWindow | None: + """Return the quota window for *mode_id* (0=auto, 1=fast, 2=expert, 3=heavy, 4=grok_4_3, 5=console).""" + if mode_id == 0: + return self.auto + if mode_id == 1: + return self.fast + if mode_id == 2: + return self.expert + if mode_id == 3: + return self.heavy + if mode_id == 4: + return self.grok_4_3 + if mode_id == 5: + return self.console + return None + + def set(self, mode_id: int, window: QuotaWindow) -> None: + """Replace the quota window for *mode_id*.""" + if mode_id == 0: + self.auto = window + elif mode_id == 1: + self.fast = window + elif mode_id == 2: + self.expert = window + elif mode_id == 3: + self.heavy = window + elif mode_id == 4: + self.grok_4_3 = window + else: + self.console = window # mode_id == 5 + + def to_dict(self) -> dict[str, dict[str, Any]]: + d: dict[str, dict[str, Any]] = { + "auto": self.auto.to_dict(), + "fast": self.fast.to_dict(), + "expert": self.expert.to_dict(), + } + if self.heavy is not None: + d["heavy"] = self.heavy.to_dict() + if self.grok_4_3 is not None: + d["grok_4_3"] = self.grok_4_3.to_dict() + if self.console is not None: + d["console"] = self.console.to_dict() + return d + + @classmethod + def from_dict(cls, d: dict[str, Any]) -> "AccountQuotaSet": + heavy_d = d.get("heavy") + grok_4_3_d = d.get("grok_4_3") + console_d = d.get("console") + return cls( + auto=QuotaWindow.from_dict(d.get("auto", {})), + fast=QuotaWindow.from_dict(d.get("fast", {})), + expert=QuotaWindow.from_dict(d.get("expert", {})), + heavy=QuotaWindow.from_dict(heavy_d) if heavy_d else None, + grok_4_3=QuotaWindow.from_dict(grok_4_3_d) if grok_4_3_d else None, + console=QuotaWindow.from_dict(console_d) if console_d else None, + ) + + +# --------------------------------------------------------------------------- +# AccountUsageStats +# --------------------------------------------------------------------------- + + +@dataclass(slots=True) +class AccountUsageStats: + """Cumulative usage counters for an account.""" + + use_count: int = 0 # Successful calls (SUCCESS feedback) + fail_count: int = 0 # Failed calls (non-success feedback) + sync_count: int = 0 # Usage API sync calls + + def to_dict(self) -> dict[str, int]: + return { + "use_count": self.use_count, + "fail_count": self.fail_count, + "sync_count": self.sync_count, + } + + @classmethod + def from_dict(cls, d: dict[str, Any]) -> "AccountUsageStats": + return cls( + use_count=int(d.get("use_count", 0)), + fail_count=int(d.get("fail_count", 0)), + sync_count=int(d.get("sync_count", 0)), + ) + + +# --------------------------------------------------------------------------- +# AccountRecord (Pydantic — control plane only) +# --------------------------------------------------------------------------- + + +class AccountRecord(BaseModel): + """Persistent account record — single source of truth for all backends. + + ``pool`` values: ``"basic"`` | ``"super"`` | ``"heavy"`` + All timestamps are milliseconds since epoch. + ``ext`` carries non-core extension data only. + """ + + token: str + pool: str = "basic" + status: AccountStatus = AccountStatus.ACTIVE + created_at: int = Field(default_factory=now_ms) + updated_at: int = Field(default_factory=now_ms) + tags: list[str] = Field(default_factory=list) + # Serialised form of AccountQuotaSet. Stored as dict for Pydantic + # round-tripping; use .quota_set() to deserialise, .with_quota_set() + # to produce an updated copy. + quota: dict[str, Any] = Field(default_factory=dict) + usage_use_count: int = 0 + usage_fail_count: int = 0 + usage_sync_count: int = 0 + last_use_at: int | None = None + last_fail_at: int | None = None + last_fail_reason: str | None = None + last_sync_at: int | None = None + last_clear_at: int | None = None + state_reason: str | None = None + deleted_at: int | None = None + ext: dict[str, Any] = Field(default_factory=dict) + revision: int = 0 + + # --- computed properties --- + + @property + def is_nsfw(self) -> bool: + return "nsfw" in self.tags + + @property + def is_super(self) -> bool: + return self.pool == "super" + + @property + def is_heavy(self) -> bool: + return self.pool == "heavy" + + def is_deleted(self) -> bool: + return self.deleted_at is not None + + def quota_set(self) -> AccountQuotaSet: + """Deserialise the stored quota dict into an AccountQuotaSet.""" + return AccountQuotaSet.from_dict(self.quota) + + def with_quota_set(self, qs: AccountQuotaSet) -> "AccountRecord": + """Return a copy of this record with the given quota set serialised.""" + return self.model_copy(update={"quota": qs.to_dict()}) + + # --- validators --- + + @field_validator("token", mode="before") + @classmethod + def _normalize_token(cls, v: Any) -> str: + if v is None: + raise ValueError("token cannot be None") + token = str(v) + # Normalise Unicode dash / space variants and strip zero-width chars. + token = token.translate( + str.maketrans( + { + "\u2010": "-", + "\u2011": "-", + "\u2012": "-", + "\u2013": "-", + "\u2014": "-", + "\u2212": "-", + "\u00a0": " ", + "\u2007": " ", + "\u202f": " ", + "\u200b": "", + "\u200c": "", + "\u200d": "", + "\ufeff": "", + } + ) + ) + token = "".join(token.split()) + if token.startswith("sso="): + token = token[4:] + token = token.encode("ascii", errors="ignore").decode("ascii") + if not token: + raise ValueError("token is empty after normalisation") + return token + + @field_validator("pool", mode="before") + @classmethod + def _normalize_pool(cls, v: Any) -> str: + val = str(v or "").strip().lower() + if val in ("super"): + return "super" + if val in ("heavy",): + return "heavy" + if val in ("ssobasic", "basic", "", "auto"): + # "auto" is a UI alias meaning "let quota sync decide"; + # save as basic for now — refresh will correct to the real type. + return "basic" + raise ValueError(f"Unknown pool: {v!r}") + + @field_validator("tags", mode="before") + @classmethod + def _normalize_tags(cls, v: Any) -> list[str]: + if not v: + return [] + if isinstance(v, str): + v = [p.strip() for p in v.split(",")] + seen: list[str] = [] + for item in v: + tag = str(item).strip() + if tag and tag not in seen: + seen.append(tag) + return seen + + +# --------------------------------------------------------------------------- +# Lightweight result types +# --------------------------------------------------------------------------- + + +class AccountMutationResult(BaseModel): + upserted: int = 0 + patched: int = 0 + deleted: int = 0 + revision: int = 0 + + +class AccountPage(BaseModel): + items: list[AccountRecord] = Field(default_factory=list) + total: int = 0 + page: int = 1 + page_size: int = 50 + total_pages: int = 1 + revision: int = 0 + + +class AccountChangeSet(BaseModel): + revision: int = 0 + # 本批返回行中观察到的最大 revision。 + # 当 has_more=True 时,调用方应只推进到 batch_max_revision, + # 避免跳过尚未返回的中间行(参见 S2 修复)。 + # 若本批为空则为 0。 + batch_max_revision: int = 0 + items: list[AccountRecord] = Field(default_factory=list) + deleted_tokens: list[str] = Field(default_factory=list) + has_more: bool = False + + +class RuntimeSnapshot(BaseModel): + revision: int = 0 + items: list[AccountRecord] = Field(default_factory=list) + + +__all__ = [ + "QuotaWindow", + "AccountQuotaSet", + "AccountUsageStats", + "AccountRecord", + "AccountMutationResult", + "AccountPage", + "AccountChangeSet", + "RuntimeSnapshot", +] diff --git a/app/control/account/quota_defaults.py b/app/control/account/quota_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f5b0c5824e440f5c2323456d298cca7f1fa86a --- /dev/null +++ b/app/control/account/quota_defaults.py @@ -0,0 +1,205 @@ +"""Default quota windows and pool inference logic. + +Canonical quota totals per pool type (from upstream rate-limits API): + + auto fast expert heavy grok_4_3 + basic — 30 — — — window: 86400 s + super 50 140 50 — 50 window: 7200 s + heavy 150 400 150 20 150 window: 7200 s + +Pool inference uses ``auto.total`` as the primary signal for super/heavy +accounts; basic accounts no longer expose auto/expert windows locally. +""" + +from typing import TYPE_CHECKING + +from .enums import QuotaSource +from .models import AccountQuotaSet, QuotaWindow + +if TYPE_CHECKING: + pass + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _w(remaining: int, total: int, window_seconds: int) -> QuotaWindow: + return QuotaWindow( + remaining=remaining, + total=total, + window_seconds=window_seconds, + reset_at=None, + synced_at=None, + source=QuotaSource.DEFAULT, + ) + + +# --------------------------------------------------------------------------- +# Per-pool default quota sets +# --------------------------------------------------------------------------- + +BASIC_FAST_LIMIT = 30 +BASIC_FAST_WINDOW_SECONDS = 86_400 + +BASIC_CONSOLE_LIMIT = 20 +BASIC_CONSOLE_WINDOW_SECONDS = 3600 + +BASIC_QUOTA_DEFAULTS = AccountQuotaSet( + auto=_w(0, 0, 0), # unsupported on basic accounts + fast=_w(BASIC_FAST_LIMIT, BASIC_FAST_LIMIT, BASIC_FAST_WINDOW_SECONDS), + expert=_w(0, 0, 0), # unsupported on basic accounts + console=_w(BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_WINDOW_SECONDS), +) + +SUPER_QUOTA_DEFAULTS = AccountQuotaSet( + auto=_w(50, 50, 7_200), # 50 queries / 2 h + fast=_w(140, 140, 7_200), # 140 queries / 2 h + expert=_w(50, 50, 7_200), # 50 queries / 2 h + grok_4_3=_w(50, 50, 7_200), # 50 queries / 2 h +) + +HEAVY_QUOTA_DEFAULTS = AccountQuotaSet( + auto=_w(150, 150, 7_200), # 150 queries / 2 h + fast=_w(400, 400, 7_200), # 400 queries / 2 h + expert=_w(150, 150, 7_200), # 150 queries / 2 h + heavy=_w(20, 20, 7_200), # 20 queries / 2 h + grok_4_3=_w(150, 150, 7_200), # 150 queries / 2 h +) + +# Map pool name → defaults object (used by backends on upsert). +_POOL_DEFAULTS: dict[str, AccountQuotaSet] = { + "basic": BASIC_QUOTA_DEFAULTS, + "super": SUPER_QUOTA_DEFAULTS, + "heavy": HEAVY_QUOTA_DEFAULTS, +} + +_SUPPORTED_MODE_IDS_BY_POOL: dict[str, frozenset[int]] = { + "basic": frozenset((1, 5)), + "super": frozenset((0, 1, 2, 4, 5)), + "heavy": frozenset((0, 1, 2, 3, 4, 5)), +} + +# --------------------------------------------------------------------------- +# Pool inference — keyed on auto.total (unique across pool types) +# --------------------------------------------------------------------------- + +_AUTO_TOTAL_TO_POOL: dict[int, str] = { + 20: "basic", + 50: "super", + 150: "heavy", +} + + +def default_quota_set(pool: str) -> AccountQuotaSet: + """Return a fresh copy of the default quota set for *pool*.""" + src = _POOL_DEFAULTS.get(pool, BASIC_QUOTA_DEFAULTS) + qs = AccountQuotaSet( + auto=_w(src.auto.remaining, src.auto.total, src.auto.window_seconds), + fast=_w(src.fast.remaining, src.fast.total, src.fast.window_seconds), + expert=_w(src.expert.remaining, src.expert.total, src.expert.window_seconds), + ) + if src.heavy is not None: + qs.heavy = _w(src.heavy.remaining, src.heavy.total, src.heavy.window_seconds) + if src.grok_4_3 is not None: + qs.grok_4_3 = _w( + src.grok_4_3.remaining, src.grok_4_3.total, src.grok_4_3.window_seconds + ) + if src.console is not None: + qs.console = _w( + src.console.remaining, src.console.total, src.console.window_seconds + ) + return qs + + +def supports_mode(pool: str, mode_id: int) -> bool: + """Return whether *pool* has a default quota window for *mode_id*.""" + return mode_id in _SUPPORTED_MODE_IDS_BY_POOL.get( + pool, _SUPPORTED_MODE_IDS_BY_POOL["basic"] + ) + + +def supported_mode_ids(pool: str) -> tuple[int, ...]: + """Return the supported mode IDs for *pool* in stable request order.""" + supported = _SUPPORTED_MODE_IDS_BY_POOL.get( + pool, _SUPPORTED_MODE_IDS_BY_POOL["basic"] + ) + return tuple(mode_id for mode_id in (0, 1, 2, 3, 4, 5) if mode_id in supported) + + +def default_quota_window(pool: str, mode_id: int) -> QuotaWindow | None: + """Return the default quota window for *(pool, mode_id)*, if supported.""" + if not supports_mode(pool, mode_id): + return None + return default_quota_set(pool).get(mode_id) + + +def normalize_quota_window( + pool: str, mode_id: int, window: QuotaWindow | None +) -> QuotaWindow | None: + """Apply product-level quota policy for one pool/mode window.""" + if window is None or not supports_mode(pool, mode_id): + return None + if pool == "basic" and mode_id == 1: + return QuotaWindow( + remaining=max(0, min(int(window.remaining), BASIC_FAST_LIMIT)), + total=BASIC_FAST_LIMIT, + window_seconds=BASIC_FAST_WINDOW_SECONDS, + reset_at=window.reset_at, + synced_at=window.synced_at, + source=window.source, + ) + if pool == "basic" and mode_id == 5: + # L1 修复:矫正历史 console 配额数据到当前常量值 + # 历史值如 200/24h、70/5min、100/1min、30/15min、30/30min 等均归一到 20/60min + return QuotaWindow( + remaining=max(0, min(int(window.remaining), BASIC_CONSOLE_LIMIT)), + total=BASIC_CONSOLE_LIMIT, + window_seconds=BASIC_CONSOLE_WINDOW_SECONDS, + reset_at=window.reset_at, + synced_at=window.synced_at, + source=window.source, + ) + return window + + +def normalize_quota_set(pool: str, quota_set: AccountQuotaSet) -> AccountQuotaSet: + """Return a quota set normalized to the supported modes for *pool*.""" + defaults = default_quota_set(pool) + + auto = normalize_quota_window(pool, 0, quota_set.auto) or defaults.auto + fast = normalize_quota_window(pool, 1, quota_set.fast) or defaults.fast + expert = normalize_quota_window(pool, 2, quota_set.expert) or defaults.expert + + qs = AccountQuotaSet(auto=auto, fast=fast, expert=expert) + qs.heavy = normalize_quota_window(pool, 3, quota_set.heavy) + qs.grok_4_3 = normalize_quota_window(pool, 4, quota_set.grok_4_3) + qs.console = normalize_quota_window(pool, 5, quota_set.console) or defaults.console + return qs + + +def infer_pool(windows: dict[int, QuotaWindow]) -> str: + """Infer pool type from live quota windows returned by the rate-limits API. + + Uses ``auto.total`` (mode_id=0) as the discriminating signal. + Falls back to ``"basic"`` when the value is absent or unrecognised. + """ + auto_win = windows.get(0) + if auto_win is None: + return "basic" + return _AUTO_TOTAL_TO_POOL.get(auto_win.total, "basic") + + +__all__ = [ + "BASIC_QUOTA_DEFAULTS", + "SUPER_QUOTA_DEFAULTS", + "HEAVY_QUOTA_DEFAULTS", + "default_quota_set", + "default_quota_window", + "infer_pool", + "normalize_quota_set", + "normalize_quota_window", + "supported_mode_ids", + "supports_mode", +] diff --git a/app/control/account/refresh.py b/app/control/account/refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..2d363de22c083d608112940a65a688948cc53f03 --- /dev/null +++ b/app/control/account/refresh.py @@ -0,0 +1,675 @@ +"""Account refresh service — mode-aware usage synchronisation.""" + +import asyncio +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from app.platform.errors import UpstreamError +from app.platform.config.snapshot import get_config +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_ms +from app.platform.runtime.batch import run_batch +from app.control.model.enums import ALL_MODES_FULL +from .enums import AccountStatus, QuotaSource +from .models import AccountRecord, QuotaWindow +from .quota_defaults import ( + default_quota_window, + infer_pool, + normalize_quota_window, + supported_mode_ids, + supports_mode, +) +from .state_machine import is_manageable + +if TYPE_CHECKING: + from .repository import AccountRepository + + +@dataclass +class RefreshResult: + checked: int = 0 + refreshed: int = 0 + recovered: int = 0 + expired: int = 0 + disabled: int = 0 + rate_limited: int = 0 + failed: int = 0 + + def merge(self, other: "RefreshResult") -> None: + self.checked += other.checked + self.refreshed += other.refreshed + self.recovered += other.recovered + self.expired += other.expired + self.disabled += other.disabled + self.rate_limited += other.rate_limited + self.failed += other.failed + + +_MODE_KEYS = { + 0: "quota_auto", + 1: "quota_fast", + 2: "quota_expert", + 3: "quota_heavy", + 4: "quota_grok_4_3", + 5: "quota_console", # console.x.ai 独立配额 +} + + +def _infer_pool_from_live_windows(windows: dict[int, QuotaWindow]) -> str | None: + """Infer pool only from quota totals that identify an entitlement tier.""" + auto_win = windows.get(0) + if auto_win is not None: + inferred = infer_pool(windows) # type: ignore[arg-type] + if inferred != "basic" or auto_win.total == 20: + return inferred + + for mode_id in (2, 4): + win = windows.get(mode_id) + if win is None: + continue + if win.total == 150: + return "heavy" + if win.total == 50: + return "super" + return None + + +class AccountRefreshService: + """Fetches real quota data from the upstream usage API and persists it. + + Triggers: + 1. Import — fetch all modes supported by the account's pool. + 2. Call — fetch the called mode only (async, non-blocking). + 3. Schedule — refresh one pool per loop using that pool's supported modes. + """ + + def __init__(self, repository: "AccountRepository") -> None: + self._repo = repository + self._lock = asyncio.Lock() + self._od_lock = asyncio.Lock() + self._od_last = 0.0 + + # ------------------------------------------------------------------ + # Usage API fetch (delegates to dataplane reverse protocol) + # ------------------------------------------------------------------ + + async def _fetch_all_quotas( + self, token: str, pool: str, *, bootstrap: bool = False + ) -> dict[int, QuotaWindow] | None: + """Fetch quota windows for every mode supported by *pool*. + + Examples: + - basic -> fast + - super -> auto / fast / expert / grok_4_3 + - heavy -> auto / fast / expert / heavy / grok_4_3 + """ + try: + from app.dataplane.reverse.protocol.xai_usage import fetch_all_quotas + + mode_ids = supported_mode_ids(pool) + if bootstrap: + # Bootstrap refreshes need entitlement probes even when the + # current local image is basic. If auto is flaky, expert/heavy + # windows still provide enough signal to avoid a sticky + # misclassification. + mode_ids = tuple(dict.fromkeys((0, 2, 3, 4, *mode_ids))) + return await fetch_all_quotas(token, mode_ids) + except UpstreamError: + raise + except Exception as exc: + logger.debug( + "account quota fetch failed: token={}... pool={} error={}", + token[:10], + pool, + exc, + ) + return None + + async def _fetch_mode_quota( + self, token: str, pool: str, mode_id: int + ) -> QuotaWindow | None: + """Fetch a single mode quota window.""" + if not supports_mode(pool, mode_id): + logger.debug( + "account mode quota fetch skipped: token={}... pool={} mode_id={} reason=unsupported_mode", + token[:10], + pool, + mode_id, + ) + return None + try: + from app.dataplane.reverse.protocol.xai_usage import fetch_mode_quota + + return await fetch_mode_quota(token, mode_id) + except UpstreamError: + raise + except Exception as exc: + logger.debug( + "account mode quota fetch failed: token={}... pool={} mode_id={} error={}", + token[:10], + pool, + mode_id, + exc, + ) + return None + + # ------------------------------------------------------------------ + # Core refresh logic + # ------------------------------------------------------------------ + + async def refresh_on_import(self, tokens: list[str]) -> RefreshResult: + """Called after bulk import — sync real quotas for all accounts.""" + records = await self._repo.get_accounts(tokens) + active = [r for r in records if is_manageable(r)] + if not active: + return RefreshResult(checked=len(records)) + + concurrency = get_config("account.refresh.usage_concurrency", 15) + results = await run_batch( + active, + lambda r: self._refresh_one(r, apply_fallback=True, bootstrap=True), + concurrency=concurrency, + ) + agg = RefreshResult(checked=len(records)) + for r in results: + agg.merge(r) + return agg + + async def refresh_call_async(self, token: str, mode_id: int) -> None: + """Fire-and-forget single-mode quota sync after a successful call.""" + record = (await self._repo.get_accounts([token]) or [None])[0] + if record is None or record.is_deleted(): + return + + # mode_id=5 (CONSOLE) 是本地管理的配额,不需要请求 xai usage API + # 直接做本地扣减并更新 usage_use_count + if mode_id == 5: + await self._apply_single_mode( + record, mode_id, window=None, is_use=True, use_at_ms=now_ms() + ) + return + + try: + window = await self._fetch_mode_quota(token, record.pool, mode_id) + except UpstreamError as exc: + if await self._expire_invalid_credentials(record, exc): + return + raise + await self._apply_single_mode( + record, mode_id, window, is_use=True, use_at_ms=now_ms() + ) + + async def refresh_scheduled(self, pool: str | None = None) -> RefreshResult: + """Periodic refresh — fetch real quotas for all (or one pool's) accounts. + + Args: + pool: When set, only refreshes accounts belonging to that pool. + When ``None``, refreshes all pools. + """ + snapshot = await self._repo.runtime_snapshot() + records = [r for r in snapshot.items if is_manageable(r)] + if pool is not None: + records = [r for r in records if r.pool == pool] + + concurrency = get_config("account.refresh.usage_concurrency", 15) + results = await run_batch( + records, + lambda r: self._refresh_one(r, apply_fallback=True), + concurrency=concurrency, + ) + agg = RefreshResult() + for r in results: + agg.merge(r) + return agg + + async def refresh_on_demand(self) -> RefreshResult: + """Throttled on-demand refresh triggered by request path.""" + min_interval = float( + get_config("account.refresh.on_demand_min_interval_sec", 300) + ) + import time + + now = time.monotonic() + if now - self._od_last < min_interval: + return RefreshResult() + if self._od_lock.locked(): + return RefreshResult() + async with self._od_lock: + now = time.monotonic() + if now - self._od_last < min_interval: + return RefreshResult() + result = await self.refresh_scheduled() + self._od_last = time.monotonic() + return result + + async def refresh_tokens(self, tokens: list[str]) -> RefreshResult: + """Explicit refresh for a list of tokens (admin / manual trigger).""" + records = [r for r in await self._repo.get_accounts(tokens) if is_manageable(r)] + concurrency = get_config("account.refresh.usage_concurrency", 15) + results = await run_batch( + records, + lambda r: self._refresh_one(r, bootstrap=True), + concurrency=concurrency, + ) + agg = RefreshResult() + for r in results: + agg.merge(r) + return agg + + # ------------------------------------------------------------------ + # Per-account refresh + # ------------------------------------------------------------------ + + async def _refresh_one( + self, + record: AccountRecord, + *, + apply_fallback: bool = False, + bootstrap: bool = False, + ) -> RefreshResult: + """Fetch all pool-supported modes from the usage API and persist them. + + apply_fallback=True — used by scheduled/import paths: when API fails, + decrement REAL quotas or reset expired DEFAULT windows. + apply_fallback=False — used by manual/on-demand paths: if API fails, return + failed=1 immediately without touching stored data. + """ + if record.is_deleted(): + return RefreshResult() + + try: + windows = await self._fetch_all_quotas( + record.token, record.pool, bootstrap=bootstrap + ) + except UpstreamError as exc: + if await self._expire_invalid_credentials(record, exc): + return RefreshResult(checked=1, expired=1, failed=0) + raise + + # API call completely failed — no real data available. + if windows is None: + if not apply_fallback: + return RefreshResult(checked=1, failed=1) + # Scheduled/import path: apply conservative fallback. + return await self._apply_fallback(record) + + # We got at least a response — apply real data per mode. + qs = record.quota_set() + now = now_ms() + patches: dict[str, dict] = {} + refreshed = False + inferred = _infer_pool_from_live_windows(windows) + effective_pool = inferred if (bootstrap and inferred) else record.pool + + for mode in ALL_MODES_FULL: + mode_id = int(mode) + if mode_id in windows: + window = normalize_quota_window( + effective_pool, mode_id, windows[mode_id] + ) + if window is None: + continue + patches[_MODE_KEYS[mode_id]] = window.to_dict() + refreshed = True + elif apply_fallback: + existing = qs.get(mode_id) + if existing is None: + continue + if existing.source == QuotaSource.REAL: + patches[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining=max(0, existing.remaining - 1), + total=existing.total, + window_seconds=existing.window_seconds, + reset_at=existing.reset_at, + synced_at=existing.synced_at, + source=QuotaSource.ESTIMATED, + ).to_dict() + elif existing.is_window_expired(now): + default = default_quota_window(effective_pool, mode_id) + if default is None: + continue + patches[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining=default.total, + total=default.total, + window_seconds=default.window_seconds, + reset_at=now + default.window_seconds * 1000, + synced_at=now, + source=QuotaSource.DEFAULT, + ).to_dict() + + if not patches: + return RefreshResult(checked=1, failed=0 if refreshed else 1) + + # Infer pool type from live quota data and patch if it changed. + pool_patch = inferred if inferred is not None and inferred != record.pool else None + if pool_patch: + logger.info( + "account pool updated from live quota: token={}... previous_pool={} current_pool={}", + record.token[:10], + record.pool, + inferred, + ) + + from .commands import AccountPatch + + await self._repo.patch_accounts( + [ + AccountPatch( + token=record.token, + pool=pool_patch, + last_sync_at=now_ms() if refreshed else None, + usage_sync_delta=1 if refreshed else None, + **patches, # type: ignore[arg-type] + ) + ] + ) + was_cooling = record.status == AccountStatus.COOLING + return RefreshResult( + checked=1, + refreshed=1 if refreshed else 0, + failed=0 if refreshed else 1, + recovered=1 if (was_cooling and refreshed) else 0, + ) + + async def _apply_fallback(self, record: AccountRecord) -> RefreshResult: + """Conservative fallback when API is unreachable (scheduled/import path only).""" + qs = record.quota_set() + now = now_ms() + patches: dict[str, dict] = {} + + for mode in ALL_MODES_FULL: + mode_id = int(mode) + existing = qs.get(mode_id) + if existing is None: + continue + if existing.source == QuotaSource.REAL: + patches[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining=max(0, existing.remaining - 1), + total=existing.total, + window_seconds=existing.window_seconds, + reset_at=existing.reset_at, + synced_at=existing.synced_at, + source=QuotaSource.ESTIMATED, + ).to_dict() + elif existing.is_window_expired(now): + default = default_quota_window(record.pool, mode_id) + if default is None: + continue + patches[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining=default.total, + total=default.total, + window_seconds=default.window_seconds, + reset_at=now + default.window_seconds * 1000, + synced_at=now, + source=QuotaSource.DEFAULT, + ).to_dict() + + if patches: + from .commands import AccountPatch + + await self._repo.patch_accounts( + [AccountPatch(token=record.token, **patches)] + ) # type: ignore[arg-type] + + return RefreshResult(checked=1, failed=1) + + async def record_failure_async( + self, token: str, mode_id: int, exc: BaseException | None = None + ) -> None: + """Fire-and-forget: persist failure counter and timestamp after a failed call.""" + from .commands import AccountPatch + + try: + if exc is not None: + record = next(iter(await self._repo.get_accounts([token])), None) + if record is not None and await self._expire_invalid_credentials( + record, exc + ): + return + if ( + record is not None + and getattr(exc, "status", None) == 429 + and mode_id in _MODE_KEYS + ): + now = now_ms() + quota_patch: dict[str, dict] = {} + window = record.quota_set().get(mode_id) + extra_patch: dict = {} + if window is not None: + if mode_id == 5: + # Console 429: 一次直接清零(扣 20),账号当前窗口不再可用 + # 立即启动恢复计时器,窗口结束后由巡检任务重置 + new_remaining = 0 + reset_at = window.reset_at + if reset_at is None and window.window_seconds > 0: + reset_at = now + window.window_seconds * 1000 + quota_patch[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining=new_remaining, + total=window.total, + window_seconds=window.window_seconds, + reset_at=reset_at, + synced_at=window.synced_at, + source=QuotaSource.ESTIMATED, + ).to_dict() + # Console 专属 429 计数器(独立于 usage_fail_count, + # 避免被 500/网络超时等其他失败干扰)。 + # 12 小时滑动窗口:距离上次 429 超过 12 小时 → 计数重置为 0 + ext_data = record.ext or {} + last_429_at = int(ext_data.get("console_429_last_at", 0)) + sliding_window_ms = 12 * 3600 * 1000 + if last_429_at > 0 and (now - last_429_at) > sliding_window_ms: + console_429_count = 0 + else: + console_429_count = int(ext_data.get("console_429_count", 0)) + new_429_count = console_429_count + 1 + ext_merge: dict = { + **ext_data, + "console_429_count": new_429_count, + "console_429_last_at": now, + } + # 12 小时内累计 3 次 429 标记为 EXPIRED 异常组 + if new_429_count >= 3: + extra_patch["status"] = AccountStatus.EXPIRED + extra_patch["state_reason"] = "console_429_threshold_exceeded" + ext_merge["expired_at"] = now + ext_merge["expired_reason"] = "console_429_threshold_exceeded" + logger.info( + "account marked expired due to repeated 429: token={}... count={}", + token[:10], + new_429_count, + ) + extra_patch["ext_merge"] = ext_merge + else: + # 非 console 模式保持原有清零逻辑 + reset_at = ( + window.reset_at + if window.reset_at is not None and window.reset_at > now + else now + max(window.window_seconds, 1) * 1000 + ) + quota_patch[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining=0, + total=window.total, + window_seconds=window.window_seconds, + reset_at=reset_at, + synced_at=window.synced_at, + source=QuotaSource.ESTIMATED, + ).to_dict() + await self._repo.patch_accounts( + [ + AccountPatch( + token=token, + usage_fail_delta=1, + last_fail_at=now, + last_fail_reason="rate_limited", + **extra_patch, + **quota_patch, + ) + ] + ) + return + await self._repo.patch_accounts( + [ + AccountPatch( + token=token, + usage_fail_delta=1, + last_fail_at=now_ms(), + ) + ] + ) + except Exception as exc: + logger.debug( + "account failure record update failed: token={}... error={}", + token[:10], + exc, + ) + + async def _apply_single_mode( + self, + record: AccountRecord, + mode_id: int, + window: QuotaWindow | None, + *, + is_use: bool = False, + use_at_ms: int | None = None, + ) -> None: + qs = record.quota_set() + mode_key = _MODE_KEYS.get(mode_id) + if mode_key is None: + logger.warning( + "account single-mode sync skipped: token={}... pool={} mode_id={} reason=unknown_mode", + record.token[:10], + record.pool, + mode_id, + ) + return + + quota_patch: dict[str, dict] = {} + if window is not None: + normalized = normalize_quota_window(record.pool, mode_id, window) + if normalized is None: + logger.debug( + "account single-mode quota patch skipped: token={}... pool={} mode_id={} reason=unsupported_mode", + record.token[:10], + record.pool, + mode_id, + ) + return + quota_patch[mode_key] = normalized.to_dict() + else: + existing = qs.get(mode_id) + if existing is not None: + now = now_ms() + # 如果窗口已过期,重置为默认值(适用于本地管理的配额,如 console) + if existing.is_window_expired(now): + default = default_quota_window(record.pool, mode_id) + if default is not None: + new_remaining = max(0, default.total - 1) # 本次调用消耗1次 + # console (mode_id=5) 阈值轮换策略:reset_at=None, + # 让后续扣减在 remaining<=12 时再启动计时器,与 else 分支一致; + # 非 console 模式保持原行为:首次使用即启动计时器 + if mode_id == 5: + reset_at = None + else: + reset_at = now + default.window_seconds * 1000 + quota_patch[mode_key] = QuotaWindow( + remaining=new_remaining, + total=default.total, + window_seconds=default.window_seconds, + reset_at=reset_at, + synced_at=now, + source=QuotaSource.DEFAULT, + ).to_dict() + else: + # Console 配额轮换策略:remaining 降到阈值时才启动恢复计时器, + # 避免同一批账号被反复选中(评分机制会优先选配额充足的账号)。 + new_remaining = max(0, existing.remaining - 1) + reset_at = existing.reset_at + if mode_id == 5: + # console 配额:remaining <= 12 时才启动恢复计时器 + if reset_at is None and new_remaining <= 12 and existing.window_seconds > 0: + reset_at = now + existing.window_seconds * 1000 + else: + # 非 console 模式保持原有逻辑:首次使用即启动计时器 + if reset_at is None and existing.window_seconds > 0: + reset_at = now + existing.window_seconds * 1000 + quota_patch[mode_key] = QuotaWindow( + remaining=new_remaining, + total=existing.total, + window_seconds=existing.window_seconds, + reset_at=reset_at, + synced_at=existing.synced_at, + source=QuotaSource.ESTIMATED, + ).to_dict() + else: + logger.debug( + "account single-mode quota patch skipped: token={}... pool={} mode_id={} reason=unsupported_mode", + record.token[:10], + record.pool, + mode_id, + ) + + from .commands import AccountPatch + + await self._repo.patch_accounts( + [ + AccountPatch( + token=record.token, + last_sync_at=now_ms() if window is not None else None, + usage_sync_delta=1 if window is not None else None, + usage_use_delta=1 if is_use else None, + last_use_at=use_at_ms if is_use else None, + **quota_patch, # type: ignore[arg-type] + ) + ] + ) + + async def _expire_invalid_credentials( + self, record: AccountRecord, exc: UpstreamError + ) -> bool: + from .invalid_credentials import mark_account_invalid_credentials + + return await mark_account_invalid_credentials( + self._repo, + record.token, + exc, + source="usage refresh", + ) + + # ------------------------------------------------------------------ + # Console 配额窗口自动重置(后台定时巡检) + # ------------------------------------------------------------------ + + async def reset_expired_console_windows(self) -> int: + """批量重置过期/卡死的 console 配额(委托给存储后端的 SQL 优化)。 + + Returns: + 重置的账号数量。 + """ + count = await self._repo.reset_expired_console_windows() + if count > 0: + logger.debug("console quota windows auto-reset: count={}", count) + return count + + async def recover_console_expired_accounts(self) -> int: + """自动恢复 console 429 EXPIRED 账号(满足条件)。 + + 恢复条件(AND): + - status = EXPIRED + - state_reason = console_429_threshold_exceeded + - usage_use_count > 5(有成功调用历史) + - expired_at <= now - 1 小时(等待时间够了) + + 恢复操作: + - status: EXPIRED → ACTIVE + - 清理 ext 中的 expired_at / expired_reason / console_429_count / console_429_last_at + + Returns: + 恢复的账号数量。 + """ + count = await self._repo.recover_console_expired_accounts() + if count > 0: + logger.info("console expired accounts auto-recovered: count={}", count) + return count + + +__all__ = ["AccountRefreshService", "RefreshResult"] diff --git a/app/control/account/repository.py b/app/control/account/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..80ba45de3cab1ce643a0b14844e50524fae604a0 --- /dev/null +++ b/app/control/account/repository.py @@ -0,0 +1,102 @@ +"""Account repository protocol — the contract every backend must satisfy.""" + +from typing import Protocol, runtime_checkable + +from .commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery +from .models import ( + AccountChangeSet, + AccountMutationResult, + AccountPage, + AccountRecord, + RuntimeSnapshot, +) + + +@runtime_checkable +class AccountRepository(Protocol): + """Storage contract shared by all account backends.""" + + async def initialize(self) -> None: + """Create schema / tables / indices if they do not exist.""" + ... + + async def get_revision(self) -> int: + """Return the current global revision counter.""" + ... + + async def runtime_snapshot(self) -> RuntimeSnapshot: + """Return all non-deleted accounts for hot-path bootstrap.""" + ... + + async def scan_changes( + self, + since_revision: int, + *, + limit: int = 5000, + ) -> AccountChangeSet: + """Return records modified after *since_revision* (inclusive).""" + ... + + async def upsert_accounts( + self, + items: list[AccountUpsert], + ) -> AccountMutationResult: + """Insert or replace accounts. Pushes revision.""" + ... + + async def patch_accounts( + self, + patches: list[AccountPatch], + ) -> AccountMutationResult: + """Apply partial updates to existing accounts. Pushes revision.""" + ... + + async def delete_accounts( + self, + tokens: list[str], + ) -> AccountMutationResult: + """Soft-delete accounts (set deleted_at). Pushes revision.""" + ... + + async def get_accounts( + self, + tokens: list[str], + ) -> list[AccountRecord]: + """Fetch accounts by token list.""" + ... + + async def list_accounts( + self, + query: ListAccountsQuery, + ) -> AccountPage: + """Return a paginated, filtered, sorted account list.""" + ... + + async def replace_pool( + self, + command: BulkReplacePoolCommand, + ) -> AccountMutationResult: + """Atomically replace all accounts in a pool.""" + ... + + async def reset_expired_console_windows(self) -> int: + """Batch-reset console quotas that are exhausted and expired. Pushes revision.""" + ... + + async def recover_console_expired_accounts(self) -> int: + """Auto-recover console 429 EXPIRED accounts with successful history. + + Recovery conditions (AND): + - status = EXPIRED + - state_reason = 'console_429_threshold_exceeded' + - usage_use_count > 5 + - ext.expired_at <= now - 1 hour + """ + ... + + async def close(self) -> None: + """Release database connections / file handles.""" + ... + + +__all__ = ["AccountRepository"] diff --git a/app/control/account/runtime.py b/app/control/account/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..fbf5f7f3acf1fc89f5178ae6befef03ca0bbbb8e --- /dev/null +++ b/app/control/account/runtime.py @@ -0,0 +1,102 @@ +"""Account runtime singletons and hot-apply helpers. + +These helpers expose the process-local account refresh runtime without making +callers import ``app.main``. Admin handlers use them to reconcile strategy and +scheduler state after hot config updates. +""" + +from typing import TYPE_CHECKING, Literal + +if TYPE_CHECKING: + from .refresh import AccountRefreshService + from .scheduler import AccountRefreshScheduler + +_refresh_service: "AccountRefreshService | None" = None +_refresh_scheduler: "AccountRefreshScheduler | None" = None +_refresh_scheduler_leader = False + + +def set_refresh_service(service: "AccountRefreshService | None") -> None: + """Register the process-global account refresh service.""" + global _refresh_service + _refresh_service = service + + +def get_refresh_service() -> "AccountRefreshService | None": + """Return the registered account refresh service, if any.""" + return _refresh_service + + +def set_refresh_scheduler(scheduler: "AccountRefreshScheduler | None") -> None: + """Register the process-global account refresh scheduler.""" + global _refresh_scheduler + _refresh_scheduler = scheduler + + +def get_refresh_scheduler() -> "AccountRefreshScheduler | None": + """Return the registered account refresh scheduler, if any.""" + return _refresh_scheduler + + +def set_refresh_scheduler_leader(is_leader: bool) -> None: + """Record whether this worker currently owns the refresh scheduler lock.""" + global _refresh_scheduler_leader + _refresh_scheduler_leader = bool(is_leader) + + +def is_refresh_scheduler_leader() -> bool: + """Return True when this worker is the active refresh-scheduler leader.""" + return _refresh_scheduler_leader + + +def reconcile_refresh_runtime( + enabled: bool | None = None, +) -> Literal["quota", "random"]: + """Hot-apply refresh strategy and scheduler state for the current worker.""" + from app.dataplane.account.selector import current_strategy, set_strategy + from app.platform.config.snapshot import config + from app.platform.logging.logger import logger + + refresh_enabled = ( + config.get_bool("account.refresh.enabled", False) + if enabled is None + else bool(enabled) + ) + target_strategy: Literal["quota", "random"] = ( + "quota" if refresh_enabled else "random" + ) + previous_strategy = current_strategy() + if previous_strategy != target_strategy: + set_strategy(target_strategy) + + scheduler_action = "unchanged" + scheduler = _refresh_scheduler + if scheduler is not None and _refresh_scheduler_leader: + if refresh_enabled: + if not scheduler.is_running(): + scheduler.start() + scheduler_action = "started" + elif scheduler.is_running(): + scheduler.stop() + scheduler_action = "stopped" + + if previous_strategy != target_strategy or scheduler_action != "unchanged": + logger.info( + "account refresh runtime reconciled: previous_strategy={} strategy={} leader={} scheduler_action={}", + previous_strategy, + target_strategy, + _refresh_scheduler_leader, + scheduler_action, + ) + return target_strategy + + +__all__ = [ + "get_refresh_service", + "set_refresh_service", + "get_refresh_scheduler", + "set_refresh_scheduler", + "is_refresh_scheduler_leader", + "set_refresh_scheduler_leader", + "reconcile_refresh_runtime", +] diff --git a/app/control/account/scheduler.py b/app/control/account/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..e141bb9870700b0c0252a17f4279957ab332e955 --- /dev/null +++ b/app/control/account/scheduler.py @@ -0,0 +1,121 @@ +"""Background scheduler for periodic account quota refresh. + +Runs one independent loop per pool type (basic / super / heavy), each with +its own configurable interval read from: + + account.refresh.basic_interval_sec (default 86400 — 24 h) + account.refresh.super_interval_sec (default 7200 — 2 h) + account.refresh.heavy_interval_sec (default 7200 — 2 h) +""" + +import asyncio + +from app.platform.config.snapshot import get_config +from app.platform.logging.logger import logger +from .refresh import AccountRefreshService + +# Pool → (config key, built-in default seconds) +_POOL_CONFIG: dict[str, tuple[str, int]] = { + "basic": ("account.refresh.basic_interval_sec", 86_400), + "super": ("account.refresh.super_interval_sec", 7_200), + "heavy": ("account.refresh.heavy_interval_sec", 7_200), +} + + +def _interval(pool: str) -> int: + key, default = _POOL_CONFIG[pool] + v = get_config(key, None) + return int(v) if v is not None else default + + +class AccountRefreshScheduler: + """Runs one refresh loop per pool type at pool-specific intervals. + + Lifecycle: ``start()`` → loops run in background → ``stop()`` to cancel. + """ + + def __init__(self, refresh_service: AccountRefreshService) -> None: + self._service = refresh_service + self._tasks: list[asyncio.Task] = [] + self._stop = asyncio.Event() + + def bind_service(self, refresh_service: AccountRefreshService) -> None: + """Update the refresh service used by the singleton scheduler.""" + self._service = refresh_service + + def is_running(self) -> bool: + """Return True while any pool refresh loop is still active.""" + return any(not task.done() for task in self._tasks) + + def start(self) -> None: + if self.is_running(): + return + self._stop.clear() + self._tasks = [ + asyncio.create_task(self._loop(pool), name=f"account-refresh-{pool}") + for pool in _POOL_CONFIG + ] + intervals = {p: _interval(p) for p in _POOL_CONFIG} + logger.info( + "account refresh scheduler started: basic_interval_s={} super_interval_s={} heavy_interval_s={}", + intervals["basic"], intervals["super"], intervals["heavy"], + ) + + def stop(self) -> None: + was_running = self.is_running() + self._stop.set() + for t in self._tasks: + if not t.done(): + t.cancel() + self._tasks = [] + if was_running: + logger.info("account refresh scheduler stopped") + + async def _loop(self, pool: str) -> None: + while not self._stop.is_set(): + interval = _interval(pool) + try: + await asyncio.wait_for(self._stop.wait(), timeout=float(interval)) + break # stop event fired + except asyncio.TimeoutError: + pass + + if self._stop.is_set(): + break + + try: + result = await self._service.refresh_scheduled(pool=pool) + logger.info( + "account refresh cycle completed: pool={} checked={} refreshed={} recovered={} failed={}", + pool, result.checked, result.refreshed, result.recovered, result.failed, + ) + except asyncio.CancelledError: + raise + except Exception as exc: + logger.error( + "account refresh cycle failed: pool={} error_type={} error={}", + pool, + type(exc).__name__, + exc, + ) + + +# --------------------------------------------------------------------------- +# Module-level singleton +# --------------------------------------------------------------------------- + +_scheduler: AccountRefreshScheduler | None = None + + +def get_account_refresh_scheduler( + refresh_service: AccountRefreshService, +) -> AccountRefreshScheduler: + global _scheduler + if _scheduler is None: + _scheduler = AccountRefreshScheduler(refresh_service) + else: + _scheduler.bind_service(refresh_service) + return _scheduler + + +__all__ = ["AccountRefreshScheduler", "get_account_refresh_scheduler"] diff --git a/app/control/account/state_machine.py b/app/control/account/state_machine.py new file mode 100644 index 0000000000000000000000000000000000000000..5e626edf3cbdfa5d52535732eba2ae42437215dc --- /dev/null +++ b/app/control/account/state_machine.py @@ -0,0 +1,333 @@ +"""Account lifecycle state machine. + +Applies feedback events to an AccountRecord, advancing its status +and updating quota / usage fields accordingly. +""" + +from dataclasses import dataclass, field + +from app.platform.runtime.clock import now_ms +from .enums import AccountStatus, FeedbackKind +from .models import AccountRecord, QuotaWindow +from .quota_defaults import default_quota_set + +# --------------------------------------------------------------------------- +# Policy +# --------------------------------------------------------------------------- + + +@dataclass(slots=True) +class StatePolicy: + """Configurable thresholds for automatic state transitions.""" + + fail_threshold: int = 5 # consecutive failures → COOLING + forbidden_strikes: int = 1 # 403 count → DISABLED + default_cooling_ms: int = 15 * 60 * 1000 # 15 min + + +_DEFAULT_POLICY = StatePolicy() + + +# --------------------------------------------------------------------------- +# Feedback +# --------------------------------------------------------------------------- + + +@dataclass(slots=True) +class AccountFeedback: + """Outcome of a single upstream request. + + ``mode_id`` — which quota window to update (0=auto, 1=fast, 2=expert). + ``quota_window`` — real quota window from the usage API (optional). + ``apply_usage`` — whether to increment usage_use_count on SUCCESS. + """ + + kind: FeedbackKind + mode_id: int = 0 + at: int = field(default_factory=now_ms) + status_code: int | None = None + reason: str = "" + quota_window: QuotaWindow | None = None # real value from usage API + retry_after_ms: int | None = None + confirm_expired: bool = False + apply_usage: bool = True + + @classmethod + def from_status_code( + cls, + status_code: int, + mode_id: int = 0, + *, + reason: str = "", + retry_after_ms: int | None = None, + confirm_expired: bool = False, + ) -> "AccountFeedback": + if status_code == 401: + kind = FeedbackKind.UNAUTHORIZED + elif status_code == 403: + kind = FeedbackKind.FORBIDDEN + elif status_code == 429: + kind = FeedbackKind.RATE_LIMITED + elif status_code >= 500: + kind = FeedbackKind.SERVER_ERROR + elif 200 <= status_code < 300: + kind = FeedbackKind.SUCCESS + else: + kind = FeedbackKind.SERVER_ERROR + return cls( + kind=kind, + mode_id=mode_id, + status_code=status_code, + reason=reason, + retry_after_ms=retry_after_ms, + confirm_expired=confirm_expired, + apply_usage=False, + ) + + +# --------------------------------------------------------------------------- +# State helpers +# --------------------------------------------------------------------------- + +_COOLDOWN_UNTIL_KEY = "cooldown_until" +_COOLDOWN_REASON_KEY = "cooldown_reason" +_DISABLED_AT_KEY = "disabled_at" +_DISABLED_REASON_KEY = "disabled_reason" +_EXPIRED_AT_KEY = "expired_at" +_EXPIRED_REASON_KEY = "expired_reason" +_FORBIDDEN_STRIKE_KEY = "forbidden_strikes" + + +def derive_status(record: AccountRecord, *, now: int | None = None) -> AccountStatus: + """Compute the effective status, considering cooldown expiry.""" + if record.status != AccountStatus.COOLING: + return record.status + cooldown_until = record.ext.get(_COOLDOWN_UNTIL_KEY) + if cooldown_until is None: + return AccountStatus.COOLING + ts = now if now is not None else now_ms() + if ts >= int(cooldown_until): + return AccountStatus.ACTIVE + return AccountStatus.COOLING + + +def is_selectable( + record: AccountRecord, mode_id: int, *, now: int | None = None +) -> bool: + """Return True if the account can be selected for *mode_id*.""" + if record.is_deleted(): + return False + status = derive_status(record, now=now) + if status != AccountStatus.ACTIVE: + return False + qs = record.quota_set() + win = qs.get(mode_id) + return win is not None and not win.is_exhausted() + + +def is_manageable(record: AccountRecord, *, now: int | None = None) -> bool: + """Return True if the account should participate in maintenance flows.""" + if record.is_deleted(): + return False + status = derive_status(record, now=now) + return status in (AccountStatus.ACTIVE, AccountStatus.COOLING) + + +# --------------------------------------------------------------------------- +# State transition +# --------------------------------------------------------------------------- + + +def apply_feedback( + record: AccountRecord, + feedback: AccountFeedback, + *, + policy: StatePolicy = _DEFAULT_POLICY, +) -> AccountRecord: + """Apply *feedback* to *record* and return an updated copy. + + The returned object is a **new** record; the original is not mutated. + """ + ts = feedback.at + ext = dict(record.ext) + qs = record.quota_set() + + status = record.status + last_fail_at = record.last_fail_at + last_fail_reason = record.last_fail_reason + last_use_at = record.last_use_at + last_sync_at = record.last_sync_at + use_count = record.usage_use_count + fail_count = record.usage_fail_count + sync_count = record.usage_sync_count + state_reason = record.state_reason + + # Update quota window from real API data if provided. + if feedback.quota_window is not None: + qs.set(feedback.mode_id, feedback.quota_window) + last_sync_at = ts + sync_count += 1 + elif feedback.kind == FeedbackKind.SUCCESS: + # Decrement locally when no real data is available. + win = qs.get(feedback.mode_id) + if win is not None: + updated_win = QuotaWindow( + remaining=max(0, win.remaining - 1), + total=win.total, + window_seconds=win.window_seconds, + reset_at=win.reset_at, + synced_at=win.synced_at, + source=win.source, + ) + qs.set(feedback.mode_id, updated_win) + elif feedback.kind == FeedbackKind.RATE_LIMITED: + # Mark quota as zero; set reset_at from retry_after if available. + win = qs.get(feedback.mode_id) + if win is not None: + reset_at = ( + ts + feedback.retry_after_ms + if feedback.retry_after_ms + else (ts + win.window_seconds * 1000) + ) + qs.set( + feedback.mode_id, + QuotaWindow( + remaining=0, + total=win.total, + window_seconds=win.window_seconds, + reset_at=reset_at, + synced_at=win.synced_at, + source=win.source, + ), + ) + + # Update usage counters. + if feedback.kind == FeedbackKind.SUCCESS and feedback.apply_usage: + use_count += 1 + last_use_at = ts + elif feedback.kind not in ( + FeedbackKind.SUCCESS, + FeedbackKind.RESTORE, + FeedbackKind.DISABLE, + FeedbackKind.DELETE, + ): + fail_count += 1 + last_fail_at = ts + last_fail_reason = feedback.reason or str(feedback.status_code or "") + + # Status transitions. + if feedback.kind == FeedbackKind.UNAUTHORIZED: + if feedback.confirm_expired: + status = AccountStatus.EXPIRED + state_reason = feedback.reason or "token_expired" + ext[_EXPIRED_AT_KEY] = ts + ext[_EXPIRED_REASON_KEY] = state_reason + else: + # Unconfirmed 401 — only note failure; do not expire. + pass + + elif feedback.kind == FeedbackKind.FORBIDDEN: + strikes = int(ext.get(_FORBIDDEN_STRIKE_KEY, 0)) + 1 + ext[_FORBIDDEN_STRIKE_KEY] = strikes + if strikes >= policy.forbidden_strikes: + status = AccountStatus.DISABLED + state_reason = feedback.reason or "forbidden" + ext[_DISABLED_AT_KEY] = ts + ext[_DISABLED_REASON_KEY] = state_reason + + elif feedback.kind == FeedbackKind.RATE_LIMITED: + cooldown_ms = ( + feedback.retry_after_ms + if feedback.retry_after_ms + else policy.default_cooling_ms + ) + status = AccountStatus.COOLING + state_reason = feedback.reason or "rate_limited" + ext[_COOLDOWN_UNTIL_KEY] = ts + cooldown_ms + ext[_COOLDOWN_REASON_KEY] = state_reason + + elif feedback.kind == FeedbackKind.SUCCESS: + if status == AccountStatus.COOLING: + cooldown_until = ext.get(_COOLDOWN_UNTIL_KEY) + if cooldown_until is not None and ts >= int(cooldown_until): + status = AccountStatus.ACTIVE + state_reason = None + ext.pop(_COOLDOWN_UNTIL_KEY, None) + ext.pop(_COOLDOWN_REASON_KEY, None) + ext.pop(_FORBIDDEN_STRIKE_KEY, None) + + elif feedback.kind == FeedbackKind.DISABLE: + status = AccountStatus.DISABLED + state_reason = feedback.reason or "operator_disabled" + ext[_DISABLED_AT_KEY] = ts + ext[_DISABLED_REASON_KEY] = state_reason + + elif feedback.kind == FeedbackKind.DELETE: + pass # Caller sets deleted_at. + + elif feedback.kind == FeedbackKind.RESTORE: + status = AccountStatus.ACTIVE + state_reason = None + ext.pop(_COOLDOWN_UNTIL_KEY, None) + ext.pop(_COOLDOWN_REASON_KEY, None) + ext.pop(_DISABLED_AT_KEY, None) + ext.pop(_DISABLED_REASON_KEY, None) + ext.pop(_EXPIRED_AT_KEY, None) + ext.pop(_EXPIRED_REASON_KEY, None) + ext.pop(_FORBIDDEN_STRIKE_KEY, None) + # Reset quota to defaults. + qs = default_quota_set(record.pool) + + return record.model_copy( + update={ + "status": status, + "quota": qs.to_dict(), + "usage_use_count": use_count, + "usage_fail_count": fail_count, + "usage_sync_count": sync_count, + "last_use_at": last_use_at, + "last_fail_at": last_fail_at, + "last_fail_reason": last_fail_reason, + "last_sync_at": last_sync_at, + "state_reason": state_reason, + "ext": ext, + "updated_at": ts, + } + ) + + +def clear_failures(record: AccountRecord) -> AccountRecord: + """Reset failure counters and restore ACTIVE status.""" + ext = dict(record.ext) + for k in ( + _COOLDOWN_UNTIL_KEY, + _COOLDOWN_REASON_KEY, + _DISABLED_AT_KEY, + _DISABLED_REASON_KEY, + _EXPIRED_AT_KEY, + _EXPIRED_REASON_KEY, + _FORBIDDEN_STRIKE_KEY, + ): + ext.pop(k, None) + return record.model_copy( + update={ + "status": AccountStatus.ACTIVE, + "usage_fail_count": 0, + "last_fail_at": None, + "last_fail_reason": None, + "state_reason": None, + "ext": ext, + "updated_at": now_ms(), + } + ) + + +__all__ = [ + "StatePolicy", + "AccountFeedback", + "derive_status", + "is_selectable", + "is_manageable", + "apply_feedback", + "clear_failures", +] diff --git a/app/control/admin/__init__.py b/app/control/admin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/control/model/__init__.py b/app/control/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/control/model/enums.py b/app/control/model/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..b27aad70b6a9666f56f8fa73bbb0a4115aba70b0 --- /dev/null +++ b/app/control/model/enums.py @@ -0,0 +1,77 @@ +"""Control-plane model enumerations.""" + +from enum import IntEnum, IntFlag + + +class ModeId(IntEnum): + """Upstream ``modeId`` parameter values. + + Integer values are stable — used as array indices in the hot path. + """ + + AUTO = 0 # modeId="auto" + FAST = 1 # modeId="fast" + EXPERT = 2 # modeId="expert" + HEAVY = 3 # modeId="heavy" — only available on heavy-pool accounts + GROK_4_3 = 4 # modeId="grok-420-computer-use-sa" — super/heavy only + CONSOLE = 5 # console.x.ai 独立配额 — basic pool console 模型专用 + + def to_api_str(self) -> str: + _OVERRIDES: dict[int, str] = { + ModeId.GROK_4_3: "grok-420-computer-use-sa", + } + return _OVERRIDES.get(self, self.name.lower()) # type: ignore[arg-type] + + +class Tier(IntEnum): + """Account tier — determines which pool is selected.""" + + BASIC = 0 # pool="basic" + SUPER = 1 # pool="super" + HEAVY = 2 # pool="heavy" + + +class Capability(IntFlag): + """Bitmask of features a model supports.""" + + CHAT = 1 + IMAGE = 2 + IMAGE_EDIT = 4 + VIDEO = 8 + VOICE = 16 + ASSET = 32 + CONSOLE_CHAT = 64 # 通过 console.x.ai/v1/responses 路由 + + +# Human-readable mode strings in API order. +MODE_STRINGS: dict[ModeId, str] = { + ModeId.AUTO: "auto", + ModeId.FAST: "fast", + ModeId.EXPERT: "expert", + ModeId.HEAVY: "heavy", +} + +ALL_MODES: tuple[ModeId, ...] = (ModeId.AUTO, ModeId.FAST, ModeId.EXPERT) +ALL_MODES_WITH_HEAVY: tuple[ModeId, ...] = ( + ModeId.AUTO, + ModeId.FAST, + ModeId.EXPERT, + ModeId.HEAVY, +) +ALL_MODES_FULL: tuple[ModeId, ...] = ( + ModeId.AUTO, + ModeId.FAST, + ModeId.EXPERT, + ModeId.HEAVY, + ModeId.GROK_4_3, +) + +__all__ = [ + "ModeId", + "Tier", + "Capability", + "MODE_STRINGS", + "ALL_MODES", + "ALL_MODES_WITH_HEAVY", + "ALL_MODES_FULL", +] diff --git a/app/control/model/registry.py b/app/control/model/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..a96ff19aeabb778f0d79e9f162d7fac4c863a1ce --- /dev/null +++ b/app/control/model/registry.py @@ -0,0 +1,116 @@ +"""Model registry — all supported model variants defined in one place.""" + +from .enums import Capability, ModeId, Tier +from .spec import ModelSpec + +# --------------------------------------------------------------------------- +# Master model list. +# Add new models here; no other files need to change. +# --------------------------------------------------------------------------- + +# fmt: off +MODELS: tuple[ModelSpec, ...] = ( + # === Chat ============================================================== + + # Basic fast; auto/expert require Super+ + ModelSpec("grok-4.20-0309-non-reasoning", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4.20 0309 Non-Reasoning"), + ModelSpec("grok-4.20-0309", ModeId.AUTO, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309"), + ModelSpec("grok-4.20-0309-reasoning", ModeId.EXPERT, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309 Reasoning"), + # Super+ + ModelSpec("grok-4.20-0309-non-reasoning-super", ModeId.FAST, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309 Non-Reasoning Super"), + ModelSpec("grok-4.20-0309-super", ModeId.AUTO, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309 Super"), + ModelSpec("grok-4.20-0309-reasoning-super", ModeId.EXPERT, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309 Reasoning Super"), + # Heavy+ + ModelSpec("grok-4.20-0309-non-reasoning-heavy", ModeId.FAST, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 0309 Non-Reasoning Heavy"), + ModelSpec("grok-4.20-0309-heavy", ModeId.AUTO, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 0309 Heavy"), + ModelSpec("grok-4.20-0309-reasoning-heavy", ModeId.EXPERT, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 0309 Reasoning Heavy"), + ModelSpec("grok-4.20-multi-agent-0309", ModeId.HEAVY, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 Multi-Agent 0309"), + + # --- 硬优先级反向选池 (heavy → super → basic) --- + ModelSpec("grok-4.20-fast", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4.20 Fast", prefer_best=True), + ModelSpec("grok-4.3-fast", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4.3 Fast", prefer_best=True), + ModelSpec("grok-4.20-auto", ModeId.AUTO, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 Auto", prefer_best=True), + ModelSpec("grok-4.20-expert", ModeId.EXPERT, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 Expert", prefer_best=True), + ModelSpec("grok-4.20-heavy", ModeId.HEAVY, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 Heavy", prefer_best=True), + + # === grok-4.3 (grok-420-computer-use-sa) ================================== + # Super+(basic 池不支持此模式) + ModelSpec("grok-4.3-beta", ModeId.GROK_4_3, Tier.SUPER, Capability.CHAT, True, "Grok 4.3 Beta"), + + # === Image ============================================================== + + # Basic fast + ModelSpec("grok-imagine-image-lite", ModeId.FAST, Tier.BASIC, Capability.IMAGE, True, "Grok Imagine Image Lite"), + # Super+ + ModelSpec("grok-imagine-image", ModeId.AUTO, Tier.SUPER, Capability.IMAGE, True, "Grok Imagine Image"), + ModelSpec("grok-imagine-image-pro", ModeId.AUTO, Tier.SUPER, Capability.IMAGE, True, "Grok Imagine Image Pro"), + + # === Image Edit ========================================================= + + # Super+ + ModelSpec("grok-imagine-image-edit", ModeId.AUTO, Tier.SUPER, Capability.IMAGE_EDIT, True, "Grok Imagine Image Edit"), + + # === Video ============================================================== + + # Super+ + ModelSpec("grok-imagine-video", ModeId.AUTO, Tier.SUPER, Capability.VIDEO, True, "Grok Imagine Video"), + + # === Console Chat (console.x.ai/v1/responses) =========================== + # 通过 console.x.ai 路由,使用 grok.com SSO token,免费账号可用 + # basic pool 即可(不消耗 grok.com 配额,走 console API 独立配额) + ModelSpec("grok-4.3-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.3 (Console)"), + ModelSpec("grok-4.3-low", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.3 Low Thinking"), + ModelSpec("grok-4.3-medium", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.3 Medium Thinking"), + ModelSpec("grok-4.3-high", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.3 High Thinking"), + ModelSpec("grok-4.20-0309-reasoning-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 0309 Reasoning (Console)"), + ModelSpec("grok-4.20-0309-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 0309 (Console)"), + ModelSpec("grok-4.20-multi-agent-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent (Console)"), + ModelSpec("grok-4.20-multi-agent-low", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent Low"), + ModelSpec("grok-4.20-multi-agent-medium", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent Medium"), + ModelSpec("grok-4.20-multi-agent-high", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent High"), + ModelSpec("grok-4.20-multi-agent-xhigh", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent XHigh"), + ModelSpec("grok-4.20-0309-non-reasoning-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 0309 Non-Reasoning (Console)"), + ModelSpec("grok-build-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok Build 0.1 (Console)"), +) +# fmt: on + +# --------------------------------------------------------------------------- +# Internal lookup structures — built once at import time. +# --------------------------------------------------------------------------- + +_BY_NAME: dict[str, ModelSpec] = {m.model_name: m for m in MODELS} + +_BY_CAP: dict[int, list[ModelSpec]] = {} +for _m in MODELS: + _BY_CAP.setdefault(int(_m.capability), []).append(_m) + + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- + + +def get(model_name: str) -> ModelSpec | None: + """Return the spec for *model_name*, or ``None`` if not registered.""" + return _BY_NAME.get(model_name) + + +def resolve(model_name: str) -> ModelSpec: + """Return the spec for *model_name*; raise ``ValueError`` if unknown.""" + spec = _BY_NAME.get(model_name) + if spec is None: + raise ValueError(f"Unknown model: {model_name!r}") + return spec + + +def list_enabled() -> list[ModelSpec]: + """Return all enabled models in registration order.""" + return [m for m in MODELS if m.enabled] + + +def list_by_capability(cap: Capability) -> list[ModelSpec]: + """Return enabled models that include *cap* in their capability mask.""" + return [m for m in MODELS if m.enabled and bool(m.capability & cap)] + + +__all__ = ["MODELS", "get", "resolve", "list_enabled", "list_by_capability"] diff --git a/app/control/model/spec.py b/app/control/model/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0c797e292257917d45a5732eed4dd8a5eb3fdf --- /dev/null +++ b/app/control/model/spec.py @@ -0,0 +1,98 @@ +"""ModelSpec — the single source of truth for model metadata.""" + +from dataclasses import dataclass + +from .enums import Capability, ModeId, Tier + + +@dataclass(slots=True, frozen=True) +class ModelSpec: + """Immutable descriptor for one model variant. + + ``model_name`` is the public-facing identifier used in API requests. + ``mode_id`` is the upstream ``modeId`` value (auto / fast / expert). + ``tier`` determines which account pool is used (basic / super). + When ``prefer_best`` is True, ``tier`` only affects + ``pool_name()``/``pool_id()``; the actual selection order + is reversed (heavy → super → basic). + ``capability`` is a bitmask of supported operations. + ``enabled`` gates whether the model appears in ``/v1/models``. + ``public_name`` is the human-readable display name. + ``prefer_best`` when True, reverses pool priority to try higher-tier + pools first (hard priority, not soft preference). + """ + + model_name: str + mode_id: ModeId + tier: Tier + capability: Capability + enabled: bool + public_name: str + prefer_best: bool = False + + # --- convenience predicates --- + + def is_chat(self) -> bool: + return bool(self.capability & Capability.CHAT) + + def is_image(self) -> bool: + return bool(self.capability & Capability.IMAGE) + + def is_image_edit(self) -> bool: + return bool(self.capability & Capability.IMAGE_EDIT) + + def is_video(self) -> bool: + return bool(self.capability & Capability.VIDEO) + + def is_voice(self) -> bool: + return bool(self.capability & Capability.VOICE) + + def is_console_chat(self) -> bool: + """通过 console.x.ai/v1/responses 路由的模型。""" + return bool(self.capability & Capability.CONSOLE_CHAT) + + def pool_name(self) -> str: + """Return the canonical pool string for this tier.""" + if self.tier == Tier.SUPER: + return "super" + if self.tier == Tier.HEAVY: + return "heavy" + return "basic" + + def pool_id(self) -> int: + """Return the integer PoolId for the dataplane account table.""" + return int(self.tier) + + # 返回按优先级排序的候选池 ID + def pool_candidates(self) -> tuple[int, ...]: + """Return pool IDs to try in priority order. + + When ``prefer_best`` is True the order is reversed so that the + highest-tier pool is attempted first (hard priority — the first + pool with any available account wins; lower pools are only reached + when all accounts in higher pools are exhausted). + + Default (prefer_best=False): + BASIC tier → try basic first, then super, then heavy + SUPER tier → try super first, then heavy + HEAVY tier → heavy only + + Reversed (prefer_best=True): + BASIC tier → try heavy first, then super, then basic + SUPER tier → try heavy first, then super + HEAVY tier → heavy only + """ + if self.prefer_best: + if self.tier == Tier.HEAVY: + return (2,) # heavy only + if self.tier == Tier.SUPER: + return (2, 1) # heavy, super + return (2, 1, 0) # heavy, super, basic + if self.tier == Tier.BASIC: + return (0, 1, 2) # basic, super, heavy + if self.tier == Tier.SUPER: + return (1, 2) # super, heavy + return (2,) # heavy only + + +__all__ = ["ModelSpec"] diff --git a/app/control/proxy/__init__.py b/app/control/proxy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d7581d60bf7c0586509f3d798d6479ea1af7f9e --- /dev/null +++ b/app/control/proxy/__init__.py @@ -0,0 +1,431 @@ +"""ProxyDirectory — control-plane proxy pool coordinator. + +Maintains the list of EgressNodes and ClearanceBundles. +Selection delegates to the dataplane ProxyTable; this module owns +configuration loading and clearance refresh lifecycle. +""" + +import asyncio +from urllib.parse import urlparse + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.runtime.clock import now_ms +from app.platform.runtime.ids import next_hex +from .config import resolve_clearance_config +from .models import ( + EgressMode, + ClearanceMode, + EgressNode, + ClearanceBundle, + ProxyLease, + ProxyFeedback, + ProxyFeedbackKind, + RequestKind, + ProxyScope, +) +from .providers.manual import ManualClearanceProvider +from .providers.flaresolverr import FlareSolverrClearanceProvider + +_DEFAULT_CLEARANCE_ORIGIN = "https://grok.com" +BundleKey = tuple[str, str] + + +def _clearance_host(clearance_origin: str | None) -> str: + host = urlparse(clearance_origin or _DEFAULT_CLEARANCE_ORIGIN).hostname + return (host or "grok.com").lower() + + +class ProxyDirectory: + """Owns egress nodes and clearance bundles. + + Thread-safety: all mutations are protected by ``_lock``. + """ + + def __init__(self) -> None: + self._nodes: list[EgressNode] = [] + self._resource_nodes: list[EgressNode] = [] # for media downloads + self._bundles: dict[BundleKey, ClearanceBundle] = {} + self._lock = asyncio.Lock() + # Single-flight guard: at most one FlareSolverr call per proxy+host key. + # Other coroutines wait on the Event until the active refresh completes. + self._refresh_events: dict[BundleKey, asyncio.Event] = {} + self._manual = ManualClearanceProvider() + self._flare = FlareSolverrClearanceProvider() + self._egress_mode: EgressMode = EgressMode.DIRECT + self._clearance_mode: ClearanceMode = ClearanceMode.NONE + self._config_sig: tuple | None = None + # Pool cursor for PROXY_POOL mode: sticky routing with failure-driven rotate. + # Incremented on node failure; all callers see the same cursor under _lock. + self._pool_cursor: int = 0 + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + async def load(self) -> None: + """Load proxy configuration from the current config snapshot.""" + cfg = get_config() + egress_mode = EgressMode(cfg.get_str("proxy.egress.mode", "direct")) + clearance_mode = ClearanceMode.parse( + cfg.get_str("proxy.clearance.mode", "none") + ) + base_url = cfg.get_str("proxy.egress.proxy_url", "") + res_url = cfg.get_str("proxy.egress.resource_proxy_url", "") + base_pool = tuple(cfg.get_list("proxy.egress.proxy_pool", [])) + res_pool = tuple(cfg.get_list("proxy.egress.resource_proxy_pool", [])) + clearance = resolve_clearance_config(cfg) + config_sig = ( + egress_mode.value, + clearance_mode.value, + base_url, + res_url, + base_pool, + res_pool, + cfg.get_str("proxy.clearance.flaresolverr_url", ""), + clearance.cf_cookies, + clearance.user_agent, + clearance.cf_clearance, + clearance.browser, + cfg.get_int("proxy.clearance.timeout_sec", 60), + ) + + nodes: list[EgressNode] = [] + resource_nodes: list[EgressNode] = [] + + if egress_mode == EgressMode.SINGLE_PROXY: + if base_url: + nodes.append(EgressNode(node_id="single", proxy_url=base_url)) + if res_url: + resource_nodes.append( + EgressNode(node_id="res-single", proxy_url=res_url) + ) + + elif egress_mode == EgressMode.PROXY_POOL: + for i, url in enumerate(base_pool): + nodes.append(EgressNode(node_id=f"pool-{i}", proxy_url=url)) + for i, url in enumerate(res_pool): + resource_nodes.append( + EgressNode(node_id=f"res-pool-{i}", proxy_url=url) + ) + + valid_affinities = {n.proxy_url or "direct" for n in [*nodes, *resource_nodes]} + if not valid_affinities: + valid_affinities = {"direct"} + + async with self._lock: + if self._config_sig == config_sig: + return + from .models import ClearanceBundleState + + self._egress_mode = egress_mode + self._clearance_mode = clearance_mode + self._nodes = nodes + self._resource_nodes = resource_nodes + self._pool_cursor = 0 + self._bundles = { + key: bundle.model_copy(update={"state": ClearanceBundleState.INVALID}) + for key, bundle in self._bundles.items() + if key[0] in valid_affinities + } + self._refresh_events = { + key: event + for key, event in self._refresh_events.items() + if key[0] in valid_affinities + } + self._config_sig = config_sig + + logger.info( + "proxy directory loaded: egress_mode={} clearance_mode={} node_count={} resource_node_count={}", + egress_mode, + clearance_mode, + len(nodes), + len(resource_nodes), + ) + + # ------------------------------------------------------------------ + # Acquisition + # ------------------------------------------------------------------ + + async def acquire( + self, + *, + scope: ProxyScope = ProxyScope.APP, + kind: RequestKind = RequestKind.HTTP, + resource: bool = False, + clearance_origin: str | None = None, + ) -> ProxyLease: + """Return a ProxyLease for the next request. + + For DIRECT mode, returns a lease with no proxy or clearance. + """ + proxy_url = await self._pick_proxy_url(resource=resource) + affinity = proxy_url or "direct" + clearance_host = _clearance_host(clearance_origin) + + bundle = await self._get_or_build_bundle( + affinity_key=affinity, + proxy_url=proxy_url or "", + clearance_origin=clearance_origin or _DEFAULT_CLEARANCE_ORIGIN, + ) + + return ProxyLease( + lease_id=next_hex(), + proxy_url=proxy_url, + cf_cookies=bundle.cf_cookies if bundle else "", + user_agent=bundle.user_agent if bundle else "", + clearance_host=clearance_host, + scope=scope, + kind=kind, + acquired_at=now_ms(), + ) + + async def feedback(self, lease: ProxyLease, result: ProxyFeedback) -> None: + """Apply upstream feedback to the appropriate egress node.""" + if result.kind in ( + ProxyFeedbackKind.CHALLENGE, + ProxyFeedbackKind.UNAUTHORIZED, + ): + # Invalidate associated clearance bundle. + key = (lease.proxy_url or "direct", lease.clearance_host) + async with self._lock: + from .models import ClearanceBundleState + + bundle = self._bundles.get(key) + if bundle: + self._bundles[key] = bundle.model_copy( + update={"state": ClearanceBundleState.INVALID} + ) + + # In PROXY_POOL mode, rotate to the next node on any failure so the + # next acquire() prefers a different egress rather than hammering the + # same broken node. + if ( + self._egress_mode == EgressMode.PROXY_POOL + and lease.proxy_url + and result.kind + in ( + ProxyFeedbackKind.CHALLENGE, + ProxyFeedbackKind.UNAUTHORIZED, + ProxyFeedbackKind.FORBIDDEN, + ProxyFeedbackKind.TRANSPORT_ERROR, + ) + ): + async with self._lock: + self._pool_cursor += 1 + logger.debug( + "proxy pool cursor advanced: proxy={} kind={} cursor={}", + lease.proxy_url, + result.kind, + self._pool_cursor, + ) + + # ------------------------------------------------------------------ + # Internal + # ------------------------------------------------------------------ + + async def _pick_proxy_url(self, resource: bool = False) -> str | None: + if self._egress_mode == EgressMode.DIRECT: + return None + async with self._lock: + # Prefer resource-specific nodes when available; fall back to base nodes. + nodes = ( + self._resource_nodes + if resource and self._resource_nodes + else self._nodes + ) + if not nodes: + return None + if self._egress_mode == EgressMode.SINGLE_PROXY: + return nodes[0].proxy_url + # PROXY_POOL: sticky routing — use current cursor, rotate on failure. + idx = self._pool_cursor % len(nodes) + return nodes[idx].proxy_url + + async def _get_or_build_bundle( + self, + *, + affinity_key: str, + proxy_url: str, + clearance_origin: str, + ) -> ClearanceBundle | None: + if self._clearance_mode == ClearanceMode.NONE: + return None + clearance_host = _clearance_host(clearance_origin) + key: BundleKey = (affinity_key, clearance_host) + + # Single-flight: only one coroutine fetches clearance per proxy+host key. + # Concurrent callers wait on the Event and retry once it fires. + while True: + async with self._lock: + bundle = self._bundles.get(key) + if bundle and bundle.state.value == 0: # VALID + return bundle + event = self._refresh_events.get(key) + if event is None: + # This coroutine wins the right to refresh. + event = asyncio.Event() + self._refresh_events[key] = event + break + # Another coroutine is already refreshing — wait for it, then retry. + await event.wait() + + try: + if self._clearance_mode == ClearanceMode.MANUAL: + bundle = self._manual.build_bundle( + affinity_key=affinity_key, + clearance_host=clearance_host, + ) + else: + bundle = await self._flare.refresh_bundle( + affinity_key=affinity_key, + proxy_url=proxy_url, + target_url=clearance_origin, + ) + if bundle: + async with self._lock: + self._bundles[key] = bundle + return bundle + finally: + async with self._lock: + self._refresh_events.pop(key, None) + event.set() # Wake all waiters so they retry with the new bundle. + + # ------------------------------------------------------------------ + # Clearance lifecycle helpers (used by ProxyClearanceScheduler) + # ------------------------------------------------------------------ + + async def invalidate_clearance(self) -> None: + """Mark all cached clearance bundles as invalid. + + The next ``acquire()`` call for each affinity key will trigger a fresh + FlareSolverr fetch (serialised by the single-flight guard). + """ + from .models import ClearanceBundleState + + async with self._lock: + self._bundles = { + k: b.model_copy(update={"state": ClearanceBundleState.INVALID}) + for k, b in self._bundles.items() + } + logger.debug("clearance bundles invalidated: count={}", len(self._bundles)) + + async def warm_up(self) -> None: + """Pre-fetch clearance bundles for all configured affinity keys. + + Called once at startup so the first real request does not have to wait + for FlareSolverr. Does NOT invalidate existing bundles first. + """ + if self._clearance_mode == ClearanceMode.NONE: + return + async with self._lock: + nodes = list(self._nodes) + affinity_keys = ( + [(n.proxy_url or "direct", n.proxy_url or "") for n in nodes] + if nodes + else [("direct", "")] + ) + for affinity, proxy_url in affinity_keys: + await self._get_or_build_bundle( + affinity_key=affinity, + proxy_url=proxy_url, + clearance_origin=_DEFAULT_CLEARANCE_ORIGIN, + ) + + async def refresh_clearance_safe(self) -> None: + """Scheduled clearance refresh: build new bundles then swap atomically. + + Unlike ``invalidate_clearance() + warm_up()``, this never discards a + working bundle before a replacement is ready. If FlareSolverr is + temporarily unavailable the old bundle remains valid and continues to + serve requests. + """ + if self._clearance_mode == ClearanceMode.NONE: + return + async with self._lock: + nodes = list(self._nodes) + existing = list(self._bundles.keys()) + + refresh_targets: dict[BundleKey, tuple[str, str]] = {} + default_items = ( + [(n.proxy_url or "direct", n.proxy_url or "") for n in nodes] + if nodes + else [("direct", "")] + ) + for affinity, proxy_url in default_items: + key: BundleKey = (affinity, _clearance_host(_DEFAULT_CLEARANCE_ORIGIN)) + refresh_targets[key] = (proxy_url, _DEFAULT_CLEARANCE_ORIGIN) + for key in existing: + affinity, clearance_host = key + refresh_targets.setdefault( + key, + ("" if affinity == "direct" else affinity, f"https://{clearance_host}"), + ) + + for key, (proxy_url, clearance_origin) in refresh_targets.items(): + affinity, clearance_host = key + if self._clearance_mode == ClearanceMode.MANUAL: + new_bundle = self._manual.build_bundle( + affinity_key=affinity, + clearance_host=clearance_host, + ) + else: + new_bundle = await self._flare.refresh_bundle( + affinity_key=affinity, + proxy_url=proxy_url, + target_url=clearance_origin, + ) + if new_bundle: + async with self._lock: + self._bundles[key] = new_bundle + logger.debug("clearance bundle refreshed: bundle={}", key) + else: + logger.warning( + "clearance refresh failed, keeping old bundle: bundle={}", + key, + ) + + # ------------------------------------------------------------------ + # Properties + # ------------------------------------------------------------------ + + @property + def egress_mode(self) -> EgressMode: + return self._egress_mode + + @property + def clearance_mode(self) -> ClearanceMode: + return self._clearance_mode + + @property + def node_count(self) -> int: + return len(self._nodes) + + @property + def nodes(self) -> list[EgressNode]: + """Read-only snapshot of the current egress node list.""" + return list(self._nodes) + + @property + def bundles(self) -> dict[BundleKey, ClearanceBundle]: + """Read-only snapshot of the current clearance bundles.""" + return dict(self._bundles) + + +# --------------------------------------------------------------------------- +# Module-level singleton +# --------------------------------------------------------------------------- + +_directory: ProxyDirectory | None = None + + +async def get_proxy_directory() -> ProxyDirectory: + """Return the module-level ProxyDirectory, reloading config if it changed.""" + global _directory + if _directory is None: + _directory = ProxyDirectory() + await _directory.load() + return _directory + + +__all__ = ["ProxyDirectory", "get_proxy_directory"] diff --git a/app/control/proxy/config.py b/app/control/proxy/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a62ee2ada6c2f6191b2e7381f30bb762859df1f8 --- /dev/null +++ b/app/control/proxy/config.py @@ -0,0 +1,56 @@ +"""Proxy clearance config helpers shared by control and dataplane code.""" + +from dataclasses import dataclass +from typing import Any + +from app.platform.config.snapshot import get_config + + +@dataclass(frozen=True) +class ClearanceConfig: + cf_cookies: str = "" + user_agent: str = "" + cf_clearance: str = "" + browser: str = "" + + +def _cfg_str(cfg: Any, key: str) -> str: + value = cfg.get_str(key, "") + return value if value.strip() else "" + + +def first_config_str(cfg: Any, *keys: str) -> str: + for key in keys: + value = _cfg_str(cfg, key) + if value: + return value + return "" + + +def resolve_clearance_config(cfg: Any | None = None) -> ClearanceConfig: + cfg = cfg or get_config() + return ClearanceConfig( + cf_cookies=first_config_str( + cfg, + "proxy.cf_cookies", + "proxy.clearance.cf_cookies", + ), + user_agent=first_config_str( + cfg, + "proxy.user_agent", + "proxy.clearance.user_agent", + ), + cf_clearance=first_config_str( + cfg, + "proxy.cf_clearance", + "proxy.clearance.cf_clearance", + ), + browser=first_config_str( + cfg, + "proxy.browser", + "proxy.clearance.browser", + ), + ) + + +__all__ = ["ClearanceConfig", "first_config_str", "resolve_clearance_config"] diff --git a/app/control/proxy/feedback.py b/app/control/proxy/feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..c58ff1ca4d3911127b2d2de36f1b4587f9604d1d --- /dev/null +++ b/app/control/proxy/feedback.py @@ -0,0 +1,39 @@ +"""Classify upstream HTTP responses into proxy feedback categories.""" + +from .models import ProxyFeedback, ProxyFeedbackKind + + +def classify_status_code(status_code: int) -> ProxyFeedbackKind: + if status_code == 200: + return ProxyFeedbackKind.SUCCESS + if status_code == 401: + return ProxyFeedbackKind.UNAUTHORIZED + if status_code == 403: + return ProxyFeedbackKind.CHALLENGE + if status_code == 429: + return ProxyFeedbackKind.RATE_LIMITED + if status_code >= 500: + return ProxyFeedbackKind.UPSTREAM_5XX + return ProxyFeedbackKind.FORBIDDEN + + +def build_feedback( + status_code: int, + *, + is_cloudflare: bool = False, + reason: str = "", + retry_after_ms: int | None = None, +) -> ProxyFeedback: + """Build a ``ProxyFeedback`` from an HTTP response status code.""" + kind = classify_status_code(status_code) + if is_cloudflare and status_code == 403: + kind = ProxyFeedbackKind.CHALLENGE + return ProxyFeedback( + kind = kind, + status_code = status_code, + reason = reason, + retry_after_ms = retry_after_ms, + ) + + +__all__ = ["classify_status_code", "build_feedback"] diff --git a/app/control/proxy/models.py b/app/control/proxy/models.py new file mode 100644 index 0000000000000000000000000000000000000000..8edde22ccc5db007eae4b110b719aa1cddc5faad --- /dev/null +++ b/app/control/proxy/models.py @@ -0,0 +1,109 @@ +"""Control-plane proxy domain models.""" + +from enum import IntEnum, StrEnum +from typing import Self + +from pydantic import BaseModel + + +class ProxyScope(StrEnum): + APP = "app" # grok.com API calls + ASSET = "asset" # static asset / CDN fetches + + +class RequestKind(StrEnum): + HTTP = "http" + WEBSOCKET = "websocket" + GRPC = "grpc" + + +class EgressMode(StrEnum): + DIRECT = "direct" # no proxy + SINGLE_PROXY = "single_proxy" # one fixed proxy URL + PROXY_POOL = "proxy_pool" # rotate from a pool + + +class ClearanceMode(StrEnum): + NONE = "none" # no CF clearance required + MANUAL = "manual" # operator-supplied cf_cookies + FLARESOLVERR = "flaresolverr" # maintained by FlareSolverr + + @classmethod + def parse(cls, value: str | Self) -> Self: + if isinstance(value, cls): + return value + normalized = str(value or "").strip().lower() + if not normalized: + return cls.NONE + return cls(normalized) + + +class EgressNodeState(IntEnum): + HEALTHY = 0 + DEGRADED = 1 + UNHEALTHY = 2 + + +class ClearanceBundleState(IntEnum): + VALID = 0 + STALE = 1 + INVALID = 2 + + +class ProxyFeedbackKind(StrEnum): + SUCCESS = "success" + CHALLENGE = "challenge" # CF JS challenge / captcha + UNAUTHORIZED = "unauthorized" # 401 on proxy auth + FORBIDDEN = "forbidden" # 403 not CF-related + RATE_LIMITED = "rate_limited" # 429 + UPSTREAM_5XX = "upstream_5xx" + TRANSPORT_ERROR = "transport_error" + + +class EgressNode(BaseModel): + node_id: str + proxy_url: str | None = None # None → direct + scope: ProxyScope = ProxyScope.APP + state: EgressNodeState = EgressNodeState.HEALTHY + health: float = 1.0 + inflight: int = 0 + last_used: int | None = None # ms + + +class ClearanceBundle(BaseModel): + bundle_id: str + cf_cookies: str = "" + user_agent: str = "" + state: ClearanceBundleState = ClearanceBundleState.VALID + affinity_key: str = "" # associates bundle with an egress node + clearance_host: str = "grok.com" + last_refresh_at: int | None = None # ms + + +class ProxyLease(BaseModel): + lease_id: str + proxy_url: str | None = None + cf_cookies: str = "" + user_agent: str = "" + clearance_host: str = "grok.com" + scope: ProxyScope = ProxyScope.APP + kind: RequestKind = RequestKind.HTTP + acquired_at: int = 0 # ms + + @property + def has_proxy(self) -> bool: + return bool(self.proxy_url) + + +class ProxyFeedback(BaseModel): + kind: ProxyFeedbackKind + status_code: int | None = None + reason: str = "" + retry_after_ms: int | None = None + + +__all__ = [ + "ProxyScope", "RequestKind", "EgressMode", "ClearanceMode", + "EgressNodeState", "ClearanceBundleState", "ProxyFeedbackKind", + "EgressNode", "ClearanceBundle", "ProxyLease", "ProxyFeedback", +] diff --git a/app/control/proxy/providers/__init__.py b/app/control/proxy/providers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22d28e07a1f8a960c5938cb3a7b28dd1079884db --- /dev/null +++ b/app/control/proxy/providers/__init__.py @@ -0,0 +1,4 @@ +from .manual import ManualClearanceProvider +from .flaresolverr import FlareSolverrClearanceProvider + +__all__ = ["ManualClearanceProvider", "FlareSolverrClearanceProvider"] diff --git a/app/control/proxy/providers/flaresolverr.py b/app/control/proxy/providers/flaresolverr.py new file mode 100644 index 0000000000000000000000000000000000000000..8f07d037e4ce90c94a72beda1697b19c3458e32e --- /dev/null +++ b/app/control/proxy/providers/flaresolverr.py @@ -0,0 +1,127 @@ +"""FlareSolverr-backed managed clearance provider.""" + +import asyncio +import json +from urllib import request as urllib_request +from urllib.error import HTTPError, URLError +from urllib.parse import urlparse + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from ..models import ClearanceBundle, ClearanceMode + + +def _extract_all_cookies(cookies: list[dict]) -> str: + return "; ".join(f"{c.get('name')}={c.get('value')}" for c in cookies) + + +class FlareSolverrClearanceProvider: + """Refresh CF clearance bundles via a FlareSolverr instance.""" + + async def refresh_bundle( + self, + *, + affinity_key: str, + proxy_url: str, + target_url: str = "https://grok.com", + ) -> ClearanceBundle | None: + cfg = get_config() + mode = ClearanceMode.parse(cfg.get_str("proxy.clearance.mode", "none")) + if mode != ClearanceMode.FLARESOLVERR: + return None + fs_url = cfg.get_str("proxy.clearance.flaresolverr_url", "") + timeout_sec = cfg.get_int("proxy.clearance.timeout_sec", 60) + if not fs_url: + return None + + result = await self._solve( + fs_url = fs_url, + proxy_url = proxy_url, + timeout_sec = timeout_sec, + target_url = target_url, + ) + if not result: + logger.warning( + "flaresolverr clearance refresh failed: affinity={} proxy={} target={}", + affinity_key, proxy_url or "", target_url, + ) + return None + host = result.get("clearance_host", "grok.com") + + return ClearanceBundle( + bundle_id = f"flaresolverr:{affinity_key}@{host}", + cf_cookies = result.get("cookies", ""), + user_agent = result.get("user_agent", ""), + affinity_key = affinity_key, + clearance_host = host, + ) + + async def _solve( + self, + *, + fs_url: str, + proxy_url: str, + timeout_sec: int, + target_url: str, + ) -> dict[str, str] | None: + target = target_url.strip() or "https://grok.com" + payload: dict = { + "cmd": "request.get", + "url": target, + "maxTimeout": timeout_sec * 1000, + } + if proxy_url: + payload["proxy"] = {"url": proxy_url} + + body = json.dumps(payload).encode() + request = urllib_request.Request( + f"{fs_url.rstrip('/')}/v1", + data = body, + method = "POST", + headers = {"Content-Type": "application/json"}, + ) + + try: + def _post() -> dict: + with urllib_request.urlopen(request, timeout=timeout_sec + 30) as resp: + return json.loads(resp.read().decode()) + + result = await asyncio.to_thread(_post) + if result.get("status") != "ok": + logger.warning( + "flaresolverr returned non-ok status: status={} message={}", + result.get("status"), result.get("message", ""), + ) + return None + + solution = result.get("solution", {}) + cookies = solution.get("cookies", []) + if not cookies: + logger.warning("flaresolverr returned no cookies") + return None + + ua = solution.get("userAgent", "") or "" + host = (urlparse(target).hostname or "").lower() + filtered = [ + cookie for cookie in cookies + if not host or not cookie.get("domain") or host.endswith(str(cookie.get("domain", "")).lstrip(".").lower()) + ] + chosen = filtered or cookies + return { + "cookies": _extract_all_cookies(chosen), + "user_agent": ua, + "clearance_host": host or "grok.com", + } + + except HTTPError as exc: + body_text = exc.read().decode("utf-8", "replace")[:300] + logger.warning("flaresolverr http request failed: status={} body={}", exc.code, body_text) + except URLError as exc: + logger.warning("flaresolverr connection failed: reason={}", exc.reason) + except Exception as exc: + logger.warning("flaresolverr request failed: error={}", exc) + + return None + + +__all__ = ["FlareSolverrClearanceProvider"] diff --git a/app/control/proxy/providers/manual.py b/app/control/proxy/providers/manual.py new file mode 100644 index 0000000000000000000000000000000000000000..0844a367393f8510ca6e5e42844aa8179de065b9 --- /dev/null +++ b/app/control/proxy/providers/manual.py @@ -0,0 +1,31 @@ +"""Manual clearance provider — uses operator-supplied cookies directly.""" + +from app.platform.config.snapshot import get_config +from ..config import resolve_clearance_config +from ..models import ClearanceBundle, ClearanceMode + + +class ManualClearanceProvider: + """Build a ClearanceBundle from static config values.""" + + def build_bundle( + self, + *, + affinity_key: str, + clearance_host: str = "grok.com", + ) -> ClearanceBundle | None: + cfg = get_config() + mode = ClearanceMode.parse(cfg.get_str("proxy.clearance.mode", "none")) + if mode != ClearanceMode.MANUAL: + return None + clearance = resolve_clearance_config(cfg) + return ClearanceBundle( + bundle_id=f"manual:{affinity_key}@{clearance_host}", + cf_cookies=clearance.cf_cookies, + user_agent=clearance.user_agent, + affinity_key=affinity_key, + clearance_host=clearance_host, + ) + + +__all__ = ["ManualClearanceProvider"] diff --git a/app/control/proxy/scheduler.py b/app/control/proxy/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..70bb49b8900231e79c10fdf462585d09d484eb3b --- /dev/null +++ b/app/control/proxy/scheduler.py @@ -0,0 +1,83 @@ +"""Proxy clearance refresh scheduler. + +Periodically refreshes ClearanceBundles for managed (FlareSolverr) mode. +Previously inline in ProxyDirectory; extracted for separation of concerns. +""" + +import asyncio + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.control.proxy import ProxyDirectory + + +class ProxyClearanceScheduler: + """Periodically refreshes proxy clearance bundles.""" + + def __init__(self, directory: ProxyDirectory) -> None: + self._directory = directory + self._task: asyncio.Task | None = None + self._running = False + + def start(self) -> None: + if self._running: + return + self._running = True + self._task = asyncio.create_task(self._loop()) + logger.info("proxy clearance scheduler started") + + def stop(self) -> None: + self._running = False + if self._task and not self._task.done(): + self._task.cancel() + logger.info("proxy clearance scheduler stopped") + + async def _loop(self) -> None: + # Warm up immediately on start so the first request doesn't block. + await self._warm_up() + while self._running: + try: + interval = self._get_interval() + await asyncio.sleep(interval) + if not self._running: + break + await self._refresh() + except asyncio.CancelledError: + break + except Exception as exc: + logger.error( + "proxy clearance scheduler loop failed: error_type={} error={}", + type(exc).__name__, + exc, + ) + await asyncio.sleep(60) + + async def _warm_up(self) -> None: + """Pre-fetch clearance bundles without invalidating existing ones.""" + try: + await self._directory.load() + await self._directory.warm_up() + logger.debug("proxy clearance warm-up completed") + except Exception as exc: + logger.warning("proxy clearance warm-up failed: error={}", exc) + + async def _refresh(self) -> None: + """Build fresh clearance bundles and swap atomically (build-then-swap). + + Old bundles are kept if FlareSolverr is unavailable, so a transient + refresh failure never leaves requests without clearance. + """ + try: + await self._directory.load() + await self._directory.refresh_clearance_safe() + logger.debug("proxy clearance refresh completed") + except Exception as exc: + logger.warning("proxy clearance refresh failed: error={}", exc) + + def _get_interval(self) -> int: + """Return refresh interval in seconds from config.""" + cfg = get_config() + return cfg.get_int("proxy.clearance.refresh_interval", 600) + + +__all__ = ["ProxyClearanceScheduler"] diff --git a/app/dataplane/__init__.py b/app/dataplane/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/dataplane/account/__init__.py b/app/dataplane/account/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7df53a4f0bf84df2de2df6ccf3611492c5816dab --- /dev/null +++ b/app/dataplane/account/__init__.py @@ -0,0 +1,360 @@ +"""AccountDirectory — high-concurrency hot-path account store. + +Wraps the columnar AccountRuntimeTable with lock-minimal coordination. +Bootstrap loads a full snapshot; incremental sync applies revision-based +changesets without holding the selection lock. +""" + +import asyncio +from typing import TYPE_CHECKING + +from app.platform.config.snapshot import get_config +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_s +from app.control.account.repository import AccountRepository +from app.control.account.enums import FeedbackKind +from .table import AccountRuntimeTable +from .lease import AccountLease, new_lease +from .selector import current_strategy, select, select_any +from .sync import bootstrap as _bootstrap, apply_changes +from . import feedback as fb +from ..shared.enums import POOL_ID_TO_STR, StatusId + +if TYPE_CHECKING: + pass + + +class AccountDirectory: + """High-concurrency, lock-minimal account store for the hot path. + + Design: + - ``_table`` is replaced atomically; readers never see partial state. + - ``_lock`` guards all table mutations (feedback, sync, status updates). + - Selection (``reserve``) copies the candidate set under lock, then + scores outside the lock — lock is re-acquired only to increment + inflight. + """ + + def __init__(self, repository: AccountRepository) -> None: + self._repo = repository + self._table: AccountRuntimeTable | None = None + self._lock = asyncio.Lock() + self._sync_lock = asyncio.Lock() + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + async def bootstrap(self) -> None: + """Load initial snapshot from the repository.""" + table = await _bootstrap(self._repo) + async with self._lock: + self._table = table + logger.info("account directory ready: size={}", table.size) + + async def sync_if_changed(self) -> bool: + """Apply incremental changes since last revision. + + Returns True if any changes were applied. + Uses a dedicated sync lock so only one sync runs at a time, + without blocking the selection lock. + """ + if self._table is None: + return False + + async with self._sync_lock: + async with self._lock: + table = self._table + changed = await apply_changes(table, self._repo) + if changed: + logger.debug( + "account directory synced: revision={} size={}", + table.revision, + table.size, + ) + return changed + + # ------------------------------------------------------------------ + # Selection (hot path) + # ------------------------------------------------------------------ + + async def reserve( + self, + pool_candidates: tuple[int, ...] | int, + mode_id: int, + *, + exclude_tokens: list[str] | None = None, + prefer_tags: list[str] | None = None, + now_s_override: int | None = None, + ) -> AccountLease | None: + """Select and reserve the best available account slot. + + ``pool_candidates`` is tried in order; the first pool with an available + account wins. A plain ``int`` is accepted and wrapped into a tuple. + + Returns an AccountLease, or None if no account is available. + """ + table = self._table + if table is None: + return None + + pools: tuple[int, ...] = ( + (pool_candidates,) if isinstance(pool_candidates, int) else pool_candidates + ) + ts = now_s_override if now_s_override is not None else now_s() + + # Resolve exclude set (O(n) once, before lock). + exclude_idxs: frozenset[int] | None = None + if exclude_tokens: + idxs = [ + table.idx_by_token[t] for t in exclude_tokens if t in table.idx_by_token + ] + if idxs: + exclude_idxs = frozenset(idxs) + + # Resolve tag preference set. + prefer_tag_idxs: set[int] | None = None + if prefer_tags: + sets = [ + table.tag_idx.get(tag) for tag in prefer_tags if tag in table.tag_idx + ] + if sets: + prefer_tag_idxs = set().union(*sets) + + async with self._lock: + idx: int | None = None + for pool_id in pools: + idx = select( + table, + pool_id, + mode_id, + exclude_idxs=exclude_idxs, + prefer_tag_idxs=prefer_tag_idxs, + now_s=ts, + ) + if idx is not None: + break + + if idx is None: + return None + + fb.increment_inflight(table, idx) + fb.update_last_use(table, idx, ts) + token = table.get_token(idx) + actual_pool = table.get_pool_id(idx) + + return new_lease( + idx=idx, + token=token, + pool_id=actual_pool, + mode_id=mode_id, + selected_at=ts, + ) + + async def reserve_any( + self, + pool_candidates: tuple[int, ...] | int, + *, + exclude_tokens: list[str] | None = None, + prefer_tags: list[str] | None = None, + now_s_override: int | None = None, + ) -> AccountLease | None: + """Select any active account from pool_candidates without mode quota checking. + + Used for WebSocket-based operations that manage their own upstream rate limiting. + Returns an AccountLease with mode_id=-1 (no specific mode is tracked). + """ + table = self._table + if table is None: + return None + + pools: tuple[int, ...] = ( + (pool_candidates,) if isinstance(pool_candidates, int) else pool_candidates + ) + ts = now_s_override if now_s_override is not None else now_s() + + exclude_idxs: frozenset[int] | None = None + if exclude_tokens: + idxs = [ + table.idx_by_token[t] for t in exclude_tokens if t in table.idx_by_token + ] + if idxs: + exclude_idxs = frozenset(idxs) + + prefer_tag_idxs: set[int] | None = None + if prefer_tags: + sets = [ + table.tag_idx.get(tag) for tag in prefer_tags if tag in table.tag_idx + ] + if sets: + prefer_tag_idxs = set().union(*sets) + + async with self._lock: + idx: int | None = None + for pool_id in pools: + idx = select_any( + table, + pool_id, + exclude_idxs=exclude_idxs, + prefer_tag_idxs=prefer_tag_idxs, + now_s=ts, + ) + if idx is not None: + break + + if idx is None: + return None + + fb.increment_inflight(table, idx) + fb.update_last_use(table, idx, ts) + token = table.get_token(idx) + actual_pool = table.get_pool_id(idx) + + return new_lease( + idx=idx, + token=token, + pool_id=actual_pool, + mode_id=-1, # no specific mode tracked for WS operations + selected_at=ts, + ) + + async def release(self, lease: AccountLease) -> None: + """Decrement inflight counter for a finished request.""" + table = self._table + if table is None: + return + async with self._lock: + fb.decrement_inflight(table, lease.idx) + + # ------------------------------------------------------------------ + # Feedback (hot path) + # ------------------------------------------------------------------ + + async def feedback( + self, + token: str, + kind: FeedbackKind, + mode_id: int, + *, + remaining: int | None = None, + reset_at_ms: int | None = None, + now_s_val: int | None = None, + ) -> None: + """Apply upstream response feedback to the account slot.""" + table = self._table + if table is None: + return + + idx = table.idx_by_token.get(token) + if idx is None: + return + + ts = now_s_val if now_s_val is not None else now_s() + + strategy = current_strategy() + + async with self._lock: + if kind == FeedbackKind.SUCCESS: + if strategy == "random": + fb.apply_success_random(table, idx) + else: + fb.apply_success_quota(table, idx, mode_id) + + elif kind == FeedbackKind.RATE_LIMITED: + if strategy == "random": + pool_id = int(table.pool_by_idx[idx]) + cooling_sec = _pool_cooling_sec(pool_id, mode_id) + fb.apply_rate_limited_random(table, idx, cooling_sec=cooling_sec) + else: + fb.apply_rate_limited_quota(table, idx, mode_id) + fb.update_last_fail(table, idx, ts) + + elif kind == FeedbackKind.UNAUTHORIZED: + fb.apply_auth_failure(table, idx) + fb.update_last_fail(table, idx, ts) + fb.apply_status_change(table, idx, int(StatusId.EXPIRED)) + + elif kind == FeedbackKind.FORBIDDEN: + fb.apply_forbidden(table, idx) + fb.update_last_fail(table, idx, ts) + + elif kind == FeedbackKind.SERVER_ERROR: + fb.apply_server_error(table, idx) + fb.update_last_fail(table, idx, ts) + + # Quota strategy may receive authoritative quota data from upstream + # response headers; the random strategy ignores this entirely. + if strategy == "quota" and remaining is not None and reset_at_ms is not None: + reset_s = int(reset_at_ms // 1000) + fb.apply_quota_update(table, idx, mode_id, remaining, reset_s) + + # ------------------------------------------------------------------ + # Diagnostics + # ------------------------------------------------------------------ + + @property + def size(self) -> int: + return self._table.size if self._table else 0 + + @property + def revision(self) -> int: + return self._table.revision if self._table else 0 + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +_POOL_INTERVAL_CONFIG: dict[str, tuple[str, int]] = { + "basic": ("account.refresh.basic_interval_sec", 86_400), + "super": ("account.refresh.super_interval_sec", 7_200), + "heavy": ("account.refresh.heavy_interval_sec", 7_200), +} + +# Console (mode_id=5) 窗口仅 3600s,使用 4 小时冷却(远大于窗口, +# 给上游 team 限速充分恢复时间,但不会沉寂一整天) +_CONSOLE_COOLING_SEC = 14_400 + + +def _pool_cooling_sec(pool_id: int, mode_id: int = -1) -> int: + """Cooling seconds for a 429 on a given pool (random strategy only). + + Console 模式 (mode_id=5) 使用独立冷却时长 4 小时; + 其它模式按 pool 决定(basic=24h, super/heavy=2h)。 + """ + if mode_id == 5: + return _CONSOLE_COOLING_SEC + pool_str = POOL_ID_TO_STR.get(pool_id, "basic") + interval_key, default_interval = _POOL_INTERVAL_CONFIG.get( + pool_str, _POOL_INTERVAL_CONFIG["basic"] + ) + return max(0, int(get_config(interval_key, default_interval))) + + +# --------------------------------------------------------------------------- +# Module-level singleton +# --------------------------------------------------------------------------- + +_directory: AccountDirectory | None = None + + +async def get_account_directory( + repository: AccountRepository | None = None, +) -> AccountDirectory: + """Return the module-level AccountDirectory, bootstrapping on first call. + + After first initialization, ``repository`` may be omitted. + """ + global _directory + if _directory is None: + if repository is None: + raise RuntimeError( + "AccountDirectory not bootstrapped — repository required on first call" + ) + _directory = AccountDirectory(repository) + await _directory.bootstrap() + return _directory + + +__all__ = ["AccountDirectory", "get_account_directory"] diff --git a/app/dataplane/account/feedback.py b/app/dataplane/account/feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..3372b56e3df3046897d535bc64baa20f20258844 --- /dev/null +++ b/app/dataplane/account/feedback.py @@ -0,0 +1,186 @@ +"""Apply feedback to the runtime table columns (in-place, lock-free inner ops). + +The caller (AccountDirectory) is responsible for holding the state lock before +calling these functions. + +Strategy-split functions +------------------------ +``apply_success`` / ``apply_rate_limited`` are split into ``*_quota`` and +``*_random`` variants. The caller picks exactly one based on the active +selector strategy. No runtime ``if`` inside the apply helpers themselves. +""" + +from app.platform.runtime.clock import now_s +from ..shared.enums import ALL_MODE_IDS, StatusId +from .table import AccountRuntimeTable + +# Health adjustment constants. +_SUCCESS_STEP = 0.12 +_AUTH_FACTOR = 0.55 +_FORBIDDEN_FACTOR = 0.25 +_RATE_LIMIT_FACTOR = 0.45 +_SERVER_ERROR_FACTOR = 0.75 +_MIN_HEALTH = 0.05 +_MAX_HEALTH = 1.0 + + +# --------------------------------------------------------------------------- +# apply_success — two independent implementations +# --------------------------------------------------------------------------- + + +def apply_success_quota(table: AccountRuntimeTable, idx: int, mode_id: int) -> None: + """Quota strategy: decrement per-mode quota and improve health.""" + quota_col = table._quota_col(mode_id) + quota_col[idx] = max(0, int(quota_col[idx]) - 1) + _bump_health(table, idx) + + +def apply_success_random(table: AccountRuntimeTable, idx: int) -> None: + """Random strategy: only improve health; quota columns are ignored.""" + _bump_health(table, idx) + + +# --------------------------------------------------------------------------- +# apply_rate_limited — two independent implementations +# --------------------------------------------------------------------------- + + +def apply_rate_limited_quota( + table: AccountRuntimeTable, idx: int, mode_id: int +) -> None: + """Quota strategy: zero the mode quota and reduce health.""" + table._quota_col(mode_id)[idx] = 0 + _adjust_health(table, idx, _RATE_LIMIT_FACTOR) + + +def apply_rate_limited_random( + table: AccountRuntimeTable, idx: int, *, cooling_sec: int +) -> None: + """Random strategy: set per-account cooldown timestamp; do not touch quota. + + The account stays in ``mode_available``; ``_random_select`` filters it out + until ``cooling_until_s_by_idx`` has elapsed. + """ + ts = now_s() + max(0, cooling_sec) + cooling_col = table.cooling_until_s_by_idx + cooling_col[idx] = max(int(cooling_col[idx]), ts) + _adjust_health(table, idx, _RATE_LIMIT_FACTOR) + + +# --------------------------------------------------------------------------- +# Strategy-agnostic feedback helpers (shared) +# --------------------------------------------------------------------------- + + +def apply_auth_failure(table: AccountRuntimeTable, idx: int) -> None: + """Reduce health on 401; caller may mark account expired.""" + _adjust_health(table, idx, _AUTH_FACTOR) + + +def apply_forbidden(table: AccountRuntimeTable, idx: int) -> None: + """Reduce health heavily on 403.""" + _adjust_health(table, idx, _FORBIDDEN_FACTOR) + + +def apply_server_error(table: AccountRuntimeTable, idx: int) -> None: + """Mildly reduce health on 5xx / transport errors.""" + _adjust_health(table, idx, _SERVER_ERROR_FACTOR) + + +def apply_status_change( + table: AccountRuntimeTable, idx: int, new_status_id: int +) -> None: + """Update status column and refresh availability indexes.""" + pool_id = int(table.pool_by_idx[idx]) + old_status = int(table.status_by_idx[idx]) + + if old_status == new_status_id: + return + + table.status_by_idx[idx] = new_status_id + + if new_status_id != int(StatusId.ACTIVE): + for mode_id in ALL_MODE_IDS: + bucket = table.mode_available.get((pool_id, mode_id)) + if bucket: + bucket.discard(idx) + else: + for mode_id in ALL_MODE_IDS: + if int(table._quota_col(mode_id)[idx]) > 0: + table.mode_available.setdefault((pool_id, mode_id), set()).add(idx) + + +def apply_quota_update( + table: AccountRuntimeTable, + idx: int, + mode_id: int, + remaining: int, + reset_s: int, +) -> None: + """Update quota and reset timestamp from upstream API data. + + Used exclusively by the quota strategy (refresh service). The random + strategy never calls this. + """ + quota_col = table._quota_col(mode_id) + reset_col = table._reset_col(mode_id) + quota_col[idx] = max(0, min(remaining, 32767)) + reset_col[idx] = reset_s + + pool_id = int(table.pool_by_idx[idx]) + if int(table.status_by_idx[idx]) == int(StatusId.ACTIVE): + bucket = table.mode_available.setdefault((pool_id, mode_id), set()) + if int(table._window_col(mode_id)[idx]) > 0: + bucket.add(idx) + + +def increment_inflight(table: AccountRuntimeTable, idx: int) -> None: + table.inflight_by_idx[idx] = min(int(table.inflight_by_idx[idx]) + 1, 65535) + + +def decrement_inflight(table: AccountRuntimeTable, idx: int) -> None: + table.inflight_by_idx[idx] = max(0, int(table.inflight_by_idx[idx]) - 1) + + +def update_last_use(table: AccountRuntimeTable, idx: int, now_s: int) -> None: + table.last_use_at_by_idx[idx] = now_s + + +def update_last_fail(table: AccountRuntimeTable, idx: int, now_s: int) -> None: + table.last_fail_at_by_idx[idx] = now_s + table.fail_count_by_idx[idx] = min(int(table.fail_count_by_idx[idx]) + 1, 65535) + + +# --------------------------------------------------------------------------- +# Internal +# --------------------------------------------------------------------------- + + +def _bump_health(table: AccountRuntimeTable, idx: int) -> None: + table.health_by_idx[idx] = min( + _MAX_HEALTH, float(table.health_by_idx[idx]) + _SUCCESS_STEP + ) + + +def _adjust_health(table: AccountRuntimeTable, idx: int, factor: float) -> None: + table.health_by_idx[idx] = max( + _MIN_HEALTH, float(table.health_by_idx[idx]) * factor + ) + + +__all__ = [ + "apply_success_quota", + "apply_success_random", + "apply_rate_limited_quota", + "apply_rate_limited_random", + "apply_auth_failure", + "apply_forbidden", + "apply_server_error", + "apply_status_change", + "apply_quota_update", + "increment_inflight", + "decrement_inflight", + "update_last_use", + "update_last_fail", +] diff --git a/app/dataplane/account/lease.py b/app/dataplane/account/lease.py new file mode 100644 index 0000000000000000000000000000000000000000..41edb61277de18c24622ec8057d848d25696a3eb --- /dev/null +++ b/app/dataplane/account/lease.py @@ -0,0 +1,36 @@ +"""AccountLease — minimal hot-path rental object.""" + +from dataclasses import dataclass + +from app.platform.runtime.ids import next_id + + +@dataclass(slots=True) +class AccountLease: + """Represents a reserved account slot for a single upstream request. + + Holds only the minimum fields needed on the hot path — no AccountRecord. + The slot *idx* allows O(1) array access for feedback updates. + """ + + lease_id: int # monotonic counter — cheaper than uuid + idx: int # slot in AccountRuntimeTable + token: str # cached for header building + pool_id: int # PoolId integer + mode_id: int # ModeId integer + selected_at: int # ms timestamp + + +def new_lease(idx: int, token: str, pool_id: int, mode_id: int, selected_at: int) -> AccountLease: + """Construct an AccountLease with an auto-incremented id.""" + return AccountLease( + lease_id = next_id(), + idx = idx, + token = token, + pool_id = pool_id, + mode_id = mode_id, + selected_at = selected_at, + ) + + +__all__ = ["AccountLease", "new_lease"] diff --git a/app/dataplane/account/selector.py b/app/dataplane/account/selector.py new file mode 100644 index 0000000000000000000000000000000000000000..4e74b5a787fd733379e6b648768845fd47148ba3 --- /dev/null +++ b/app/dataplane/account/selector.py @@ -0,0 +1,350 @@ +"""Hot-path account selector — pluggable strategies. + +Two fully independent strategies: + +* ``_quota_select`` — scores candidates by health / quota / inflight / fails. + Used when ``account.refresh.enabled=true``. Behaviour is the historical one, + kept unchanged. +* ``_random_select`` — uniform random choice among non-cooling candidates. + Used when ``account.refresh.enabled=false``. Ignores quota and health entirely. + +Strategy selection is process-global, registered once by the lifespan via +:func:`set_strategy`. Callers (``AccountDirectory``) invoke :func:`select` / +:func:`select_any` and are unaware of which strategy is active. +""" + +import array # noqa: F401 — used in forward-referenced type annotations +import random +from typing import Literal + +from app.platform.config.snapshot import get_config +from .table import AccountRuntimeTable + +# Scoring weights used by the quota strategy. +_W_HEALTH = 100.0 +_W_QUOTA = 25.0 +_W_RECENT = 15.0 # penalty for recently used accounts +_W_INFLIGHT = 20.0 +_W_FAIL = 4.0 +_RECENT_WINDOW_S = 60 # seconds — 覆盖 grok-4-3 思考时长(典型 30-60s),强制账号轮换 +_QUOTA_MAX_INFLIGHT = 12 # quota 策略下单账号最多 12 个并发请求,防止单账号堆积引发上游风控 +_RANDOM_MAX_FAILS = 5 # random 策略下,累计失败 >= 5 次的账号暂时不选(D2 修复) + + +# --------------------------------------------------------------------------- +# Strategy registry +# --------------------------------------------------------------------------- + +_StrategyName = Literal["quota", "random"] +_STRATEGY_NAME: _StrategyName = "random" + + +def set_strategy(name: _StrategyName) -> None: + """Register the process-global selection strategy. + + Called once by the lifespan after reading ``account.refresh.enabled``. + """ + global _STRATEGY_NAME + if name not in ("quota", "random"): + raise ValueError(f"unknown selection strategy: {name!r}") + _STRATEGY_NAME = name + + +def current_strategy() -> _StrategyName: + return _STRATEGY_NAME + + +# --------------------------------------------------------------------------- +# Public entry points — delegate to the active strategy +# --------------------------------------------------------------------------- + + +def select( + table: AccountRuntimeTable, + pool_id: int, + mode_id: int, + *, + exclude_idxs: frozenset[int] | None = None, + prefer_tag_idxs: set[int] | None = None, + now_s: int, +) -> int | None: + """Select an account slot for ``(pool_id, mode_id)``. + + Returns the slot index or ``None`` when no candidate is available. + Does not mutate the table — callers increment inflight separately. + """ + if _STRATEGY_NAME == "random": + return _random_select( + table, pool_id, + exclude_idxs=exclude_idxs, + prefer_tag_idxs=prefer_tag_idxs, + now_s=now_s, + ) + return _quota_select( + table, pool_id, mode_id, + exclude_idxs=exclude_idxs, + prefer_tag_idxs=prefer_tag_idxs, + now_s=now_s, + ) + + +def select_any( + table: AccountRuntimeTable, + pool_id: int, + *, + exclude_idxs: frozenset[int] | None = None, + prefer_tag_idxs: set[int] | None = None, + now_s: int, +) -> int | None: + """Select any active account in ``pool_id`` irrespective of per-mode quota. + + Used by WebSocket-based products that manage their own rate limiting. + """ + if _STRATEGY_NAME == "random": + return _random_select( + table, pool_id, + exclude_idxs=exclude_idxs, + prefer_tag_idxs=prefer_tag_idxs, + now_s=now_s, + ) + return _quota_select_any( + table, pool_id, + exclude_idxs=exclude_idxs, + prefer_tag_idxs=prefer_tag_idxs, + now_s=now_s, + ) + + +# --------------------------------------------------------------------------- +# Strategy: quota — score-based selection (unchanged behaviour) +# --------------------------------------------------------------------------- + + +def _quota_select( + table: AccountRuntimeTable, + pool_id: int, + mode_id: int, + *, + exclude_idxs: frozenset[int] | None, + prefer_tag_idxs: set[int] | None, + now_s: int, +) -> int | None: + candidates: set[int] | None = table.mode_available.get((pool_id, mode_id)) + if not candidates: + return None + + reset_col = table._reset_col(mode_id) + quota_col = table._quota_col(mode_id) + total_col = table._total_col(mode_id) + window_col = table._window_col(mode_id) + inflight_col = table.inflight_by_idx + _maybe_reset_windows( + table, candidates, mode_id, + reset_col, quota_col, total_col, window_col, + pool_id, now_s, + ) + + working: set[int] = candidates.copy() + if exclude_idxs: + working -= exclude_idxs + # B3: inflight 硬上限过滤,避免单账号堆积导致上游风控 + working = { + idx for idx in working + if int(quota_col[idx]) > 0 + and int(inflight_col[idx]) < _QUOTA_MAX_INFLIGHT + } + if not working: + return None + + if prefer_tag_idxs: + preferred = working & prefer_tag_idxs + working = preferred if preferred else working + + return _best(table, working, quota_col, now_s) + + +def _quota_select_any( + table: AccountRuntimeTable, + pool_id: int, + *, + exclude_idxs: frozenset[int] | None, + prefer_tag_idxs: set[int] | None, + now_s: int, +) -> int | None: + candidates: set[int] = _pool_union(table, pool_id) + if not candidates: + return None + + working = candidates.copy() + if exclude_idxs: + working -= exclude_idxs + if not working: + return None + + if prefer_tag_idxs: + preferred = working & prefer_tag_idxs + working = preferred if preferred else working + + return _best_no_quota(table, working, now_s) + + +def _maybe_reset_windows( + table: AccountRuntimeTable, + candidates: set[int], + mode_id: int, + reset_col: "array.array", + quota_col: "array.array", + total_col: "array.array", + window_col: "array.array", + pool_id: int, + now_s: int, +) -> None: + """Reset expired windows inline for any pool (no API call needed). + + L7 修复:原仅对 basic 池生效;扩展到 super/heavy 后,在 refresh scheduler + 卡死或上游不可达时也能本地兜底重置,避免账号"卡死"在过期窗口。 + """ + for idx in list(candidates): + r = reset_col[idx] + if r == 0 or now_s < r: + continue + if int(table.pool_by_idx[idx]) != pool_id: + continue + new_total = int(total_col[idx]) + window_s = int(window_col[idx]) + if new_total <= 0 or window_s <= 0: + continue + quota_col[idx] = new_total + reset_col[idx] = now_s + window_s + + +def _best( + table: AccountRuntimeTable, + working: set[int], + quota_col: "array.array", + now_s: int, +) -> int | None: + best_idx = -1 + best_score = -1e18 + + health_col = table.health_by_idx + inflight_col = table.inflight_by_idx + fail_col = table.fail_count_by_idx + last_use_col = table.last_use_at_by_idx + + for idx in working: + quota = int(quota_col[idx]) + if quota <= 0: + continue + health = float(health_col[idx]) + inflight = int(inflight_col[idx]) + fails = min(int(fail_col[idx]), 10) + last_use = int(last_use_col[idx]) + + score = ( + health * _W_HEALTH + + quota * _W_QUOTA + - inflight * _W_INFLIGHT + - fails * _W_FAIL + ) + if last_use > 0: + age_s = now_s - last_use + if age_s < _RECENT_WINDOW_S: + score -= (1.0 - age_s / _RECENT_WINDOW_S) * _W_RECENT + + if score > best_score: + best_score = score + best_idx = idx + + return best_idx if best_idx >= 0 else None + + +def _best_no_quota( + table: AccountRuntimeTable, + working: set[int], + now_s: int, +) -> int | None: + best_idx = -1 + best_score = -1e18 + + health_col = table.health_by_idx + inflight_col = table.inflight_by_idx + fail_col = table.fail_count_by_idx + last_use_col = table.last_use_at_by_idx + + for idx in working: + health = float(health_col[idx]) + inflight = int(inflight_col[idx]) + fails = min(int(fail_col[idx]), 10) + last_use = int(last_use_col[idx]) + + score = health * _W_HEALTH - inflight * _W_INFLIGHT - fails * _W_FAIL + if last_use > 0: + age_s = now_s - last_use + if age_s < _RECENT_WINDOW_S: + score -= (1.0 - age_s / _RECENT_WINDOW_S) * _W_RECENT + + if score > best_score: + best_score = score + best_idx = idx + + return best_idx if best_idx >= 0 else None + + +# --------------------------------------------------------------------------- +# Strategy: random — uniform choice with cooling + inflight filter +# --------------------------------------------------------------------------- + + +def _random_select( + table: AccountRuntimeTable, + pool_id: int, + *, + exclude_idxs: frozenset[int] | None, + prefer_tag_idxs: set[int] | None, + now_s: int, +) -> int | None: + candidates: set[int] = _pool_union(table, pool_id) + if not candidates: + return None + + max_inflight = int(get_config("account.selection.max_inflight", 8)) + cooling_col = table.cooling_until_s_by_idx + inflight_col = table.inflight_by_idx + fail_col = table.fail_count_by_idx + + working = candidates.copy() + if exclude_idxs: + working -= exclude_idxs + # D2 修复:累计失败 >= _RANDOM_MAX_FAILS 的账号暂时排除,避免重复打到刚失败的账号 + working = { + idx for idx in working + if int(cooling_col[idx]) <= now_s + and int(inflight_col[idx]) < max_inflight + and int(fail_col[idx]) < _RANDOM_MAX_FAILS + } + if not working: + return None + + if prefer_tag_idxs: + preferred = working & prefer_tag_idxs + working = preferred if preferred else working + + return random.choice(tuple(working)) + + +# --------------------------------------------------------------------------- +# Shared helper +# --------------------------------------------------------------------------- + + +def _pool_union(table: AccountRuntimeTable, pool_id: int) -> set[int]: + """Union of all ``mode_available`` buckets for ``pool_id``.""" + out: set[int] = set() + for (pid, _mid), accounts in table.mode_available.items(): + if pid == pool_id: + out |= accounts + return out + + +__all__ = ["select", "select_any", "set_strategy", "current_strategy"] diff --git a/app/dataplane/account/sync.py b/app/dataplane/account/sync.py new file mode 100644 index 0000000000000000000000000000000000000000..f4e04957359058b4ff3fe4e94ff7395184afcd95 --- /dev/null +++ b/app/dataplane/account/sync.py @@ -0,0 +1,165 @@ +"""Synchronise the AccountRuntimeTable from the control-plane repository. + +Two modes: + bootstrap — full snapshot load at startup. + incremental — revision-based change scan at runtime. +""" + +from app.platform.logging.logger import logger +from app.platform.runtime.clock import ms_to_s +from app.control.account.models import AccountRecord +from app.control.account.quota_defaults import normalize_quota_set +from app.control.account.repository import AccountRepository +from app.control.account.state_machine import derive_status +from ..shared.enums import POOL_STR_TO_ID, STATUS_STR_TO_ID, StatusId +from .table import AccountRuntimeTable, make_empty_table + + +def _record_to_slot_args(record: AccountRecord) -> dict: + """Extract columnar values from a control-plane AccountRecord.""" + qs = normalize_quota_set(record.pool, record.quota_set()) + status_id = STATUS_STR_TO_ID.get(str(derive_status(record)), int(StatusId.ACTIVE)) + pool_id = POOL_STR_TO_ID.get(record.pool, 0) + + def _reset_s(window) -> int: + if window.reset_at is None: + return 0 + return int(ms_to_s(window.reset_at)) + + def _total(window) -> int: + return max(0, int(window.total)) if window is not None else 0 + + def _window_s(window) -> int: + return max(0, int(window.window_seconds)) if window is not None else 0 + + heavy_w = qs.heavy + grok_4_3_w = qs.grok_4_3 + console_w = qs.console + # fmt: off + return dict( + pool_id = pool_id, + status_id = status_id, + quota_auto = max(0, qs.auto.remaining), + quota_fast = max(0, qs.fast.remaining), + quota_expert = max(0, qs.expert.remaining), + quota_heavy = max(0, heavy_w.remaining) if heavy_w is not None else -1, + quota_grok_4_3 = max(0, grok_4_3_w.remaining) if grok_4_3_w is not None else -1, + quota_console = max(0, console_w.remaining) if console_w is not None else -1, + total_auto = _total(qs.auto), + total_fast = _total(qs.fast), + total_expert = _total(qs.expert), + total_heavy = _total(heavy_w), + total_grok_4_3 = _total(grok_4_3_w), + total_console = _total(console_w), + window_auto = _window_s(qs.auto), + window_fast = _window_s(qs.fast), + window_expert = _window_s(qs.expert), + window_heavy = _window_s(heavy_w), + window_grok_4_3 = _window_s(grok_4_3_w), + window_console = _window_s(console_w), + reset_auto = _reset_s(qs.auto), + reset_fast = _reset_s(qs.fast), + reset_expert = _reset_s(qs.expert), + reset_heavy = _reset_s(heavy_w) if heavy_w is not None else 0, + reset_grok_4_3 = _reset_s(grok_4_3_w) if grok_4_3_w is not None else 0, + reset_console = _reset_s(console_w) if console_w is not None else 0, + health = 1.0, + last_use_s = ms_to_s(record.last_use_at) if record.last_use_at else 0, + last_fail_s = ms_to_s(record.last_fail_at) if record.last_fail_at else 0, + fail_count = record.usage_fail_count, + tags = record.tags, + ) + # fmt: on + + +async def bootstrap(repository: AccountRepository) -> AccountRuntimeTable: + """Load all non-deleted accounts into a fresh AccountRuntimeTable.""" + snapshot = await repository.runtime_snapshot() + table = make_empty_table() + # Cache tags per token for tag_idx. + _tags_by_token: dict[str, list[str]] = {} + + for record in snapshot.items: + if record.is_deleted(): + continue + args = _record_to_slot_args(record) + tags = args.pop("tags") + _tags_by_token[record.token] = tags + table._append_slot(record.token, **args, tags=tags) + + table.revision = snapshot.revision + logger.info( + "account runtime table bootstrapped: revision={} account_count={} pool_count={}", + table.revision, + table.size, + len({k[0] for k in table.mode_available}), + ) + return table + + +async def apply_changes( + table: AccountRuntimeTable, + repository: AccountRepository, + *, + batch_limit: int = 5000, +) -> bool: + """Incrementally sync changes since ``table.revision``. + + Returns ``True`` if any changes were applied. + """ + changed = False + while True: + changeset = await repository.scan_changes(table.revision, limit=batch_limit) + + for token in changeset.deleted_tokens: + idx = table.idx_by_token.get(token) + if idx is not None: + table._remove_from_indexes(idx) + # Mark as deleted in status column so it is skipped. + table.status_by_idx[idx] = int(StatusId.DELETED) + table.size = max(0, table.size - 1) + changed = True + + for record in changeset.items: + if record.is_deleted(): + # Handle soft-delete from items list too. + idx = table.idx_by_token.get(record.token) + if idx is not None: + table._remove_from_indexes(idx) + table.status_by_idx[idx] = int(StatusId.DELETED) + table.size = max(0, table.size - 1) + changed = True + continue + + args = _record_to_slot_args(record) + tags = args.pop("tags") + existing = table.idx_by_token.get(record.token) + + if existing is not None: + old_tags = [] + # Collect old tags from tag_idx (reverse lookup). + for tag, bucket in list(table.tag_idx.items()): + if existing in bucket: + old_tags.append(tag) + table._update_slot(existing, **args, old_tags=old_tags, new_tags=tags) + else: + table._append_slot(record.token, **args, tags=tags) + + changed = True + + if changeset.has_more: + # 中间批:只推进到本批观察到的最大 revision, + # 否则下一轮 scan 会跳过尚未返回的中间行(S2 修复)。 + if changeset.batch_max_revision > table.revision: + table.revision = changeset.batch_max_revision + else: + # 最后一批:可以信任 changeset.revision(db 当前全局 rev), + # 把 table 推进到全局 rev,使下次 scan 不再重复扫描已处理行。 + if changeset.revision > table.revision: + table.revision = changeset.revision + break + + return changed + + +__all__ = ["bootstrap", "apply_changes"] diff --git a/app/dataplane/account/table.py b/app/dataplane/account/table.py new file mode 100644 index 0000000000000000000000000000000000000000..f00cf898c422b381cf4a71f1d8a67930da11c178 --- /dev/null +++ b/app/dataplane/account/table.py @@ -0,0 +1,456 @@ +"""Columnar runtime account table for high-throughput hot-path selection. + +Memory layout (1 000 accounts): + Object-list design : ~800 KB (Python object overhead per entry) + Columnar array design: ~80 KB (packed C arrays) + +All quota, status, health, and counter fields are stored as typed +``array.array`` columns indexed by a compact integer slot index. +""" + +import array +from dataclasses import dataclass, field +from typing import Iterator + +from ..shared.enums import ALL_MODE_IDS, StatusId + +# --------------------------------------------------------------------------- +# Column type codes +# 'B' uint8 — pool_id, status_id +# 'h' int16 — quota remaining / total (max 32767; sufficient for all known limits) +# 'H' uint16 — inflight, fail_count +# 'f' float32 — health score +# 'L' uint32 — epoch-second timestamps / window lengths (valid until year 2106) +# --------------------------------------------------------------------------- + +_QUOTA_COLS = ( + "quota_auto", + "quota_fast", + "quota_expert", + "quota_heavy", + "quota_grok_4_3", + "quota_console", +) +_RESET_COLS = ( + "reset_auto", + "reset_fast", + "reset_expert", + "reset_heavy", + "reset_grok_4_3", + "reset_console", +) +_INFLIGHT_CAP = 32_767 # avoid int16 overflow on quota + +# --------------------------------------------------------------------------- +# AccountRuntimeTable +# --------------------------------------------------------------------------- + + +@dataclass +class AccountRuntimeTable: + """Columnar in-memory account store. + + Columns are indexed by a compact integer *slot index* (idx). + The index space is dense: deleted slots are reused on next bootstrap. + + Thread-safety: the caller (AccountDirectory) owns all locking. + """ + + # --- Identity --- + token_by_idx: list[str] = field(default_factory=list) + idx_by_token: dict[str, int] = field(default_factory=dict) + + # --- Pool / status (uint8) --- + pool_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("B")) + status_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("B")) + + # --- Quota remaining per mode (int16; -1 = unknown) --- + quota_auto_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + quota_fast_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + quota_expert_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + quota_heavy_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + quota_grok_4_3_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + + # --- Quota remaining per mode (int16; -1 = unknown) --- console + quota_console_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + + # --- Quota total per mode (int16; 0 = unsupported / unknown) --- + total_auto_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + total_fast_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + total_expert_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + total_heavy_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + total_grok_4_3_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + + # --- Quota total per mode (int16; 0 = unsupported / unknown) --- console + total_console_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("h") + ) + + # --- Window size per mode (uint32 seconds; 0 = unsupported / unknown) --- + window_auto_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + window_fast_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + window_expert_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + window_heavy_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + window_grok_4_3_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + + # --- Window size per mode (uint32 seconds; 0 = unsupported / unknown) --- console + window_console_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + + # --- Window reset timestamps (uint32 epoch-seconds; 0 = unknown) --- + reset_auto_at_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + reset_fast_at_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + reset_expert_at_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + reset_heavy_at_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + reset_grok_4_3_at_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + + # --- Window reset timestamps (uint32 epoch-seconds; 0 = unknown) --- console + reset_console_at_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + + # --- Runtime counters (uint16) --- + inflight_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("H") + ) + fail_count_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("H") + ) + + # --- Health score (float32; [0.05, 1.0]) --- + health_by_idx: "array.array[float]" = field( + default_factory=lambda: array.array("f") + ) + + # --- Last-activity timestamps (uint32 epoch-seconds; 0 = never) --- + last_use_at_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + last_fail_at_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + + # --- Per-account cooldown (random strategy only; uint32 epoch-seconds; 0 = not cooling) --- + cooling_until_s_by_idx: "array.array[int]" = field( + default_factory=lambda: array.array("L") + ) + + # --- Pre-computed selection indexes --- + # (pool_id, mode_id) → set of idx with a supported quota window and status == ACTIVE + mode_available: dict[tuple[int, int], set[int]] = field(default_factory=dict) + # tag string → set of idx + tag_idx: dict[str, set[int]] = field(default_factory=dict) + + # --- Metadata --- + revision: int = 0 + size: int = 0 # number of live (non-deleted) slots + + # --------------------------------------------------------------------------- + # Internal helpers + # --------------------------------------------------------------------------- + + def _quota_col(self, mode_id: int) -> "array.array[int]": + if mode_id == 0: + return self.quota_auto_by_idx + if mode_id == 1: + return self.quota_fast_by_idx + if mode_id == 2: + return self.quota_expert_by_idx + if mode_id == 3: + return self.quota_heavy_by_idx + if mode_id == 4: + return self.quota_grok_4_3_by_idx + return self.quota_console_by_idx + + def _reset_col(self, mode_id: int) -> "array.array[int]": + if mode_id == 0: + return self.reset_auto_at_by_idx + if mode_id == 1: + return self.reset_fast_at_by_idx + if mode_id == 2: + return self.reset_expert_at_by_idx + if mode_id == 3: + return self.reset_heavy_at_by_idx + if mode_id == 4: + return self.reset_grok_4_3_at_by_idx + return self.reset_console_at_by_idx + + def _total_col(self, mode_id: int) -> "array.array[int]": + if mode_id == 0: + return self.total_auto_by_idx + if mode_id == 1: + return self.total_fast_by_idx + if mode_id == 2: + return self.total_expert_by_idx + if mode_id == 3: + return self.total_heavy_by_idx + if mode_id == 4: + return self.total_grok_4_3_by_idx + return self.total_console_by_idx + + def _window_col(self, mode_id: int) -> "array.array[int]": + if mode_id == 0: + return self.window_auto_by_idx + if mode_id == 1: + return self.window_fast_by_idx + if mode_id == 2: + return self.window_expert_by_idx + if mode_id == 3: + return self.window_heavy_by_idx + if mode_id == 4: + return self.window_grok_4_3_by_idx + return self.window_console_by_idx + + def _add_to_indexes(self, idx: int) -> None: + pool_id = int(self.pool_by_idx[idx]) + status_id = int(self.status_by_idx[idx]) + if status_id != int(StatusId.ACTIVE): + return + for mode_id in ALL_MODE_IDS: + if self._window_col(mode_id)[idx] > 0: + self.mode_available.setdefault((pool_id, mode_id), set()).add(idx) + + def _remove_from_indexes(self, idx: int) -> None: + pool_id = int(self.pool_by_idx[idx]) + for mode_id in ALL_MODE_IDS: + bucket = self.mode_available.get((pool_id, mode_id)) + if bucket: + bucket.discard(idx) + + def _remove_from_tag_idx(self, idx: int, tags: list[str]) -> None: + for tag in tags: + bucket = self.tag_idx.get(tag) + if bucket: + bucket.discard(idx) + + def _add_to_tag_idx(self, idx: int, tags: list[str]) -> None: + for tag in tags: + self.tag_idx.setdefault(tag, set()).add(idx) + + # --------------------------------------------------------------------------- + # Slot append (used during bootstrap) + # --------------------------------------------------------------------------- + + def _append_slot( + self, + token: str, + pool_id: int, + status_id: int, + quota_auto: int, + quota_fast: int, + quota_expert: int, + quota_heavy: int, + quota_grok_4_3: int, + quota_console: int, + total_auto: int, + total_fast: int, + total_expert: int, + total_heavy: int, + total_grok_4_3: int, + total_console: int, + window_auto: int, + window_fast: int, + window_expert: int, + window_heavy: int, + window_grok_4_3: int, + window_console: int, + reset_auto: int, + reset_fast: int, + reset_expert: int, + reset_heavy: int, + reset_grok_4_3: int, + reset_console: int, + health: float, + last_use_s: int, + last_fail_s: int, + fail_count: int, + tags: list[str], + ) -> int: + idx = len(self.token_by_idx) + self.token_by_idx.append(token) + self.idx_by_token[token] = idx + self.pool_by_idx.append(pool_id) + self.status_by_idx.append(status_id) + self.quota_auto_by_idx.append(max(-1, min(quota_auto, 32767))) + self.quota_fast_by_idx.append(max(-1, min(quota_fast, 32767))) + self.quota_expert_by_idx.append(max(-1, min(quota_expert, 32767))) + self.quota_heavy_by_idx.append(max(-1, min(quota_heavy, 32767))) + self.quota_grok_4_3_by_idx.append(max(-1, min(quota_grok_4_3, 32767))) + self.quota_console_by_idx.append(max(-1, min(quota_console, 32767))) + self.total_auto_by_idx.append(max(0, min(total_auto, 32767))) + self.total_fast_by_idx.append(max(0, min(total_fast, 32767))) + self.total_expert_by_idx.append(max(0, min(total_expert, 32767))) + self.total_heavy_by_idx.append(max(0, min(total_heavy, 32767))) + self.total_grok_4_3_by_idx.append(max(0, min(total_grok_4_3, 32767))) + self.total_console_by_idx.append(max(0, min(total_console, 32767))) + self.window_auto_by_idx.append(max(0, window_auto)) + self.window_fast_by_idx.append(max(0, window_fast)) + self.window_expert_by_idx.append(max(0, window_expert)) + self.window_heavy_by_idx.append(max(0, window_heavy)) + self.window_grok_4_3_by_idx.append(max(0, window_grok_4_3)) + self.window_console_by_idx.append(max(0, window_console)) + self.reset_auto_at_by_idx.append(reset_auto) + self.reset_fast_at_by_idx.append(reset_fast) + self.reset_expert_at_by_idx.append(reset_expert) + self.reset_heavy_at_by_idx.append(reset_heavy) + self.reset_grok_4_3_at_by_idx.append(reset_grok_4_3) + self.reset_console_at_by_idx.append(reset_console) + self.inflight_by_idx.append(0) + self.fail_count_by_idx.append(min(fail_count, 65535)) + self.health_by_idx.append(health) + self.last_use_at_by_idx.append(last_use_s) + self.last_fail_at_by_idx.append(last_fail_s) + self.cooling_until_s_by_idx.append(0) + self.size += 1 + self._add_to_indexes(idx) + self._add_to_tag_idx(idx, tags) + return idx + + # --------------------------------------------------------------------------- + # Slot update (used during incremental sync) + # --------------------------------------------------------------------------- + + def _update_slot( + self, + idx: int, + pool_id: int, + status_id: int, + quota_auto: int, + quota_fast: int, + quota_expert: int, + quota_heavy: int, + quota_grok_4_3: int, + quota_console: int, + total_auto: int, + total_fast: int, + total_expert: int, + total_heavy: int, + total_grok_4_3: int, + total_console: int, + window_auto: int, + window_fast: int, + window_expert: int, + window_heavy: int, + window_grok_4_3: int, + window_console: int, + reset_auto: int, + reset_fast: int, + reset_expert: int, + reset_heavy: int, + reset_grok_4_3: int, + reset_console: int, + health: float, + last_use_s: int, + last_fail_s: int, + fail_count: int, + old_tags: list[str], + new_tags: list[str], + ) -> None: + self._remove_from_indexes(idx) + self._remove_from_tag_idx(idx, old_tags) + + self.pool_by_idx[idx] = pool_id + self.status_by_idx[idx] = status_id + self.quota_auto_by_idx[idx] = max(-1, min(quota_auto, 32767)) + self.quota_fast_by_idx[idx] = max(-1, min(quota_fast, 32767)) + self.quota_expert_by_idx[idx] = max(-1, min(quota_expert, 32767)) + self.quota_heavy_by_idx[idx] = max(-1, min(quota_heavy, 32767)) + self.quota_grok_4_3_by_idx[idx] = max(-1, min(quota_grok_4_3, 32767)) + self.quota_console_by_idx[idx] = max(-1, min(quota_console, 32767)) + self.total_auto_by_idx[idx] = max(0, min(total_auto, 32767)) + self.total_fast_by_idx[idx] = max(0, min(total_fast, 32767)) + self.total_expert_by_idx[idx] = max(0, min(total_expert, 32767)) + self.total_heavy_by_idx[idx] = max(0, min(total_heavy, 32767)) + self.total_grok_4_3_by_idx[idx] = max(0, min(total_grok_4_3, 32767)) + self.total_console_by_idx[idx] = max(0, min(total_console, 32767)) + self.window_auto_by_idx[idx] = max(0, window_auto) + self.window_fast_by_idx[idx] = max(0, window_fast) + self.window_expert_by_idx[idx] = max(0, window_expert) + self.window_heavy_by_idx[idx] = max(0, window_heavy) + self.window_grok_4_3_by_idx[idx] = max(0, window_grok_4_3) + self.window_console_by_idx[idx] = max(0, window_console) + self.reset_auto_at_by_idx[idx] = reset_auto + self.reset_fast_at_by_idx[idx] = reset_fast + self.reset_expert_at_by_idx[idx] = reset_expert + self.reset_heavy_at_by_idx[idx] = reset_heavy + self.reset_grok_4_3_at_by_idx[idx] = reset_grok_4_3 + self.reset_console_at_by_idx[idx] = reset_console + self.fail_count_by_idx[idx] = min(fail_count, 65535) + self.last_use_at_by_idx[idx] = last_use_s + self.last_fail_at_by_idx[idx] = last_fail_s + # health is not reset on update + + self._add_to_indexes(idx) + self._add_to_tag_idx(idx, new_tags) + + # --------------------------------------------------------------------------- + # Public read accessors + # --------------------------------------------------------------------------- + + def get_token(self, idx: int) -> str: + return self.token_by_idx[idx] + + def get_pool_id(self, idx: int) -> int: + return int(self.pool_by_idx[idx]) + + def quota_for(self, idx: int, mode_id: int) -> int: + return int(self._quota_col(mode_id)[idx]) + + def is_active(self, idx: int) -> bool: + return int(self.status_by_idx[idx]) == int(StatusId.ACTIVE) + + def iter_live_indices(self) -> Iterator[int]: + for idx in range(len(self.token_by_idx)): + if int(self.status_by_idx[idx]) != int(StatusId.DELETED): + yield idx + + +def make_empty_table() -> AccountRuntimeTable: + """Return a freshly initialised (empty) runtime table.""" + return AccountRuntimeTable() + + +__all__ = ["AccountRuntimeTable", "make_empty_table"] diff --git a/app/dataplane/proxy/__init__.py b/app/dataplane/proxy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33dfbb6e90ece4485897ed06b3bd1b224e51ed42 --- /dev/null +++ b/app/dataplane/proxy/__init__.py @@ -0,0 +1,55 @@ +"""ProxyRuntime — thin hot-path wrapper around ProxyDirectory. + +Delegates acquisition and feedback to the control-plane ProxyDirectory. +Kept as a thin shim so callers in the dataplane need not import control +modules directly. +""" + +from app.control.proxy import ProxyDirectory, get_proxy_directory +from app.control.proxy.models import ( + ProxyLease, ProxyFeedback, ProxyScope, RequestKind, +) + + +class ProxyRuntime: + """Hot-path facade around ProxyDirectory.""" + + def __init__(self, directory: ProxyDirectory) -> None: + self._dir = directory + + async def acquire( + self, + *, + scope: ProxyScope = ProxyScope.APP, + kind: RequestKind = RequestKind.HTTP, + resource: bool = False, + clearance_origin: str | None = None, + ) -> ProxyLease: + return await self._dir.acquire( + scope=scope, + kind=kind, + resource=resource, + clearance_origin=clearance_origin, + ) + + async def feedback(self, lease: ProxyLease, result: ProxyFeedback) -> None: + await self._dir.feedback(lease, result) + + @property + def has_proxy(self) -> bool: + from app.control.proxy.models import EgressMode + return self._dir.egress_mode != EgressMode.DIRECT + + +_runtime: ProxyRuntime | None = None + + +async def get_proxy_runtime() -> ProxyRuntime: + global _runtime + directory = await get_proxy_directory() + if _runtime is None: + _runtime = ProxyRuntime(directory) + return _runtime + + +__all__ = ["ProxyRuntime", "get_proxy_runtime"] diff --git a/app/dataplane/proxy/adapters/__init__.py b/app/dataplane/proxy/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..932c7c31d40e3ba2306a6e64a7ad2ea68eb1bcca --- /dev/null +++ b/app/dataplane/proxy/adapters/__init__.py @@ -0,0 +1,7 @@ +from .headers import build_http_headers, build_sso_cookie, build_ws_headers +from .session import ResettableSession, build_session_kwargs, normalize_proxy_url + +__all__ = [ + "build_http_headers", "build_sso_cookie", "build_ws_headers", + "ResettableSession", "build_session_kwargs", "normalize_proxy_url", +] diff --git a/app/dataplane/proxy/adapters/headers.py b/app/dataplane/proxy/adapters/headers.py new file mode 100644 index 0000000000000000000000000000000000000000..8f47430c736013343c94819db2ed5065d0e4c0f7 --- /dev/null +++ b/app/dataplane/proxy/adapters/headers.py @@ -0,0 +1,360 @@ +"""HTTP/WebSocket header builders for reverse-proxy requests. + +All values are sanitized to ASCII-safe Latin-1 before use. +""" + +import base64 +import random +import re +import string +import uuid +from typing import Optional +from urllib.parse import urlparse + + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.control.proxy.models import ProxyLease +from app.dataplane.proxy.adapters.profile import ProxyProfile, resolve_proxy_profile + +# --------------------------------------------------------------------------- +# Unicode → ASCII normalisation map +# --------------------------------------------------------------------------- + +_CHAR_MAP = str.maketrans( + { + "\u2010": "-", + "\u2011": "-", + "\u2012": "-", + "\u2013": "-", + "\u2014": "-", + "\u2212": "-", + "\u2018": "'", + "\u2019": "'", + "\u201c": '"', + "\u201d": '"', + "\u00a0": " ", + "\u2007": " ", + "\u202f": " ", + "\u200b": "", + "\u200c": "", + "\u200d": "", + "\ufeff": "", + } +) + + +def _sanitize(value: Optional[str], *, field: str, strip_spaces: bool = False) -> str: + raw = "" if value is None else str(value) + out = raw.translate(_CHAR_MAP) + out = re.sub(r"\s+", "", out) if strip_spaces else out.strip() + out = out.encode("latin-1", errors="ignore").decode("latin-1") + if out != raw: + logger.debug( + "header sanitized: field={} original_len={} sanitized_len={}", + field, + len(raw), + len(out), + ) + return out + + +# --------------------------------------------------------------------------- +# Statsig / request-id generation +# --------------------------------------------------------------------------- + + +def _statsig_id() -> str: + cfg = get_config() + if cfg.get_bool("features.dynamic_statsig", False): + if random.choice((True, False)): + rand = "".join(random.choices(string.ascii_lowercase + string.digits, k=5)) + msg = f"x1:TypeError: Cannot read properties of null (reading 'children['{rand}']')" + else: + rand = "".join(random.choices(string.ascii_lowercase, k=10)) + msg = f"x1:TypeError: Cannot read properties of undefined (reading '{rand}')" + return base64.b64encode(msg.encode()).decode() + return ( + "ZTpUeXBlRXJyb3I6IENhbm5vdCByZWFkIHByb3BlcnRpZXMgb2YgdW5kZWZpbmVkIChyZWFkaW5nICdjaGls" + "ZE5vZGVzJyk=" + ) + + +# --------------------------------------------------------------------------- +# Client-hints helpers +# --------------------------------------------------------------------------- + + +def _major_version(browser: Optional[str], ua: Optional[str]) -> Optional[str]: + for src in (browser or "", ua or ""): + m = re.search(r"(\d{2,3})", src) + if m: + return m.group(1) + return None + + +def _platform(ua: str) -> Optional[str]: + u = ua.lower() + if "windows" in u: + return "Windows" + if "mac os x" in u or "macintosh" in u: + return "macOS" + if "android" in u: + return "Android" + if "iphone" in u or "ipad" in u: + return "iOS" + if "linux" in u: + return "Linux" + return None + + +def _arch(ua: str) -> Optional[str]: + u = ua.lower() + if "aarch64" in u or "arm" in u: + return "arm" + if "x86_64" in u or "x64" in u or "win64" in u or "intel" in u: + return "x86" + return None + + +def _client_hints(browser: Optional[str], ua: Optional[str]) -> dict[str, str]: + b = (browser or "").lower() + u = (ua or "").lower() + is_chromium = any(k in b for k in ("chrome", "chromium", "edge", "brave")) or any( + k in u for k in ("chrome", "chromium", "edg") + ) + if not is_chromium or "firefox" in u or ("safari" in u and "chrome" not in u): + return {} + ver = _major_version(browser, ua) + if not ver: + return {} + if "edge" in b or "edg" in u: + brand = "Microsoft Edge" + elif "brave" in b: + brand = "Brave" + elif "chromium" in b: + brand = "Chromium" + else: + brand = "Google Chrome" + + sec_ch_ua = f'"{brand}";v="{ver}", "Chromium";v="{ver}", "Not(A:Brand";v="24"' + plat = _platform(ua or "") + arch = _arch(ua or "") + mobile = "?1" if ("mobile" in u or plat in ("Android", "iOS")) else "?0" + + hints: dict[str, str] = { + "Sec-Ch-Ua": sec_ch_ua, + "Sec-Ch-Ua-Mobile": mobile, + "Sec-Ch-Ua-Model": "", + } + if plat: + hints["Sec-Ch-Ua-Platform"] = f'"{plat}"' + if arch: + hints["Sec-Ch-Ua-Arch"] = arch + hints["Sec-Ch-Ua-Bitness"] = "64" + return hints + + +# --------------------------------------------------------------------------- +# Lease resolution +# --------------------------------------------------------------------------- + + +def _resolve_profile(lease: ProxyLease | None) -> ProxyProfile: + return resolve_proxy_profile(lease) + + +# --------------------------------------------------------------------------- +# Public builders +# --------------------------------------------------------------------------- + + +def build_sso_cookie( + sso_token: str, + *, + lease: ProxyLease | None = None, + cf_cookies: str | None = None, + cf_clearance: str | None = None, +) -> str: + """Build the Cookie header value for an SSO-authenticated request. + + When *cf_clearance* is not provided, the value is resolved from the lease's + cf_cookies profile or falls back to the config's cf_clearance (supporting + both ``proxy.clearance.cf_clearance`` and legacy ``proxy.cf_clearance`` paths). + Historical bug: earlier v2.0 releases silently defaulted cf_clearance to the + empty string when not passed explicitly, causing Cookies without a CF + clearance token and immediate 403 from Cloudflare on every grok.com call. + """ + tok = sso_token[4:] if sso_token.startswith("sso=") else sso_token + tok = _sanitize(tok, field="sso_token", strip_spaces=True) + + cookie = f"sso={tok}; sso-rw={tok}" + profile = _resolve_profile(lease) + eff_cookies = _sanitize( + cf_cookies if cf_cookies is not None else profile.cf_cookies, field="cf_cookies" + ) + eff_clearance = _sanitize( + cf_clearance if cf_clearance is not None else profile.cf_clearance, + field="cf_clearance", + strip_spaces=True, + ) + + if eff_clearance and eff_cookies: + if re.search(r"(?:^|;\s*)cf_clearance=", eff_cookies): + eff_cookies = re.sub( + r"(^|;\s*)cf_clearance=[^;]*", + r"\1cf_clearance=" + eff_clearance, + eff_cookies, + count=1, + ) + else: + eff_cookies = f"{eff_cookies.rstrip('; ')}; cf_clearance={eff_clearance}" + elif eff_clearance: + eff_cookies = f"cf_clearance={eff_clearance}" + + if eff_cookies: + cookie += f"; {eff_cookies}" + return cookie + + +def build_http_headers( + cookie_token: str, + *, + content_type: Optional[str] = None, + origin: Optional[str] = None, + referer: Optional[str] = None, + lease: ProxyLease | None = None, +) -> dict[str, str]: + """Build headers for a standard HTTP reverse-proxy request.""" + profile = _resolve_profile(lease) + raw_ua = profile.user_agent + ua = _sanitize(raw_ua, field="user_agent") + browser = profile.browser + org = _sanitize(origin or "https://grok.com", field="origin") + ref = _sanitize(referer or "https://grok.com/", field="referer") + + ct = content_type or "application/json" + if ct == "application/json": + accept = "*/*" + fd = "empty" + elif ct in ("image/jpeg", "image/png", "video/mp4", "video/webm"): + accept = ( + "text/html,application/xhtml+xml,application/xml;q=0.9," + "image/avif,image/webp,image/apng,*/*;q=0.8" + ) + fd = "document" + else: + accept = "*/*" + fd = "empty" + + org_host = urlparse(org).hostname + ref_host = urlparse(ref).hostname + site = "same-origin" if org_host and org_host == ref_host else "same-site" + + headers: dict[str, str] = { + "Accept": accept, + "Accept-Encoding": "gzip, deflate, br, zstd", + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Baggage": ( + "sentry-environment=production," + "sentry-release=d6add6fb0460641fd482d767a335ef72b9b6abb8," + "sentry-public_key=b311e0f2690c81f25e2c4cf6d4f7ce1c" + ), + "Content-Type": ct, + "Origin": org, + "Priority": "u=1, i", + "Referer": ref, + "Sec-Fetch-Dest": fd, + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": site, + "User-Agent": ua, + "x-statsig-id": _statsig_id(), + "x-xai-request-id": str(uuid.uuid4()), + } + headers.update(_client_hints(browser, raw_ua)) + headers["Cookie"] = build_sso_cookie(cookie_token, lease=lease) + + logger.debug("http headers built: header_count={}", len(headers)) + return headers + + +def build_ws_headers( + token: Optional[str] = None, + *, + origin: Optional[str] = None, + extra: Optional[dict[str, str]] = None, + lease: ProxyLease | None = None, +) -> dict[str, str]: + """Build headers for a WebSocket upgrade request.""" + profile = _resolve_profile(lease) + raw_ua = profile.user_agent + ua = _sanitize(raw_ua, field="user_agent") + browser = profile.browser + org = _sanitize(origin or "https://grok.com", field="origin") + + headers: dict[str, str] = { + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Cache-Control": "no-cache", + "Origin": org, + "Pragma": "no-cache", + "User-Agent": ua, + } + headers.update(_client_hints(browser, raw_ua)) + if token: + headers["Cookie"] = build_sso_cookie(token, lease=lease) + if extra: + headers.update(extra) + return headers + + +def build_console_headers( + sso_token: str, + *, + lease: ProxyLease | None = None, + content_type: str = "application/json", +) -> dict[str, str]: + """Build headers for console.x.ai/v1/responses requests. + + 抓包确认的认证方式: + - Authorization: Bearer anonymous (固定值) + - Cookie: sso=; sso-rw=; cf_clearance=... (身份 + CF clearance) + + cf_clearance 从 proxy lease 的 clearance profile 中获取(与 grok.com 共用同一套机制)。 + """ + tok = sso_token[4:] if sso_token.startswith("sso=") else sso_token + tok = _sanitize(tok, field="sso_token", strip_spaces=True) + + # 复用现有 clearance profile(cf_clearance / user_agent) + profile = _resolve_profile(lease) + ua = _sanitize(profile.user_agent, field="user_agent") + cf_clearance = _sanitize(profile.cf_clearance, field="cf_clearance", strip_spaces=True) + + cookie = f"sso={tok}; sso-rw={tok}" + if cf_clearance: + cookie += f"; cf_clearance={cf_clearance}" + + headers: dict[str, str] = { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate, br, zstd", + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Authorization": "Bearer anonymous", + "Content-Type": content_type, + "Cookie": cookie, + "Origin": "https://console.x.ai", + "Priority": "u=1, i", + "Referer": "https://console.x.ai/", + "Sec-Fetch-Dest": "empty", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": "same-origin", + "User-Agent": ua or ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/136.0.0.0 Safari/537.36" + ), + "x-cluster": "https://us-east-1.api.x.ai", + } + headers.update(_client_hints(profile.browser, profile.user_agent)) + return headers + + +__all__ = ["build_http_headers", "build_sso_cookie", "build_ws_headers", "build_console_headers"] diff --git a/app/dataplane/proxy/adapters/profile.py b/app/dataplane/proxy/adapters/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..20da9e6b60070a5c7bc43c21f1e69d8cba95f43c --- /dev/null +++ b/app/dataplane/proxy/adapters/profile.py @@ -0,0 +1,119 @@ +"""Shared Cloudflare proxy profile resolution.""" + +from dataclasses import dataclass +from functools import lru_cache +import re +from typing import get_args + +from app.control.proxy.config import resolve_clearance_config +from app.control.proxy.models import ProxyLease + + +@dataclass(frozen=True) +class ProxyProfile: + cf_cookies: str = "" + user_agent: str = "" + cf_clearance: str = "" + browser: str = "" + + +def extract_cookie_value(cookie_header: str, name: str) -> str: + if not cookie_header: + return "" + match = re.search(rf"(?:^|;\s*){re.escape(name)}=([^;]*)", cookie_header) + return match.group(1) if match else "" + + +@lru_cache(maxsize=1) +def _supported_browser_profiles() -> set[str]: + try: + from curl_cffi.requests.impersonate import BrowserTypeLiteral + + return {str(item) for item in get_args(BrowserTypeLiteral)} + except Exception: + return set() + + +def _supported_browser(candidate: str) -> str: + if not candidate: + return "" + supported = _supported_browser_profiles() + if not supported or candidate in supported: + return candidate + + family = re.match(r"[a-z_]+", candidate) + if family and family.group(0) in supported: + return family.group(0) + return "" + + +def browser_from_user_agent(user_agent: str) -> str: + ua = user_agent or "" + lower = ua.lower() + + firefox = re.search(r"firefox/(\d+)", lower) + if firefox: + return _supported_browser(f"firefox{firefox.group(1)}") or _supported_browser( + "firefox" + ) + + edge = re.search(r"edg/(\d+)", lower) + if edge: + return _supported_browser(f"edge{edge.group(1)}") or _supported_browser("edge") + + chrome = re.search(r"(?:chrome|chromium|crios)/(\d+)", lower) + if chrome: + suffix = "_android" if "android" in lower else "" + exact = _supported_browser(f"chrome{chrome.group(1)}{suffix}") + return exact or _supported_browser("chrome_android" if suffix else "chrome") + + safari = "safari/" in lower and "chrome/" not in lower and "chromium/" not in lower + if safari: + return _supported_browser( + "safari_ios" if ("iphone" in lower or "ipad" in lower) else "safari" + ) + + return "" + + +def resolve_proxy_profile(lease: ProxyLease | None) -> ProxyProfile: + """Resolve cookies, UA, clearance and curl_cffi browser from one source order. + + Flat legacy keys win over the nested v2 clearance keys because external + refresher sidecars write the flat values at runtime. The resolved browser + is derived from the effective User-Agent first, keeping header UA, + client-hints and curl_cffi impersonation aligned. + """ + cfg = resolve_clearance_config() + + if lease is not None: + cookies = lease.cf_cookies or cfg.cf_cookies + user_agent = lease.user_agent or cfg.user_agent + clearance = ( + extract_cookie_value(lease.cf_cookies, "cf_clearance") or cfg.cf_clearance + ) + else: + cookies = cfg.cf_cookies + user_agent = cfg.user_agent + clearance = cfg.cf_clearance + + browser = ( + browser_from_user_agent(user_agent) + or _supported_browser(cfg.browser) + or "chrome120" + ) + + return ProxyProfile( + cf_cookies=cookies, + user_agent=user_agent, + cf_clearance=clearance, + browser=browser, + ) + + +__all__ = [ + "ProxyProfile", + "browser_from_user_agent", + "extract_cookie_value", + "resolve_proxy_profile", +] diff --git a/app/dataplane/proxy/adapters/session.py b/app/dataplane/proxy/adapters/session.py new file mode 100644 index 0000000000000000000000000000000000000000..fb5c3b0418b0797039a79e5cd7c5afd936bd0c11 --- /dev/null +++ b/app/dataplane/proxy/adapters/session.py @@ -0,0 +1,169 @@ +"""curl_cffi session builder for reverse-proxy requests.""" + +import asyncio +from typing import Any +from urllib.parse import urlparse + +from curl_cffi.const import CurlOpt + +from app.platform.config.snapshot import get_config +from app.platform.errors import UpstreamError +from app.control.proxy.models import ProxyLease +from app.dataplane.proxy.adapters.profile import resolve_proxy_profile + + +def _skip_proxy_ssl(proxy_url: str) -> bool: + if not proxy_url: + return False + cfg = get_config() + return cfg.get_bool("proxy.egress.skip_ssl_verify", False) + + +def normalize_proxy_url(url: str) -> str: + """Normalize SOCKS schemes for consistent DNS-over-proxy behaviour.""" + if not url: + return url + scheme = urlparse(url).scheme.lower() + if scheme == "socks": + return "socks5h://" + url[len("socks://") :] + if scheme == "socks5": + return "socks5h://" + url[len("socks5://") :] + if scheme == "socks4": + return "socks4a://" + url[len("socks4://") :] + return url + + +def build_session_kwargs( + *, + lease: ProxyLease | None = None, + browser_override: str | None = None, + extra: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Build kwargs suitable for ``curl_cffi.requests.AsyncSession``.""" + kwargs: dict[str, Any] = dict(extra or {}) + + # Browser impersonation. + if not kwargs.get("impersonate"): + browser = browser_override or resolve_proxy_profile(lease).browser + if browser: + kwargs["impersonate"] = browser + + # Proxy URL. + proxy_url = "" + if lease is not None and lease.proxy_url: + proxy_url = normalize_proxy_url(lease.proxy_url) + scheme = urlparse(proxy_url).scheme.lower() + if scheme.startswith("socks"): + kwargs.setdefault("proxy", proxy_url) + else: + kwargs.setdefault("proxies", {"http": proxy_url, "https": proxy_url}) + + # curl SSL options for proxy. + if _skip_proxy_ssl(proxy_url): + opts = dict(kwargs.get("curl_options") or {}) + opts[CurlOpt.PROXY_SSL_VERIFYPEER] = 0 + opts[CurlOpt.PROXY_SSL_VERIFYHOST] = 0 + kwargs["curl_options"] = opts + + return kwargs + + +def _wrap_transport_error(exc: BaseException) -> UpstreamError: + if isinstance(exc, UpstreamError): + return exc + body = str(exc).replace("\n", "\\n")[:400] + return UpstreamError( + f"Transport request failed: {exc}", + status=502, + body=body, + ) + + +class ResettableSession: + """AsyncSession wrapper that resets connection on configurable status codes. + + Designed for long-lived hot-path use; session is recreated transparently + when a reset-triggering status code is received. + """ + + def __init__( + self, + *, + lease: ProxyLease | None = None, + browser_override: str | None = None, + reset_on_status: set[int] | None = None, + **session_kwargs: Any, + ) -> None: + self._kwargs = build_session_kwargs( + lease=lease, + browser_override=browser_override, + extra=session_kwargs or None, + ) + if reset_on_status is None: + codes = get_config().get_list("retry.reset_session_status_codes", [403]) + reset_on_status = {int(c) for c in codes} + self._reset_on = reset_on_status + self._reset_pending = False + self._lock = asyncio.Lock() + self._session = self._create() + + def _create(self): + from curl_cffi.requests import AsyncSession + + return AsyncSession(**self._kwargs) + + async def _maybe_reset(self) -> None: + if not self._reset_pending: + return + async with self._lock: + if not self._reset_pending: + return + self._reset_pending = False + old, self._session = self._session, self._create() + try: + await old.close() + except Exception: + pass + + async def _request(self, method: str, *args: Any, **kwargs: Any): + await self._maybe_reset() + try: + response = await getattr(self._session, method)(*args, **kwargs) + except Exception as exc: + self._reset_pending = True + raise _wrap_transport_error(exc) from exc + if self._reset_on and response.status_code in self._reset_on: + self._reset_pending = True + return response + + async def get(self, *args: Any, **kwargs: Any): + return await self._request("get", *args, **kwargs) + + async def post(self, *args: Any, **kwargs: Any): + return await self._request("post", *args, **kwargs) + + async def delete(self, *args: Any, **kwargs: Any): + return await self._request("delete", *args, **kwargs) + + async def close(self) -> None: + if self._session is not None: + try: + await self._session.close() + finally: + self._session = None # type: ignore[assignment] + + async def __aenter__(self) -> "ResettableSession": + return self + + async def __aexit__(self, *_: Any) -> None: + await self.close() + + def __getattr__(self, name: str) -> Any: + return getattr(self._session, name) + + +__all__ = [ + "ResettableSession", + "build_session_kwargs", + "normalize_proxy_url", +] diff --git a/app/dataplane/proxy/lease.py b/app/dataplane/proxy/lease.py new file mode 100644 index 0000000000000000000000000000000000000000..3437d73f65465f5e156f9ce9896c09ad569616b9 --- /dev/null +++ b/app/dataplane/proxy/lease.py @@ -0,0 +1,10 @@ +"""Proxy dataplane lease — re-export from control plane. + +ProxyLease is defined in ``app.control.proxy.models`` and used throughout +both control and dataplane layers. This module provides a canonical import +path within the dataplane package. +""" + +from app.control.proxy.models import ProxyLease + +__all__ = ["ProxyLease"] diff --git a/app/dataplane/proxy/selector.py b/app/dataplane/proxy/selector.py new file mode 100644 index 0000000000000000000000000000000000000000..3f4005a40757172d673dfc57727a76760890b614 --- /dev/null +++ b/app/dataplane/proxy/selector.py @@ -0,0 +1,39 @@ +"""Proxy dataplane selector — pick the best egress node from a ProxyRuntimeTable. + +Extracted from ProxyDirectory.acquire() to formalize the dataplane separation. +""" + +from app.control.proxy.models import ( + EgressMode, EgressNode, EgressNodeState, + ProxyScope, RequestKind, +) +from .table import ProxyRuntimeTable + + +def select_proxy( + table: ProxyRuntimeTable, + scope: ProxyScope = ProxyScope.APP, + kind: RequestKind = RequestKind.HTTP, +) -> str | None: + """Select a proxy URL from the table. + + Returns ``None`` for DIRECT mode or if no healthy nodes are available. + """ + if table.egress_mode == EgressMode.DIRECT: + return None + + if table.egress_mode == EgressMode.SINGLE_PROXY: + if table.nodes: + return table.nodes[0].proxy_url + return None + + # PROXY_POOL: pick the node with lowest inflight count. + healthy = table.healthy_nodes() + if not healthy: + return None + + best = min(healthy, key=lambda n: n.inflight) + return best.proxy_url + + +__all__ = ["select_proxy"] diff --git a/app/dataplane/proxy/table.py b/app/dataplane/proxy/table.py new file mode 100644 index 0000000000000000000000000000000000000000..3a83cb40d7ea4261de4c5d0549e1fac5c7343ae5 --- /dev/null +++ b/app/dataplane/proxy/table.py @@ -0,0 +1,56 @@ +"""Proxy dataplane table — runtime view of egress nodes and clearance bundles. + +Thin wrapper around ProxyDirectory's internal state, formalizing the +dataplane/control-plane boundary. The control-plane ProxyDirectory owns +mutation; this module provides a read-only snapshot for selector logic. +""" + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +from app.control.proxy.models import ( + EgressNode, ClearanceBundle, EgressMode, ClearanceMode, +) + +if TYPE_CHECKING: + from app.control.proxy import ProxyDirectory + +BundleKey = tuple[str, str] + + +@dataclass +class ProxyRuntimeTable: + """Read-only snapshot of proxy state for dataplane selection.""" + + egress_mode: EgressMode = EgressMode.DIRECT + clearance_mode: ClearanceMode = ClearanceMode.NONE + nodes: list[EgressNode] = field(default_factory=list) + bundles: dict[BundleKey, ClearanceBundle] = field(default_factory=dict) + + @property + def node_count(self) -> int: + return len(self.nodes) + + @property + def has_nodes(self) -> bool: + return len(self.nodes) > 0 + + def healthy_nodes(self) -> list[EgressNode]: + from app.control.proxy.models import EgressNodeState + return [n for n in self.nodes if n.state == EgressNodeState.HEALTHY] + + +def snapshot_from_directory(directory: "ProxyDirectory") -> ProxyRuntimeTable: + """Build a ProxyRuntimeTable from the current ProxyDirectory state. + + This is a point-in-time snapshot — not kept in sync automatically. + """ + return ProxyRuntimeTable( + egress_mode=directory.egress_mode, + clearance_mode=directory.clearance_mode, + nodes=directory.nodes, + bundles=directory.bundles, + ) + + +__all__ = ["ProxyRuntimeTable", "snapshot_from_directory"] diff --git a/app/dataplane/reverse/__init__.py b/app/dataplane/reverse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/dataplane/reverse/classifier.py b/app/dataplane/reverse/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..c2f7e7b84bc8b1bf108afb9e43696e5fbf54ea3a --- /dev/null +++ b/app/dataplane/reverse/classifier.py @@ -0,0 +1,55 @@ +"""Reverse pipeline result classifier. + +Maps upstream HTTP status codes and response bodies to a ResultCategory. +""" + +from typing import Any + +from app.dataplane.reverse.protocol.xai_usage import is_invalid_credentials_body + +from .types import ResultCategory + + +def classify_result( + status_code: int, + body: str = "", + *, + payload: Any = None, +) -> ResultCategory: + """Classify an upstream response into a ResultCategory. + + ``body`` is the raw response body (or first ~400 chars for error responses). + ``payload`` is the parsed JSON, if available. + """ + if status_code == 200: + return ResultCategory.SUCCESS + + if status_code == 429: + return ResultCategory.RATE_LIMITED + + if status_code == 401: + return ResultCategory.AUTH_FAILURE + + if status_code == 400 and is_invalid_credentials_body(body): + return ResultCategory.AUTH_FAILURE + + if status_code == 403: + # Known blocked/invalid account markers take precedence. + if is_invalid_credentials_body(body): + return ResultCategory.AUTH_FAILURE + # Check if the body indicates a Cloudflare challenge. + if body and ("cf-challenge" in body.lower() or "cloudflare" in body.lower()): + return ResultCategory.FORBIDDEN + # Generic 403 (suspension, WAF, etc.) — not a credential issue. + return ResultCategory.FORBIDDEN + + if status_code == 404: + return ResultCategory.NOT_FOUND + + if status_code >= 500: + return ResultCategory.UPSTREAM_5XX + + return ResultCategory.UNKNOWN + + +__all__ = ["classify_result"] diff --git a/app/dataplane/reverse/executor.py b/app/dataplane/reverse/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..e113614126a267aecc4e4119a9b1aaf8d29233a2 --- /dev/null +++ b/app/dataplane/reverse/executor.py @@ -0,0 +1,184 @@ +"""Reverse pipeline executor — the 7-step request lifecycle. + +Pipeline: plan → account → proxy → serialize → execute → classify → feedback + +This executor is opt-in. Existing products-layer code that calls transport +directly continues to work; the executor wraps the same pattern with +structured feedback and classification. +""" + +import asyncio +from typing import Any + +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_ms +from app.platform.errors import UpstreamError +from app.control.model.spec import ModelSpec +from app.dataplane.account import AccountDirectory, get_account_directory +from app.dataplane.account.lease import AccountLease +from app.dataplane.proxy import get_proxy_runtime + +from .types import ReversePlan, ReverseLeaseSet, ReverseResult, ResultCategory +from .planner import build_plan +from .classifier import classify_result +from .feedback import build_proxy_feedback + + +async def execute( + spec: ModelSpec, + request: dict[str, Any], + *, + payload_builder: Any | None = None, +) -> ReverseResult: + """Execute the full reverse pipeline for one request. + + Parameters + ---------- + spec : ModelSpec + The resolved model specification. + request : dict + The raw API request body. + payload_builder : callable, optional + ``(plan, token, request) → bytes`` — serializes the request into the + upstream payload format. If None, the request dict is JSON-encoded. + + Returns + ------- + ReverseResult + Classified outcome of the upstream call. + """ + t0 = now_ms() + + # Step 1: Plan + plan = build_plan(spec, request) + + # Step 2: Acquire account + directory = await get_account_directory() + + lease = await directory.reserve(plan.pool_candidates, plan.mode_id) + if lease is None: + return ReverseResult( + category=ResultCategory.RATE_LIMITED, + error="No available accounts", + latency_ms=int(now_ms() - t0), + ) + + # Step 3: Acquire proxy + proxy_runtime = await get_proxy_runtime() + proxy_lease = await proxy_runtime.acquire() + + leases = ReverseLeaseSet( + account_idx=lease.idx, + account_token=lease.token, + proxy_lease=proxy_lease, + ) + + # Step 4-5: Serialize + Execute + result = await _execute_transport(plan, leases, request, payload_builder) + result.latency_ms = int(now_ms() - t0) + + # Step 6: Classify (done inside _execute_transport) + + # Step 7: Feedback + release (fire-and-forget) + asyncio.create_task( + _apply_feedback_and_release(plan, leases, result, directory, lease), + ) + + return result + + +async def _execute_transport( + plan: ReversePlan, + leases: ReverseLeaseSet, + request: dict[str, Any], + payload_builder: Any | None, +) -> ReverseResult: + """Execute the transport call and classify the result.""" + try: + import orjson + + if payload_builder: + payload = payload_builder(plan, leases.account_token, request) + else: + payload = orjson.dumps(request) + + from app.dataplane.reverse.transport.http import post_json + + raw = await post_json( + plan.endpoint, + leases.account_token, + payload, + lease=leases.proxy_lease, + timeout_s=plan.timeout_s, + content_type=plan.content_type, + origin=plan.origin, + referer=plan.referer, + ) + category = classify_result(200) + return ReverseResult( + category=category, + status_code=200, + payload=raw, + ) + except UpstreamError as exc: + category = classify_result(exc.status, exc.details.get("body", "")) + return ReverseResult( + category=category, + status_code=exc.status, + body=exc.details.get("body", ""), + error=str(exc), + ) + except Exception as exc: + logger.error( + "reverse transport execution failed: error_type={} error={}", + type(exc).__name__, + exc, + ) + return ReverseResult( + category=ResultCategory.TRANSPORT_ERR, + error=str(exc), + ) + + +async def _apply_feedback_and_release( + plan: ReversePlan, + leases: ReverseLeaseSet, + result: ReverseResult, + directory: AccountDirectory, + account_lease: AccountLease, +) -> None: + """Apply account and proxy feedback, then release the lease (best-effort).""" + try: + # Release inflight counter. + await directory.release(account_lease) + + # Account feedback via the directory's feedback API. + from app.control.account.enums import FeedbackKind + + _CATEGORY_TO_FEEDBACK = { + ResultCategory.SUCCESS: FeedbackKind.SUCCESS, + ResultCategory.RATE_LIMITED: FeedbackKind.RATE_LIMITED, + ResultCategory.AUTH_FAILURE: FeedbackKind.UNAUTHORIZED, + ResultCategory.FORBIDDEN: FeedbackKind.FORBIDDEN, + ResultCategory.UPSTREAM_5XX: FeedbackKind.SERVER_ERROR, + ResultCategory.TRANSPORT_ERR: FeedbackKind.SERVER_ERROR, + ResultCategory.UNKNOWN: FeedbackKind.SERVER_ERROR, + } + fb_kind = _CATEGORY_TO_FEEDBACK.get(result.category) + if fb_kind is not None: + await directory.feedback( + leases.account_token, + fb_kind, + plan.mode_id, + ) + + # Proxy feedback. + if leases.proxy_lease: + proxy_fb = build_proxy_feedback(result) + proxy_runtime = await get_proxy_runtime() + await proxy_runtime.feedback(leases.proxy_lease, proxy_fb) + except Exception as exc: + logger.debug("reverse feedback update failed (non-fatal): error={}", exc) + + +__all__ = ["execute"] diff --git a/app/dataplane/reverse/feedback.py b/app/dataplane/reverse/feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9053e8bc5e15a71e208faaf4a959de46af0451 --- /dev/null +++ b/app/dataplane/reverse/feedback.py @@ -0,0 +1,84 @@ +"""Reverse pipeline feedback — translate ReverseResult into account + proxy feedback. + +Called after every upstream call to update account health/quota and proxy state. +""" + +from app.control.account.commands import AccountPatch +from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind +from app.platform.runtime.clock import now_ms +from .types import ResultCategory, ReverseResult + + +# --------------------------------------------------------------------------- +# Account feedback +# --------------------------------------------------------------------------- + +def build_account_feedback( + token: str, + result: ReverseResult, + *, + mode_id: int = 0, +) -> AccountPatch: + """Build an AccountPatch reflecting the outcome of a request. + + SUCCESS → increment use_count, update last_use_at + RATE_LIMITED → decrement quota for the mode + AUTH_FAILURE → increment fail_count, set last_fail_reason + Others → increment fail_count + """ + ts = now_ms() + + if result.category == ResultCategory.SUCCESS: + return AccountPatch( + token=token, + usage_use_delta=1, + last_use_at=ts, + ) + + if result.category == ResultCategory.RATE_LIMITED: + # Signal quota exhaustion for the specific mode. + quota_update: dict[str, dict] = {} + mode_key = {0: "quota_auto", 1: "quota_fast", 2: "quota_expert"}.get(mode_id) + if mode_key: + quota_update[mode_key] = {"remaining": 0} + return AccountPatch( + token=token, + usage_fail_delta=1, + last_fail_at=ts, + last_fail_reason=f"rate_limited (mode={mode_id})", + **({mode_key: quota_update[mode_key]} if mode_key and quota_update else {}), + ) + + return AccountPatch( + token=token, + usage_fail_delta=1, + last_fail_at=ts, + last_fail_reason=result.error or result.category.name, + ) + + +# --------------------------------------------------------------------------- +# Proxy feedback +# --------------------------------------------------------------------------- + +_CATEGORY_TO_PROXY: dict[ResultCategory, ProxyFeedbackKind] = { + ResultCategory.SUCCESS: ProxyFeedbackKind.SUCCESS, + ResultCategory.RATE_LIMITED: ProxyFeedbackKind.RATE_LIMITED, + ResultCategory.AUTH_FAILURE: ProxyFeedbackKind.UNAUTHORIZED, + ResultCategory.FORBIDDEN: ProxyFeedbackKind.CHALLENGE, + ResultCategory.UPSTREAM_5XX: ProxyFeedbackKind.UPSTREAM_5XX, + ResultCategory.TRANSPORT_ERR: ProxyFeedbackKind.TRANSPORT_ERROR, +} + + +def build_proxy_feedback(result: ReverseResult) -> ProxyFeedback: + """Build a ProxyFeedback from a ReverseResult.""" + kind = _CATEGORY_TO_PROXY.get(result.category, ProxyFeedbackKind.TRANSPORT_ERROR) + return ProxyFeedback( + kind=kind, + status_code=result.status_code, + reason=result.error, + ) + + +__all__ = ["build_account_feedback", "build_proxy_feedback"] diff --git a/app/dataplane/reverse/planner.py b/app/dataplane/reverse/planner.py new file mode 100644 index 0000000000000000000000000000000000000000..b034b9675195bf7c7f73a8794af8b497c8e91fa6 --- /dev/null +++ b/app/dataplane/reverse/planner.py @@ -0,0 +1,81 @@ +"""Reverse pipeline planner — build_plan() from model spec and request metadata. + +Determines the endpoint URL, transport kind, pool/mode IDs, and timeout +for a given operation. Does NOT execute anything — pure data transform. +""" + +from typing import Any + +from app.control.model.spec import ModelSpec +from app.dataplane.reverse.runtime.endpoint_table import ( + CHAT, MEDIA_POST, WS_IMAGINE, +) +from .types import ReversePlan, TransportKind + + +# --------------------------------------------------------------------------- +# Profile defaults (timeout / content-type per transport) +# --------------------------------------------------------------------------- + +_DEFAULTS: dict[TransportKind, dict[str, Any]] = { + TransportKind.HTTP_SSE: {"timeout_s": 120.0, "content_type": "application/json"}, + TransportKind.HTTP_JSON: {"timeout_s": 30.0, "content_type": "application/json"}, + TransportKind.WEBSOCKET: {"timeout_s": 300.0, "content_type": "application/json"}, + TransportKind.GRPC_WEB: {"timeout_s": 15.0, "content_type": "application/grpc-web+proto"}, +} + + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- + +def build_plan(spec: ModelSpec, request: dict[str, Any] | None = None) -> ReversePlan: + """Produce a ReversePlan for the given model spec. + + ``request`` is the raw API request body — used to refine the plan + (e.g. detect image-edit vs image-gen) but may be ``None``. + """ + endpoint, tkind = _resolve_endpoint(spec, request or {}) + defaults = _DEFAULTS.get(tkind, _DEFAULTS[TransportKind.HTTP_JSON]) + + return ReversePlan( + endpoint = endpoint, + transport_kind = tkind, + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + timeout_s = defaults["timeout_s"], + content_type = defaults["content_type"], + ) + + +# --------------------------------------------------------------------------- +# Internal routing logic +# --------------------------------------------------------------------------- + +def _resolve_endpoint( + spec: ModelSpec, + request: dict[str, Any], +) -> tuple[str, TransportKind]: + """Determine (endpoint_url, transport_kind) for the given capability.""" + + if spec.is_chat(): + return CHAT, TransportKind.HTTP_SSE + + if spec.is_image(): + return WS_IMAGINE, TransportKind.WEBSOCKET + + if spec.is_image_edit(): + return CHAT, TransportKind.HTTP_SSE + + if spec.is_video(): + return MEDIA_POST, TransportKind.HTTP_JSON + + if spec.is_voice(): + # LiveKit negotiation is HTTP JSON, actual voice is WebSocket. + return CHAT, TransportKind.HTTP_SSE + + # Fallback: treat as chat. + return CHAT, TransportKind.HTTP_SSE + + +__all__ = ["build_plan"] diff --git a/app/dataplane/reverse/protocol/__init__.py b/app/dataplane/reverse/protocol/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/dataplane/reverse/protocol/tool_parser.py b/app/dataplane/reverse/protocol/tool_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..4db4f281fe0e079732f708365333d813c5428f73 --- /dev/null +++ b/app/dataplane/reverse/protocol/tool_parser.py @@ -0,0 +1,264 @@ +"""Tool call parser — extract structured tool calls from model text output. + +Tries multiple formats in priority order: + 1. XML (canonical format we inject) + 2. JSON envelope {"tool_calls": [...]} + 3. JSON array [{"name": ..., "input": ...}] + 4. Alternative XML tags (, ) + +Returns a list of ParsedToolCall dataclasses. +""" + +from __future__ import annotations + +import json +import os +import re +import time +from dataclasses import dataclass, field +from typing import Any + + +# --------------------------------------------------------------------------- +# Data model +# --------------------------------------------------------------------------- + +@dataclass +class ParsedToolCall: + call_id: str + name: str + arguments: str # always a JSON string + + @staticmethod + def make(name: str, arguments: Any) -> "ParsedToolCall": + call_id = f"call_{int(time.time() * 1000)}{os.urandom(3).hex()}" + if isinstance(arguments, str): + args_str = arguments + else: + try: + args_str = json.dumps(arguments, ensure_ascii=False, separators=(",", ":")) + except (TypeError, ValueError): + args_str = "{}" + return ParsedToolCall(call_id=call_id, name=name, arguments=args_str) + + +@dataclass +class ParseResult: + calls: list[ParsedToolCall] = field(default_factory=list) + saw_tool_syntax: bool = False # detected XML/JSON envelope even if parsing failed + + +# --------------------------------------------------------------------------- +# Public entry point +# --------------------------------------------------------------------------- + +def parse_tool_calls( + text: str, + available_tools: list[str] | None = None, +) -> ParseResult: + """Parse tool calls from model-generated text. + + Args: + text: Full or partial model output text. + available_tools: If provided, only calls whose name appears in this + list are accepted (case-sensitive). + """ + result = ParseResult() + if not text or not text.strip(): + return result + + # Fast path: check whether tool-call syntax is present at all + if not _has_tool_syntax(text): + return result + result.saw_tool_syntax = True + + # Try parsers in priority order + calls = ( + _parse_xml_tool_calls(text) + or _parse_json_envelope(text) + or _parse_json_array(text) + or _parse_alt_xml(text) + ) + + if calls and available_tools: + calls = [c for c in calls if c.name in available_tools] + + result.calls = calls or [] + return result + + +# --------------------------------------------------------------------------- +# Syntax detection +# --------------------------------------------------------------------------- + +_TOOL_SYNTAX_PATTERNS = re.compile( + r" bool: + return bool(_TOOL_SYNTAX_PATTERNS.search(text)) + + +# --------------------------------------------------------------------------- +# Parser 1: XML (canonical) +# --------------------------------------------------------------------------- + +_XML_ROOT_RE = re.compile(r"(.*?)", re.DOTALL | re.IGNORECASE) +_XML_CALL_RE = re.compile(r"(.*?)", re.DOTALL | re.IGNORECASE) +_XML_NAME_RE = re.compile(r"(.*?)", re.DOTALL | re.IGNORECASE) +_XML_PARAMS_RE = re.compile(r"(.*?)", re.DOTALL | re.IGNORECASE) + + +def _parse_xml_tool_calls(text: str) -> list[ParsedToolCall]: + root_m = _XML_ROOT_RE.search(text) + if not root_m: + return [] + calls: list[ParsedToolCall] = [] + for call_m in _XML_CALL_RE.finditer(root_m.group(1)): + inner = call_m.group(1) + name_m = _XML_NAME_RE.search(inner) + params_m = _XML_PARAMS_RE.search(inner) + if not name_m: + continue + name = name_m.group(1).strip() + params = params_m.group(1).strip() if params_m else "{}" + parsed_args = _parse_json_tolerant(params) + if parsed_args is None: + continue + calls.append(ParsedToolCall.make(name, parsed_args)) + return calls + + +# --------------------------------------------------------------------------- +# Parser 2: {"tool_calls": [...]} JSON envelope +# --------------------------------------------------------------------------- + +def _parse_json_envelope(text: str) -> list[ParsedToolCall]: + # Only attempt if the text literally contains "tool_calls" key + if '"tool_calls"' not in text: + return [] + obj = _extract_outermost_json_obj(text) + if not isinstance(obj, dict): + return [] + raw_calls = obj.get("tool_calls") + if not isinstance(raw_calls, list): + return [] + return _extract_from_call_list(raw_calls) + + +_JSON_DECODER = json.JSONDecoder() + + +def _extract_outermost_json_obj(text: str) -> Any: + """Find and parse the first top-level JSON object in *text*. + + Uses JSONDecoder.raw_decode which handles the object boundary correctly + without a manual bracket-depth tracker. + """ + start = text.find("{") + if start == -1: + return None + try: + obj, _ = _JSON_DECODER.raw_decode(text, start) + return obj + except (json.JSONDecodeError, ValueError): + # Attempt repair on the substring from first '{' onward + end = text.rfind("}") + 1 + return _try_repair_json(text[start:end]) if end > start else None + + +# --------------------------------------------------------------------------- +# Parser 3: bare JSON array [{"name":..., "input":...}] +# --------------------------------------------------------------------------- + +_JSON_ARR_RE = re.compile(r"\[[\s\S]+\]", re.DOTALL) + +def _parse_json_array(text: str) -> list[ParsedToolCall]: + m = _JSON_ARR_RE.search(text) + if not m: + return [] + try: + arr = json.loads(m.group(0)) + except (json.JSONDecodeError, ValueError): + return [] + if not isinstance(arr, list): + return [] + return _extract_from_call_list(arr) + + +def _extract_from_call_list(items: list[Any]) -> list[ParsedToolCall]: + calls: list[ParsedToolCall] = [] + for item in items: + if not isinstance(item, dict): + continue + name = (item.get("name") or item.get("tool_name") or "").strip() + args = item.get("input") or item.get("arguments") or item.get("parameters") or {} + if not name: + continue + calls.append(ParsedToolCall.make(name, args)) + return calls + + +# --------------------------------------------------------------------------- +# Parser 4: alternative XML tags (, ) +# --------------------------------------------------------------------------- + +_FC_RE = re.compile(r"(.*?)", re.DOTALL | re.IGNORECASE) +_INVOKE_RE = re.compile(r'(.*?)', re.DOTALL | re.IGNORECASE) +_FC_NAME_RE = re.compile(r"(.*?)", re.DOTALL | re.IGNORECASE) +_FC_ARGS_RE = re.compile(r"(.*?)", re.DOTALL | re.IGNORECASE) + + +def _parse_alt_xml(text: str) -> list[ParsedToolCall]: + calls: list[ParsedToolCall] = [] + + # ...... + for m in _FC_RE.finditer(text): + inner = m.group(1) + name_m = _FC_NAME_RE.search(inner) + args_m = _FC_ARGS_RE.search(inner) + if not name_m: + continue + name = name_m.group(1).strip() + args = _parse_json_tolerant(args_m.group(1).strip() if args_m else "{}") + if args is None: + continue + calls.append(ParsedToolCall.make(name, args)) + + # ... + for m in _INVOKE_RE.finditer(text): + name = m.group(1).strip() + inner = m.group(2) + args = _parse_json_tolerant(inner.strip()) + if args is None: + args = {} + calls.append(ParsedToolCall.make(name, args)) + + return calls + + +# --------------------------------------------------------------------------- +# JSON helpers +# --------------------------------------------------------------------------- + +def _parse_json_tolerant(s: str) -> Any: + """Try to parse JSON; attempt light repair on failure.""" + if not s: + return {} + try: + return json.loads(s) + except (json.JSONDecodeError, ValueError): + repaired = _try_repair_json(s) + return repaired + + +def _try_repair_json(s: str) -> Any: + """Very lightweight JSON repair: fix unescaped newlines inside strings.""" + try: + # Replace literal newlines inside strings (common model output issue) + fixed = re.sub(r'(? must be a single-line valid JSON object (no line breaks inside). +- Place multiple tool calls inside ONE element. +- Do NOT use markdown code fences around the XML. +- Do NOT output any inner monologue or explanation alongside the XML. + + + + TOOL_NAME + {{"key": "value"}} + + + +WRONG (never do this): +```xml +... +``` +I'll call the search tool now. ... + +{tool_choice_instruction} +NOTE: Even if you believe you cannot fulfill the request, you must still follow the WHEN TO CALL rule above.\ +""" + +_CHOICE_AUTO = "WHEN TO CALL: Call a tool when it is clearly needed. Otherwise respond in plain text." +_CHOICE_NONE = "WHEN TO CALL: Do NOT call any tools. Respond in plain text only." +_CHOICE_REQUIRED = "WHEN TO CALL: You MUST output a XML block. Do NOT write any plain-text reply. If you are uncertain, still call the most relevant tool with your best guess at the parameters." +_CHOICE_FORCED = "WHEN TO CALL: You MUST output a XML block calling the tool named \"{name}\". Do NOT write any plain-text reply under any circumstances." + + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- + +def build_tool_system_prompt( + tools: list[dict[str, Any]], + tool_choice: Any = None, +) -> str: + """Return the full system-level instruction block to inject into the prompt. + + Args: + tools: OpenAI-format tool definitions (list of {type, function:{name,description,parameters}}). + tool_choice: OpenAI tool_choice value — "auto" | "none" | "required" | + {"type": "function", "function": {"name": "..."}} + """ + tool_defs = _format_tool_definitions(tools) + choice_instruction = _build_choice_instruction(tools, tool_choice) + return _TOOL_SYSTEM_HEADER.format( + tool_definitions=tool_defs, + tool_choice_instruction=choice_instruction, + ) + + +def extract_tool_names(tools: list[dict[str, Any]]) -> list[str]: + """Return the list of function names from an OpenAI tools array.""" + names: list[str] = [] + for tool in tools: + func = tool.get("function") or {} + name = func.get("name", "").strip() + if name: + names.append(name) + return names + + +def inject_into_message(message: str, system_prompt: str) -> str: + """Prepend the tool system prompt to the flattened message string.""" + return f"[system]: {system_prompt}\n\n{message}" + + +def tool_calls_to_xml(tool_calls: list[dict[str, Any]]) -> str: + """Convert an OpenAI tool_calls array back into the XML format we use in + prompts, so multi-turn conversations reconstruct context correctly.""" + lines = [""] + for tc in tool_calls: + func = tc.get("function") or {} + name = func.get("name", "") + args = func.get("arguments", "{}") + # Normalise to single-line JSON + try: + args = json.dumps(json.loads(args), ensure_ascii=False, separators=(",", ":")) + except (json.JSONDecodeError, ValueError, TypeError): + pass + lines.append(" ") + lines.append(f" {name}") + lines.append(f" {args}") + lines.append(" ") + lines.append("") + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Internals +# --------------------------------------------------------------------------- + +def _format_tool_definitions(tools: list[dict[str, Any]]) -> str: + parts: list[str] = [] + for tool in tools: + func = tool.get("function") or {} + name = func.get("name", "").strip() + desc = (func.get("description") or "").strip() + params = func.get("parameters") + + lines: list[str] = [] + lines.append(f"Tool: {name}") + if desc: + lines.append(f"Description: {desc}") + if params: + try: + lines.append(f"Parameters: {json.dumps(params, ensure_ascii=False)}") + except (TypeError, ValueError): + lines.append(f"Parameters: {params}") + parts.append("\n".join(lines)) + return "\n\n".join(parts) + + +def _build_choice_instruction( + tools: list[dict[str, Any]], + tool_choice: Any, +) -> str: + if tool_choice is None or tool_choice == "auto": + return _CHOICE_AUTO + if tool_choice == "none": + return _CHOICE_NONE + if tool_choice == "required": + return _CHOICE_REQUIRED + # Object form: {"type": "function", "function": {"name": "..."}} + if isinstance(tool_choice, dict): + tc_type = tool_choice.get("type", "") + if tc_type == "none": + return _CHOICE_NONE + if tc_type == "required": + return _CHOICE_REQUIRED + if tc_type == "function": + forced_name = (tool_choice.get("function") or {}).get("name", "").strip() + if forced_name: + return _CHOICE_FORCED.format(name=forced_name) + return _CHOICE_AUTO diff --git a/app/dataplane/reverse/protocol/xai_assets.py b/app/dataplane/reverse/protocol/xai_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..1438ee693c1808dae2d17955e26a34496b3a77d5 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_assets.py @@ -0,0 +1,81 @@ +"""XAI asset management protocol — list / delete / download endpoints. + +URL reference (from production reverse analysis): + list GET https://grok.com/rest/assets + delete DELETE https://grok.com/rest/assets-metadata/{asset_id} + download GET https://assets.grok.com/{path} (streaming) + +The app-chat upload endpoint is handled separately in transport/asset_upload.py. +""" + +import pathlib +import urllib.parse +from urllib.parse import urlparse + +ASSETS_LIST_URL = "https://grok.com/rest/assets" +ASSETS_DELETE_URL = "https://grok.com/rest/assets-metadata" # append /{asset_id} +ASSETS_DOWNLOAD_BASE = "https://assets.grok.com" + +# app-chat file management (used by asset_upload.py). +APP_CHAT_UPLOAD_URL = "https://grok.com/rest/app-chat/upload-file" + +# MIME type mapping used for download content-type inference. +_EXTENSION_MIME: dict[str, str] = { + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + ".webp": "image/webp", + ".mp4": "video/mp4", + ".webm": "video/webm", +} + +def asset_delete_url(asset_id: str) -> str: + return f"{ASSETS_DELETE_URL}/{asset_id}" + + +def resolve_download_url(file_path: str) -> tuple[str, str, str]: + """Resolve *file_path* to ``(url, origin, referer)``. + + *file_path* may be: + - a full ``https://assets.grok.com/...`` URL + - an absolute path ``/foo/bar.png`` + - a relative path ``foo/bar.png`` + """ + parsed = urlparse(file_path) + if parsed.scheme and parsed.netloc: + url = file_path + origin = f"{parsed.scheme}://{parsed.netloc}" + else: + path = file_path if file_path.startswith("/") else f"/{file_path}" + url = f"{ASSETS_DOWNLOAD_BASE}{path}" + origin = ASSETS_DOWNLOAD_BASE + return url, origin, f"{origin}/" + + +def infer_content_type(url: str) -> str | None: + """Return a best-guess MIME type for *url* based on file extension.""" + path = pathlib.Path(urllib.parse.urlparse(url).path) + return _EXTENSION_MIME.get(path.suffix.lower()) + + +def resolve_asset_reference( + file_id: str, + file_uri: str, + *, + user_id: str | None = None, +) -> str | None: + """Return the absolute asset content URL used by image-edit requests.""" + if file_uri: + url, _, _ = resolve_download_url(file_uri) + return url + if file_id and user_id: + return f"{ASSETS_DOWNLOAD_BASE}/users/{user_id}/{file_id}/content" + return None + + +__all__ = [ + "ASSETS_LIST_URL", "ASSETS_DELETE_URL", "ASSETS_DOWNLOAD_BASE", + "APP_CHAT_UPLOAD_URL", + "asset_delete_url", "resolve_download_url", "infer_content_type", + "resolve_asset_reference", +] diff --git a/app/dataplane/reverse/protocol/xai_auth.py b/app/dataplane/reverse/protocol/xai_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..8989cb1f40cea3ac742c5f135323a05e066f0410 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_auth.py @@ -0,0 +1,284 @@ +"""XAI auth protocol — accept ToS, NSFW controls, birth date. + +Each public function handles proxy acquisition, the upstream call, and +proxy feedback, returning a simple result or raising ``UpstreamError``. +""" + +import datetime +import random +from typing import TYPE_CHECKING + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import UpstreamError +from app.platform.net.grpc import GrpcClient, GrpcStatus +from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs +from app.dataplane.reverse.runtime.endpoint_table import ( + ACCEPT_TOS as ACCEPT_TOS_URL, + BASE as GROK_ORIGIN, + NSFW_MGMT as NSFW_MGMT_URL, + SET_BIRTH as SET_BIRTH_URL, +) +from app.dataplane.reverse.transport.grpc_web import post_grpc_web +from app.dataplane.reverse.transport.http import post_json + +if TYPE_CHECKING: + pass + +# ------------------------------------------------------------------ +# Endpoint URLs +# ------------------------------------------------------------------ + +ACCOUNTS_ORIGIN = "https://accounts.x.ai" + +# ------------------------------------------------------------------ +# Payload builders +# ------------------------------------------------------------------ + +def build_accept_tos_payload() -> bytes: + """gRPC-Web payload for SetTosAcceptedVersion (proto field 2 = true).""" + return GrpcClient.encode_payload(b"\x10\x01") + + +def build_nsfw_mgmt_payload(enabled: bool = True) -> bytes: + """gRPC-Web payload that sets always_show_nsfw_content to *enabled*.""" + name = b"always_show_nsfw_content" + inner = b"\x0a" + bytes([len(name)]) + name + protobuf = b"\x0a\x02\x10" + (b"\x01" if enabled else b"\x00") + b"\x12" + bytes([len(inner)]) + inner + return GrpcClient.encode_payload(protobuf) + + +def build_set_birth_payload() -> dict: + """JSON payload for /rest/auth/set-birth-date with a random adult birth date.""" + today = datetime.date.today() + birth_year = today.year - random.randint(20, 48) + birth_month = random.randint(1, 12) + birth_day = random.randint(1, 28) + hour = random.randint(0, 23) + minute = random.randint(0, 59) + second = random.randint(0, 59) + microsecond = random.randint(0, 999) + return { + "birthDate": ( + f"{birth_year:04d}-{birth_month:02d}-{birth_day:02d}" + f"T{hour:02d}:{minute:02d}:{second:02d}.{microsecond:03d}Z" + ) + } + +# ------------------------------------------------------------------ +# Transport helpers (manage proxy lifecycle internally) +# ------------------------------------------------------------------ + +async def _grpc_call( + url: str, + token: str, + payload: bytes, + *, + label: str, + origin: str = "https://grok.com", + referer: str = "https://grok.com/", + session: ResettableSession | None = None, + lease=None, +) -> GrpcStatus: + """POST a gRPC-Web frame and parse the status. + + When *session* and *lease* are both provided the caller manages the proxy + lifecycle (no acquire / feedback is done here). This allows multiple calls + to share one TCP connection and one proxy lease, avoiding repeated TLS + handshakes. + + When called without *session* / *lease* (the default) the function acquires + its own lease and manages proxy feedback, preserving the original behaviour. + """ + cfg = get_config() + timeout_s = cfg.get_float("nsfw.timeout", 30.0) + shared = session is not None and lease is not None + + if not shared: + proxy = await get_proxy_runtime() + lease = await proxy.acquire( + scope=ProxyScope.APP, + kind=RequestKind.HTTP, + clearance_origin=origin, + ) + + try: + _, trailers = await post_grpc_web( + url, token, payload, + lease=lease, timeout_s=timeout_s, origin=origin, referer=referer, + session=session, + ) + except UpstreamError as exc: + if not shared: + await proxy.feedback(lease, ProxyFeedback( + kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500 + else ProxyFeedbackKind.FORBIDDEN, + status_code=exc.status or 502, + )) + raise + except Exception as exc: + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + raise UpstreamError(f"{label}: transport error: {exc}") from exc + + status = GrpcClient.get_status(trailers) + if status.ok or status.code == -1: + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200)) + logger.debug("auth grpc call completed: label={} grpc_code={}", label, status.code) + else: + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.UPSTREAM_5XX, status_code=status.http_equiv)) + raise UpstreamError( + f"{label}: gRPC error code={status.code} message={status.message!r}", + status=status.http_equiv, + ) + + return status + + +# ------------------------------------------------------------------ +# Public API +# ------------------------------------------------------------------ + +async def accept_tos(token: str) -> GrpcStatus: + """Accept the ToS for *token* via gRPC-Web.""" + return await _grpc_call( + ACCEPT_TOS_URL, + token, + build_accept_tos_payload(), + label = "accept_tos", + origin = ACCOUNTS_ORIGIN, + referer = f"{ACCOUNTS_ORIGIN}/accept-tos", + ) + + +async def set_nsfw(token: str, enabled: bool) -> GrpcStatus: + """Set always_show_nsfw_content for *token* via gRPC-Web.""" + return await _grpc_call( + NSFW_MGMT_URL, + token, + build_nsfw_mgmt_payload(enabled), + label = "enable_nsfw" if enabled else "disable_nsfw", + origin = GROK_ORIGIN, + referer = f"{GROK_ORIGIN}/?_s=data", + ) + + +async def enable_nsfw(token: str) -> GrpcStatus: + """Enable always_show_nsfw_content for *token* via gRPC-Web.""" + return await set_nsfw(token, True) + + +async def disable_nsfw(token: str) -> GrpcStatus: + """Disable always_show_nsfw_content for *token* via gRPC-Web.""" + return await set_nsfw(token, False) + + +async def set_birth_date( + token: str, + session: ResettableSession | None = None, + lease=None, +) -> dict: + """Post a random adult birth date for *token* via REST. + + Accepts optional *session* / *lease* for connection reuse (see ``_grpc_call``). + """ + import orjson + + cfg = get_config() + timeout_s = cfg.get_float("nsfw.timeout", 30.0) + shared = session is not None and lease is not None + + if not shared: + proxy = await get_proxy_runtime() + lease = await proxy.acquire( + scope=ProxyScope.APP, + kind=RequestKind.HTTP, + clearance_origin=GROK_ORIGIN, + ) + + payload = orjson.dumps(build_set_birth_payload()) + try: + result = await post_json( + SET_BIRTH_URL, token, payload, + lease=lease, timeout_s=timeout_s, + origin=GROK_ORIGIN, referer=f"{GROK_ORIGIN}/?_s=data", + session=session, + ) + except UpstreamError as exc: + if not shared: + await proxy.feedback(lease, ProxyFeedback( + kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500 + else ProxyFeedbackKind.FORBIDDEN, + status_code=exc.status or 502, + )) + raise + except Exception as exc: + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + raise UpstreamError(f"set_birth_date: transport error: {exc}") from exc + + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200)) + logger.debug("auth birth date update completed") + return result + + +async def nsfw_sequence(token: str) -> None: + """Run accept_tos → set_birth_date → enable_nsfw. + + accept_tos runs against ``accounts.x.ai`` with its own host-specific + clearance. The grok.com birth-date and NSFW update steps still share one + session + lease to avoid an extra handshake per token. + """ + await accept_tos(token) + + proxy = await get_proxy_runtime() + lease = await proxy.acquire( + scope=ProxyScope.APP, + kind=RequestKind.HTTP, + clearance_origin=GROK_ORIGIN, + ) + + kwargs = build_session_kwargs(lease=lease) + try: + async with ResettableSession(**kwargs) as session: + try: + await set_birth_date(token, session=session, lease=lease) + except UpstreamError as exc: + # 429 with "birth-date-change-limit-reached" in the response body + # means the birth date is already set and locked — safe to skip + # and proceed to enable_nsfw. Any other 429 (true rate limit) or + # other status code is re-raised as a real failure. + body = exc.details.get("body", "") + if exc.status == 429 and "birth-date-change-limit-reached" in body: + logger.debug("auth birth date already set (locked), skipping: token={}...", token[:8]) + else: + raise + await _grpc_call( + NSFW_MGMT_URL, token, build_nsfw_mgmt_payload(), + label="enable_nsfw", origin=GROK_ORIGIN, referer=f"{GROK_ORIGIN}/?_s=data", + session=session, lease=lease, + ) + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200)) + logger.debug("auth nsfw sequence completed: token={}...", token[:8]) + except UpstreamError as exc: + await proxy.feedback(lease, ProxyFeedback( + kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500 + else ProxyFeedbackKind.FORBIDDEN, + status_code=exc.status or 502, + )) + raise + except Exception as exc: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + raise UpstreamError(f"nsfw_sequence: transport error: {exc}") from exc + + +__all__ = [ + "ACCEPT_TOS_URL", "NSFW_MGMT_URL", "SET_BIRTH_URL", + "build_accept_tos_payload", "build_nsfw_mgmt_payload", "build_set_birth_payload", + "accept_tos", "set_nsfw", "enable_nsfw", "disable_nsfw", "set_birth_date", "nsfw_sequence", +] diff --git a/app/dataplane/reverse/protocol/xai_chat.py b/app/dataplane/reverse/protocol/xai_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..2a43e14c0530d527c2c88ffa14da0836717b0716 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_chat.py @@ -0,0 +1,669 @@ +"""XAI app-chat protocol — payload builder and SSE stream adapter.""" + +import re +from dataclasses import dataclass +from typing import Any + +import orjson + +from app.platform.errors import UpstreamError +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.control.model.enums import ModeId +from app.dataplane.reverse.protocol.xai_chat_reasoning import ReasoningAggregator + + +def build_chat_payload( + *, + message: str, + mode_id: ModeId, + file_attachments: list[str] = (), + tool_overrides: dict[str, Any] | None = None, + model_config_override: dict[str, Any] | None = None, + request_overrides: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Build the JSON payload for POST /rest/app-chat/conversations/new.""" + cfg = get_config() + + payload: dict[str, Any] = { + "collectionIds": [], + "connectors": [], + "deviceEnvInfo": { + "darkModeEnabled": False, + "devicePixelRatio": 2, + "screenHeight": 1329, + "screenWidth": 2056, + "viewportHeight": 1083, + "viewportWidth": 2056, + }, + "disableMemory": not cfg.get_bool("features.memory", False), + "disableSearch": False, + "disableSelfHarmShortCircuit": False, + "disableTextFollowUps": False, + "enableImageGeneration": True, + "enableImageStreaming": True, + "enableSideBySide": True, + "fileAttachments": list(file_attachments), + "forceConcise": False, + "forceSideBySide": False, + "imageAttachments": [], + "imageGenerationCount": 2, + "isAsyncChat": False, + "message": message, + "modeId": mode_id.to_api_str(), + "responseMetadata": {}, + "returnImageBytes": False, + "returnRawGrokInXaiRequest": False, + "searchAllConnectors": False, + "sendFinalMetadata": True, + "temporary": cfg.get_bool("features.temporary", True), + "toolOverrides": tool_overrides or { + "gmailSearch": False, + "googleCalendarSearch": False, + "outlookSearch": False, + "outlookCalendarSearch": False, + "googleDriveSearch": False, + }, + } + + custom = cfg.get_str("features.custom_instruction", "").strip() + if custom: + payload["customPersonality"] = custom + + if model_config_override: + payload["responseMetadata"]["modelConfigOverride"] = model_config_override + + if request_overrides: + payload.update({k: v for k, v in request_overrides.items() if v is not None}) + + logger.debug( + "chat payload built: mode={} message_len={} file_count={}", + mode_id.to_api_str(), len(message), len(file_attachments), + ) + return payload + + +# --------------------------------------------------------------------------- +# SSE line classification (unchanged) +# --------------------------------------------------------------------------- + + +def classify_line(line: str | bytes) -> tuple[str, str]: + """Return (event_type, data) for a raw SSE line. + + event_type: 'data' | 'done' | 'skip' + + Handles both standard SSE ``data: {...}`` lines and raw JSON lines + (upstream sometimes omits the ``data:`` prefix). + """ + if isinstance(line, bytes): + line = line.decode("utf-8", "replace") + line = line.strip() + if not line: + return "skip", "" + if line.startswith("data:"): + data = line[5:].strip() + if data == "[DONE]": + return "done", "" + return "data", data + if line.startswith("event:"): + return "skip", "" + # Raw JSON line (no "data:" prefix) — treat as data. + if line.startswith("{"): + return "data", line + return "skip", "" + + +def stream_error_from_payload(obj: dict[str, Any]) -> UpstreamError | None: + """Convert upstream in-band stream error payloads to retryable errors.""" + error = obj.get("error") + if not isinstance(error, dict): + return None + + raw_message = error.get("message") or error.get("error") or "Upstream stream error" + message = str(raw_message) + code = error.get("code") + text = message.lower() + status = 429 if code == 8 or "too many requests" in text or "rate limit" in text else 502 + + try: + body = orjson.dumps(obj).decode() + except (TypeError, ValueError): + body = str(obj) + + return UpstreamError( + f"Upstream stream error: {message}", + status=status, + body=body[:400], + ) + + +def raise_for_stream_error(data: str | bytes | dict[str, Any]) -> None: + """Raise :class:`UpstreamError` for raw or decoded in-band stream errors.""" + if isinstance(data, dict): + obj = data + else: + try: + obj = orjson.loads(data) + except (orjson.JSONDecodeError, ValueError, TypeError): + return + if not isinstance(obj, dict): + return + exc = stream_error_from_payload(obj) + if exc is not None: + raise exc + + +# --------------------------------------------------------------------------- +# FrameEvent — single output event from StreamAdapter.feed() +# --------------------------------------------------------------------------- + +@dataclass(slots=True) +class FrameEvent: + """One parsed event produced by StreamAdapter.""" + + kind: str + """Event kind: + - ``text`` — cleaned final text token (content = token string) + - ``thinking`` — Grok main-model thinking (content = raw token) + - ``image`` — generated image final URL (content = full URL, image_id = upstream UUID) + - ``image_progress`` — generated image progress (content = percent string, image_id = upstream UUID) + - ``annotation`` — url citation annotation (annotation_data = annotation dict) + - ``soft_stop`` — stream end signal + - ``skip`` — filtered frame, do nothing + """ + content: str = "" + image_id: str = "" + rollout_id: str = "" + message_tag: str = "" + message_step_id: int | None = None + annotation_data: dict | None = None + + +# --------------------------------------------------------------------------- +# StreamAdapter — stateful SSE frame parser +# --------------------------------------------------------------------------- + +_GROK_RENDER_RE = re.compile( + r']*>.*?', + re.DOTALL, +) + +_IMAGE_BASE = "https://assets.grok.com/" + +# 工具使用卡片 → emoji 单行格式化映射(详细模式专用) +# 格式: tool_name → (emoji, (可展示的参数 key 列表)) +_TOOL_FMT: dict[str, tuple[str, tuple[str, ...]]] = { + "web_search": ("🔍", ("query", "q")), + "x_search": ("🔍", ("query",)), + "x_keyword_search": ("🔍", ("query",)), + "x_semantic_search": ("🔍", ("query",)), + "browse_page": ("🌐", ("url",)), + "search_images": ("🖼️", ("image_description", "imageDescription")), + "image_search": ("🖼️", ("image_description", "imageDescription")), + "chatroom_send": ("📋", ("message",)), + "code_execution": ("💻", ()), +} + + +class StreamAdapter: + """Parse upstream SSE frames and emit :class:`FrameEvent` objects. + + One instance per HTTP request. Call :meth:`feed` for every ``data:`` + line; iterate over the returned list of events. + """ + + __slots__ = ( + "_card_cache", + "_citation_order", + "_citation_map", + "_last_citation_index", + "_pending_citations", + "_annotations", + "_text_offset", + "_emitted_reasoning_keys", + "_reasoning", + "_summary_mode", + "_last_rollout", + "_content_started", + "_web_search_results", + "_web_search_urls_seen", + "thinking_buf", + "text_buf", + "image_urls", + ) + + def __init__(self) -> None: + self._card_cache: dict[str, dict] = {} + self._citation_order: list[str] = [] + self._citation_map: dict[str, int] = {} + self._last_citation_index: int = -1 + self._pending_citations: list[dict] = [] # _render_replace 产出的待定位引用 + self._annotations: list[dict] = [] # 已定位的完整 annotations(绝对位置) + self._text_offset: int = 0 # 累计文本长度(仅 text 事件) + self._emitted_reasoning_keys: set[str] = set() + # 思维链模式:精简摘要 / 详细原始流 + self._summary_mode: bool = get_config().get_bool("features.thinking_summary", False) + self._last_rollout: str = "" + self._content_started: bool = False + self._reasoning = ReasoningAggregator() if self._summary_mode else None + self._web_search_results: list[dict] = [] + self._web_search_urls_seen: set[str] = set() + self.thinking_buf: list[str] = [] + self.text_buf: list[str] = [] + self.image_urls: list[tuple[str, str]] = [] # [(url, imageUuid), ...] + + # 搜索信源追加:当配置启用且有 webSearchResults 时,格式化为 ## Sources 段落 + # 标记行 [grok2api-sources]: # 是 markdown link reference definition,渲染器不显示, + # 用于 _extract_message() 在多轮对话中精确识别并剥离前轮的 Sources 段落 + def references_suffix(self) -> str: + """当有搜索信源且配置启用时,格式化为 ## Sources markdown 段落。""" + if not self._web_search_results: + return "" + if not get_config().get_bool("features.show_search_sources", False): + return "" + lines = ["\n\n## Sources", "[grok2api-sources]: #"] + for item in self._web_search_results: + title = item.get("title") or item.get("url", "") + # 转义 Markdown 链接文本中的特殊字符,防止 []\ 打坏语法 + title = title.replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]") + lines.append(f"- [{title}]({item['url']})") + return "\n".join(lines) + "\n" + + # 内联引用 annotations:生成时同步构建,含绝对位置 + def annotations_list(self) -> list[dict]: + """已收集的 url_citation annotations(扁平格式,绝对位置)。无引用时返回 []。""" + return list(self._annotations) + + # 结构化搜索信源:始终输出(不受配置开关控制),供 search_sources 字段使用 + def search_sources_list(self) -> list[dict] | None: + """当有搜索信源时,返回结构化列表;无则返回 None。""" + if not self._web_search_results: + return None + return [ + { + "url": item["url"], + "title": item.get("title") or item.get("url", ""), + "type": item.get("type", "web"), + } + for item in self._web_search_results + ] + + # ------------------------------------------------------------------ + # Public API + # ------------------------------------------------------------------ + + def feed(self, data: str) -> list[FrameEvent]: + """Parse one JSON ``data:`` payload; return 0-N events.""" + try: + obj = orjson.loads(data) + except (orjson.JSONDecodeError, ValueError, TypeError): + return [] + raise_for_stream_error(obj) + + result = obj.get("result") + if not result: + return [] + resp = result.get("response") + if not resp: + return [] + + events: list[FrameEvent] = [] + + # ── cache every cardAttachment first ────────────────────── + card_raw = resp.get("cardAttachment") + if card_raw: + events.extend(self._handle_card(card_raw)) + + # ── 采集 webSearchResults(搜索信源,多帧累积去重)─────── + wsr = resp.get("webSearchResults") + if wsr and isinstance(wsr, dict): + for item in wsr.get("results", []): + if isinstance(item, dict) and item.get("url"): + url = item["url"] + if url not in self._web_search_urls_seen: + self._web_search_urls_seen.add(url) + self._web_search_results.append({**item, "type": "web"}) + + # ── 采集 xSearchResults(X/Twitter 帖子信源,多帧累积去重)── + xsr = resp.get("xSearchResults") + if xsr and isinstance(xsr, dict): + for item in xsr.get("results", []): + if isinstance(item, dict) and item.get("postId") and item.get("username"): + url = f"https://x.com/{item['username']}/status/{item['postId']}" + if url not in self._web_search_urls_seen: + self._web_search_urls_seen.add(url) + # 构造 title:归一化空白,text 为空退回 @username + # Markdown 转义统一在 references_suffix() 中处理 + raw = re.sub(r"\s+", " ", (item.get("text") or "")).strip() + if raw: + title = f"𝕏/@{item['username']}: {raw[:50]}{'...' if len(raw) > 50 else ''}" + else: + title = f"𝕏/@{item['username']}" + self._web_search_results.append({"url": url, "title": title, "type": "x_post"}) + + token = resp.get("token") + think = resp.get("isThinking") + tag = resp.get("messageTag") + rollout = resp.get("rolloutId") + step_id = resp.get("messageStepId") + + if tag == "tool_usage_card": + # 正文已开始后的迟到 tool card:静默丢弃 + if self._content_started: + return events + if self._summary_mode: + # 精简模式:走 ReasoningAggregator 提炼摘要 + for line in self._summarize_tool_usage_summary( + resp, rollout=rollout, step_id=step_id, + ): + self._append_reasoning( + events, line, + rollout=rollout, tag=tag, step_id=step_id, + ) + else: + # 详细模式:格式化为 emoji 单行(含 Agent 身份) + line = self._format_tool_card(resp, rollout=rollout) + if line: + # 同步 Agent 标识,确保后续 Grok summary 能正确插前缀 + if rollout: + self._last_rollout = rollout + self._append_reasoning( + events, line, + rollout=rollout, tag=tag, step_id=step_id, + ) + return events # card events (if any) already added + + # ── raw_function_result ─────────────────────────────────── + if tag == "raw_function_result": + return events + + # ── toolUsageCardId-only follow-up frame ────────────────── + if resp.get("toolUsageCardId") and not resp.get("webSearchResults") and not resp.get("codeExecutionResult"): + return events + + # ── 思维链 token 处理 ────────────────────────────────────── + if token is not None and think is True: + # 正文已开始后的迟到 thinking:写入 buf(非流式可用)但不发事件(流式不显示) + if self._content_started: + raw = str(token).strip() + if raw: + formatted = raw if raw.endswith("\n") else raw + "\n" + self.thinking_buf.append(formatted) + return events + if self._summary_mode: + # 精简模式:走 ReasoningAggregator 提炼摘要 + for line in self._reasoning.on_thinking( + str(token), tag=tag, rollout=rollout, + step_id=step_id if isinstance(step_id, int) else None, + ): + self._append_reasoning( + events, line, + rollout=rollout, tag=tag, step_id=step_id, + ) + else: + # 详细模式:Agent 切换时插入身份前缀,原始 token 直接透传 + raw = str(token) + # 去掉 Grok summary 自带的 "- " 前缀,避免触发 markdown 列表缩进 + if raw.startswith("- "): + raw = raw[2:] + if not raw: + return events + agent = rollout or "" + if agent and agent != self._last_rollout: + self._last_rollout = agent + # Agent 切换标识:绕过去重,直接写 buf + 发 event(同一 Agent 可多次出现) + header = f"\n[{agent}]\n" + self.thinking_buf.append(header) + events.append(FrameEvent( + "thinking", header, rollout_id=agent, + )) + self._append_reasoning( + events, raw, + rollout=rollout, tag=tag, step_id=step_id, + ) + return events + + # ── final text token (needs cleaning) ───────────────────── + if token is not None and think is not True and tag == "final": + self._content_started = True + cleaned, local_anns = self._clean_token(token) + if cleaned: + # 先发 text 事件(OpenAI 顺序:text.delta 先,annotation.added 后) + self.text_buf.append(cleaned) + events.append(FrameEvent("text", cleaned)) + # 再发 annotation 事件:局部位置 → 绝对位置 + for ann in local_anns: + ann["start_index"] = self._text_offset + ann.pop("local_start") + ann["end_index"] = self._text_offset + ann.pop("local_end") + self._annotations.append(ann) + events.append(FrameEvent("annotation", annotation_data=ann)) + self._text_offset += len(cleaned) + return events + + # ── end signals ─────────────────────────────────────────── + if resp.get("isSoftStop"): + self._flush_pending_reasoning(events) + events.append(FrameEvent("soft_stop")) + return events + + if resp.get("finalMetadata"): + self._flush_pending_reasoning(events) + events.append(FrameEvent("soft_stop")) + return events + + return events + + # ------------------------------------------------------------------ + # Card attachment handling + # ------------------------------------------------------------------ + + def _handle_card(self, card_raw: dict) -> list[FrameEvent]: + """Cache card data; emit image event on progress=100.""" + try: + jd = orjson.loads(card_raw["jsonData"]) + except (orjson.JSONDecodeError, ValueError, TypeError, KeyError): + return [] + + card_id = jd.get("id", "") + self._card_cache[card_id] = jd + + chunk = jd.get("image_chunk") + if chunk: + progress = chunk.get("progress") + uuid = chunk.get("imageUuid", "") + events: list[FrameEvent] = [] + try: + if progress is not None: + events.append(FrameEvent("image_progress", str(int(progress)), uuid)) + except (TypeError, ValueError): + pass + if chunk.get("progress") == 100 and not chunk.get("moderated"): + url = _IMAGE_BASE + chunk["imageUrl"] + self.image_urls.append((url, uuid)) + events.append(FrameEvent("image", url, uuid)) + return events + + return [] + + # ------------------------------------------------------------------ + # Token cleaning — → markdown + # ------------------------------------------------------------------ + + # 返回 (cleaned_text, local_annotations),annotations 含局部 start/end + def _clean_token(self, token: str) -> tuple[str, list[dict]]: + if " str: + card_id = m.group(1) + render_type = m.group(3) + card = self._card_cache.get(card_id) + if not card: + return "" + + if render_type == "render_searched_image": + img = card.get("image", {}) + title = img.get("title", "image") + thumb = img.get("thumbnail") or img.get("original", "") + link = img.get("link", "") + if link: + return f"[![{title}]({thumb})]({link})" + return f"![{title}]({thumb})" + + if render_type == "render_generated_image": + return "" # actual URL emitted by progress=100 card frame + + if render_type == "render_inline_citation": + url = card.get("url", "") + if not url: + return "" + index = self._citation_map.get(url) + if index is None: + self._citation_order.append(url) + index = len(self._citation_order) + self._citation_map[url] = index + # 连续相同引用去重 + if index == self._last_citation_index: + return "" + self._last_citation_index = index + citation_text = f" [[{index}]]({url})" + # 解析标题:card → webSearchResults → URL fallback + # Grok citation card 仅含 [id, type, cardType, url],无 title 字段 + title = card.get("title", "") + if not title: + for item in self._web_search_results: + if item.get("url") == url: + title = item.get("title", "") + break + # 记录引用元数据,位置在 _clean_token 返回后定位 + self._pending_citations.append({ + "url": url, + "title": title or url, + "needle": citation_text, + }) + return citation_text + + return "" + + def _append_reasoning( + self, + events: list[FrameEvent], + line: str, + *, + rollout: str | None, + tag: str | None, + step_id: Any, + ) -> None: + """将思维链文本追加到 thinking_buf 和事件列表(双模式去重)""" + if self._summary_mode: + # 精简模式:激进去重(移除标点/空格后比较) + text = line.strip() + if not text: + return + key = self._normalize_key(text) + else: + # 详细模式:精确去重(rollout + 原文) + text = line + if not text: + return + key = f"{rollout or ''}:{text}" + + if key in self._emitted_reasoning_keys: + return + self._emitted_reasoning_keys.add(key) + + # 统一用 \n 换行(去掉 "- " 前缀后不再有列表上下文,普通 \n 即可) + formatted = text if text.endswith("\n") else text + "\n" + self.thinking_buf.append(formatted) + events.append(FrameEvent( + "thinking", + formatted, + rollout_id=rollout or "", + message_tag=tag or "", + message_step_id=step_id if isinstance(step_id, int) else None, + )) + + def _flush_pending_reasoning(self, events: list[FrameEvent]) -> None: + """flush ReasoningAggregator 缓冲事件(仅精简模式有效)""" + if self._summary_mode and self._reasoning is not None: + for line in self._reasoning.finalize(): + self._append_reasoning(events, line, rollout="", tag="summary", step_id=None) + + @staticmethod + def _extract_tool_info(resp: dict[str, Any]) -> tuple[str, dict[str, Any]]: + """从 toolUsageCard 提取工具名(snake_case)和参数""" + card = resp.get("toolUsageCard") + if not isinstance(card, dict): + return "", {} + for key, value in card.items(): + if key == "toolUsageCardId" or not isinstance(value, dict): + continue + # camelCase → snake_case + tool_name = re.sub(r"(? list[str]: + tool_name, args = self._extract_tool_info(resp) + if not tool_name: + return [] + return self._reasoning.on_tool_usage(tool_name, args, rollout=rollout, step_id=step_id) + + # 详细模式:格式化为 emoji 单行(含 Agent 身份) + def _format_tool_card(self, resp: dict[str, Any], *, rollout: str | None) -> str: + tool_name, args = self._extract_tool_info(resp) + if not tool_name: + return "" + emoji, arg_keys = _TOOL_FMT.get(tool_name, ("🔧", ())) + # 提取要展示的参数值 + display_arg = "" + for ak in arg_keys: + val = args.get(ak) + if val: + display_arg = str(val).strip() + break + # 构造 Agent 前缀(不加前导 \n,由 _append_reasoning 统一处理换行) + prefix = f"[{rollout}] " if rollout else "" + if display_arg: + return f"{prefix}{emoji} {tool_name}: {display_arg}" + return f"{prefix}{emoji} {tool_name}" + + def _normalize_key(self, text: str) -> str: + lowered = text.lower() + lowered = re.sub(r"https?://\S+", "", lowered) + lowered = re.sub(r"[^\w\u4e00-\u9fff]+", "", lowered) + return lowered + + +__all__ = [ + "build_chat_payload", + "classify_line", + "FrameEvent", + "StreamAdapter", +] diff --git a/app/dataplane/reverse/protocol/xai_chat_reasoning.py b/app/dataplane/reverse/protocol/xai_chat_reasoning.py new file mode 100644 index 0000000000000000000000000000000000000000..3ddea7e55b48be6cefc10b04c85bb7c8c36c27a2 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_chat_reasoning.py @@ -0,0 +1,633 @@ +"""Reasoning normalization and aggregation for XAI app-chat streams.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any + + +_GENERIC_HEADERS = { + "", + "thinking about your request", +} + +_PROGRESSIVE_HINTS = ( + "正在", "准备", "计划", "查找", "搜索", "浏览", "确认", "核对", "整合", "挖掘", "比对", + "checking", "browsing", "verifying", "integrating", "digging", "cross-checking", "searching", "planning", +) + +_FINDING_HINTS = ( + "尚未", "已经", "已", "确认", "表明", "说明", "显示", "主要", "通常", "支持", "出现", "启动", + "持续", "提升", "更新", "灰度", "发布", "上线", "多模态", "视觉", "专家", "context", "token", + "参数", "每天", "大潮", "小潮", "半日潮", "引力", "周期", "模式", "confirmed", "launched", + "released", "rollout", "testing", "native multimodal", "widely believed", "latest", +) + +_LOW_VALUE_PREFIXES = ( + "用户", "user", "i can", "我可以", "我收集", "建议", "need", "需要", "应该", "since instructions", + "proposed", "mermaid", "可以用", "我建议", +) + +_TRACK_RULES: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("latest_updates", ("最新", "latest", "today", "recent", "最近", "update", "news", "本周", "4月", "april")), + ("release_status", ("release date", "released", "release", "launch", "上线", "发布", "正式发布", "current status")), + ("gray_rollout", ("灰度", "grayscale", "gray release", "灰度测试", "内测", "rollout")), + ("official_confirmation", ("official", "官网", "official site", "site:", "platform.deepseek.com", "deepseek.ai")), + ("ui_modes", ("vision", "视觉", "expert", "专家模式", "fast", "default", "ui", "界面", "mode")), + ("v4_lite", ("v4 lite", "sealion", "sealion-lite", "海狮")), + ("specs_architecture", ("specs", "parameters", "architecture", "engram", "mhc", "moe", "context", "benchmarks", "规格", "参数", "架构", "万亿")), + ("definition_basics", ("定义", "解释", "什么是", "what is", "phenomenon", "现象")), + ("causes_mechanism", ("成因", "原因", "cause", "causes", "gravity", "引力", "机制")), + ("categories_types", ("春潮", "小潮", "半日潮", "全日潮", "类型", "分类")), + ("impacts_applications", ("影响", "应用", "发电", "航运", "生活", "生态")), +) + +_ZH_LABELS = { + "understanding": "理解问题", + "scope": "检索范围", + "evidence": "核验与证据", + "finding": "关键发现", + "latest_updates": "最新动态", + "release_status": "发布状态与上线节奏", + "gray_rollout": "灰度进展", + "official_confirmation": "官方渠道确认", + "ui_modes": "Expert / Vision 模式关联", + "v4_lite": "V4 Lite 与 Sealion 线索", + "specs_architecture": "规格、架构与上下文能力", + "definition_basics": "定义与基础解释", + "causes_mechanism": "成因与机制", + "categories_types": "分类与相关类型", + "impacts_applications": "影响与应用", +} + +_EN_LABELS = { + "understanding": "Understanding", + "scope": "Research Scope", + "evidence": "Verification", + "finding": "Key Findings", + "latest_updates": "latest updates", + "release_status": "release status and rollout timing", + "gray_rollout": "gray rollout progress", + "official_confirmation": "official confirmation", + "ui_modes": "Expert / Vision mode signals", + "v4_lite": "V4 Lite and Sealion clues", + "specs_architecture": "specs, architecture, and context capability", + "definition_basics": "definition and basic explanation", + "causes_mechanism": "causes and mechanism", + "categories_types": "categories and related types", + "impacts_applications": "impacts and applications", +} + + +@dataclass(slots=True) +class ReasoningEvent: + section: str + text: str + track: str = "" + evidence_level: int = 0 + dedupe_key: str = "" + + +class ReasoningAggregator: + """Normalize raw stream fragments into enterprise-style reasoning output.""" + + __slots__ = ( + "_language", + "_en_votes", + "_zh_votes", + "_agent_search_started", + "_emitted_keys", + "_seen_tracks", + "_seen_findings", + "_pending_events", + "_section_started", + "_track_best_level", + "_track_emit_counts", + ) + + def __init__(self) -> None: + self._language: str | None = None + self._en_votes = 0 + self._zh_votes = 0 + self._agent_search_started = False + self._emitted_keys: set[str] = set() + self._seen_tracks: set[str] = set() + self._seen_findings: set[str] = set() + self._pending_events: list[ReasoningEvent] = [] + self._section_started: set[str] = set() + self._track_best_level: dict[tuple[str, str], int] = {} + self._track_emit_counts: dict[tuple[str, str], int] = {} + + def on_thinking( + self, + token: str, + *, + tag: str | None, + rollout: str | None, + step_id: int | None, + ) -> list[str]: + self._observe_language(token) + tag_name = str(tag or "").strip() + text = str(token or "").strip() + if not text: + return [] + + if tag_name == "header": + event = self._normalize_header(text, step_id=step_id) + return self._dispatch(event) if event else [] + + if tag_name == "summary": + event = self._normalize_summary(text, step_id=step_id) + return self._dispatch(event) if event else [] + + event = self._normalize_summary(text, step_id=step_id) + return self._dispatch(event) if event else [] + + def on_tool_usage( + self, + tool_name: str, + args: dict[str, Any], + *, + rollout: str | None, + step_id: int | None, + ) -> list[str]: + lines: list[str] = [] + self._observe_language(str(args.get("query") or args.get("message") or args.get("instructions") or "")) + + if tool_name == "web_search": + query = str(args.get("query") or args.get("q") or "").strip() + if not query: + return [] + if str(rollout or "").startswith("Agent") and not self._agent_search_started: + self._agent_search_started = True + lines.extend(self._dispatch(ReasoningEvent( + "scope", + self._localized_line("agents_started"), + dedupe_key="scope:agents_started", + ))) + track = self._infer_track(query) + if not track: + return lines + lines.extend(self._dispatch(ReasoningEvent( + "scope", + self._localized_track_line(track), + track=track, + evidence_level=1, + dedupe_key=f"scope:web:{track}", + ))) + return lines + + if tool_name in {"x_search", "x_keyword_search", "x_semantic_search"}: + query = str(args.get("query") or "").strip() + track = self._infer_track(query) + if not track: + return [] + return self._dispatch(ReasoningEvent( + "evidence", + self._localized_social_line(track), + track=track, + evidence_level=2, + dedupe_key=f"evidence:social:{track}", + )) + + if tool_name == "browse_page": + url = str(args.get("url") or "").strip() + source_kind, track = self._classify_page_source(url, args) + if not source_kind: + return [] + return self._dispatch(ReasoningEvent( + "evidence", + self._localized_browse_line(source_kind, track), + track=track or source_kind, + evidence_level=4 if source_kind in {"official", "product"} else 3, + dedupe_key=f"evidence:browse:{source_kind}:{track or ''}", + )) + + if tool_name in {"search_images", "image_search"}: + description = str(args.get("image_description") or args.get("imageDescription") or "").strip() + if not description: + return [] + topic = self._classify_image_topic(description) + if not topic: + return [] + return self._dispatch(ReasoningEvent( + "scope", + self._localized_image_line(topic), + track="visual_assets", + evidence_level=1, + dedupe_key=f"scope:image:{topic}", + )) + + if tool_name == "chatroom_send": + message = str(args.get("message") or "").strip() + if not message: + return [] + lines = [] + for section, text, track, level in self._extract_report_events(message): + lines.extend(self._dispatch(ReasoningEvent( + section, + text, + track=track, + evidence_level=level, + dedupe_key=f"{section}:report:{track}:{self._normalize_key(text)}", + ))) + return lines + + if tool_name == "code_execution": + return self._dispatch(ReasoningEvent( + "evidence", + self._localized_line("code_execution"), + dedupe_key="evidence:code_execution", + )) + + return [] + + def finalize(self) -> list[str]: + if not self._pending_events: + return [] + if self._language is None: + self._language = "en" if self._en_votes > 0 and self._zh_votes == 0 else "zh" + return self._flush_pending() + + def _normalize_header(self, text: str, *, step_id: int | None) -> ReasoningEvent | None: + stripped = text.strip() + if stripped.lower() in _GENERIC_HEADERS: + return None + section = "understanding" if not self._looks_like_verification(stripped) and (step_id or 0) <= 1 else "evidence" + return ReasoningEvent(section, self._to_bullet_text(stripped), dedupe_key=f"{section}:header:{self._normalize_key(stripped)}") + + def _normalize_summary(self, text: str, *, step_id: int | None) -> ReasoningEvent | None: + summary = text.lstrip("- ").strip() + if not summary: + return None + if summary.startswith(("建议搜索", "正在调用工具搜索")): + return None + + track = self._infer_track(summary) + if self._looks_like_progress(summary): + section = "evidence" if self._looks_like_verification(summary) else "scope" + return ReasoningEvent(section, self._to_bullet_text(summary), track=track, evidence_level=2 if section == "evidence" else 1, dedupe_key=f"{section}:summary:{self._normalize_key(summary)}") + + if self._looks_like_finding(summary): + if self._is_unconfirmed_signal(summary): + return ReasoningEvent("evidence", self._to_bullet_text(summary), track=track, evidence_level=2, dedupe_key=f"evidence:summary:{self._normalize_key(summary)}") + if not self._agent_search_started and (step_id or 0) <= 1: + return ReasoningEvent("understanding", self._to_bullet_text(summary), track=track, evidence_level=2, dedupe_key=f"understanding:summary:{self._normalize_key(summary)}") + return ReasoningEvent("finding", self._to_bullet_text(summary), track=track, evidence_level=3, dedupe_key=f"finding:summary:{self._normalize_key(summary)}") + + section = "understanding" if (step_id or 0) <= 1 else "scope" + return ReasoningEvent(section, self._to_bullet_text(summary), track=track, evidence_level=1, dedupe_key=f"{section}:summary:{self._normalize_key(summary)}") + + def _extract_report_events(self, message: str) -> list[tuple[str, str, str, int]]: + parts = re.split(r"(?:\n+|[。!?!?;;]+|\s+-\s+)", message.replace("\\n", "\n")) + candidates: list[tuple[int, str]] = [] + for raw_part in parts: + clause = self._clean_report_clause(raw_part) + if not clause: + continue + if self._language == "zh" and not re.search(r"[\u4e00-\u9fff]", clause): + continue + if self._language == "en" and re.search(r"[\u4e00-\u9fff]", clause): + continue + score = self._score_report_clause(clause) + if score <= 0: + continue + candidates.append((score, clause)) + + candidates.sort(key=lambda item: (-item[0], len(item[1]))) + results: list[tuple[str, str, str, int]] = [] + seen_local: set[str] = set() + seen_track_counts: dict[tuple[str, str], int] = {} + for _, clause in candidates: + key = self._normalize_key(clause) + if key in seen_local: + continue + seen_local.add(key) + track = self._infer_track(clause) + section = "finding" if self._looks_like_finding(clause) else "evidence" + if self._is_unconfirmed_signal(clause): + section = "evidence" + track_key = (section, track or "_") + current_track_count = seen_track_counts.get(track_key, 0) + max_track_count = 2 if section == "finding" else 1 + if current_track_count >= max_track_count: + continue + seen_track_counts[track_key] = current_track_count + 1 + level = self._infer_evidence_level(clause, default=3 if section == "finding" else 2) + results.append((section, self._to_bullet_text(clause), track, level)) + if len(results) >= 6: + break + results.sort(key=lambda item: (0 if item[0] == "evidence" else 1, item[2], -item[3])) + return results + + def _dispatch(self, event: ReasoningEvent) -> list[str]: + if self._language is None: + self._pending_events.append(event) + if self._zh_votes > 0: + self._language = "zh" + elif self._en_votes >= 3: + self._language = "en" + elif len(self._pending_events) < 4: + return [] + else: + self._language = "en" + return self._flush_pending() + + lines: list[str] = [] + if self._pending_events: + lines.extend(self._flush_pending()) + lines.extend(self._emit(event)) + return lines + + def _flush_pending(self) -> list[str]: + lines: list[str] = [] + pending = self._pending_events + self._pending_events = [] + for event in pending: + lines.extend(self._emit(event)) + return lines + + def _emit(self, event: ReasoningEvent) -> list[str]: + text = event.text.strip() + if not text: + return [] + if event.section == "scope" and ("evidence" in self._section_started or "finding" in self._section_started): + return [] + if event.section == "evidence" and "finding" in self._section_started: + if event.evidence_level >= 4 or event.track in { + "latest_updates", + "release_status", + "official_confirmation", + "specs_architecture", + "v4_lite", + }: + promoted_key = event.dedupe_key or f"evidence:{self._normalize_key(text)}" + event = ReasoningEvent( + "finding", + text, + track=event.track, + evidence_level=event.evidence_level, + dedupe_key=f"finding:promoted:{promoted_key}", + ) + else: + return [] + + dedupe_key = event.dedupe_key or f"{event.section}:{self._normalize_key(text)}" + if dedupe_key in self._emitted_keys: + return [] + + if event.track: + count_key = (event.section, event.track) + emitted_count = self._track_emit_counts.get(count_key, 0) + max_per_track = 1 if event.section in {"scope", "evidence"} else 2 + if emitted_count >= max_per_track and not dedupe_key.endswith("agents_started"): + return [] + best_key = (event.section, event.track) + best_level = self._track_best_level.get(best_key, -1) + if best_level > event.evidence_level: + return [] + self._track_best_level[best_key] = max(best_level, event.evidence_level) + self._track_emit_counts[count_key] = emitted_count + 1 + + self._emitted_keys.add(dedupe_key) + lines: list[str] = [] + if event.section not in self._section_started: + self._section_started.add(event.section) + lines.append(self._section_title(event.section) + "\n") + lines.append(text + "\n") + return lines + + def _observe_language(self, text: str) -> None: + if not text: + return + cjk_count = len(re.findall(r"[\u4e00-\u9fff]", text)) + en_count = len(re.findall(r"[A-Za-z]", text)) + if cjk_count >= 4 or cjk_count > max(2, en_count // 2): + self._zh_votes += 1 + if self._language is None: + self._language = "zh" + return + if en_count >= 4: + self._en_votes += 1 + + def _section_title(self, section: str) -> str: + labels = _ZH_LABELS if self._language != "en" else _EN_LABELS + return labels.get(section, section) + + def _localized_line(self, key: str) -> str: + zh_map = { + "agents_started": "- 已启动并行代理进行交叉检索与核验。", + "code_execution": "- 正在执行代码或生成可运行内容。", + } + en_map = { + "agents_started": "- Parallel agents have started cross-checking the topic.", + "code_execution": "- Executing code or generating runnable content.", + } + mapping = zh_map if self._language != "en" else en_map + return mapping[key] + + def _localized_track_line(self, track: str) -> str: + label = self._track_label(track) + if self._language == "en": + return f"- Parallel research: {label}." + return f"- 并行检索:{label}。" + + def _localized_social_line(self, track: str) -> str: + label = self._track_label(track) + if self._language == "en": + return f"- Social cross-check: {label}." + return f"- 社媒交叉核验:{label}。" + + def _localized_browse_line(self, source_kind: str, track: str) -> str: + track_label = self._track_label(track) if track else "" + if self._language == "en": + mapping = { + "official": "Page verification: official site and official pages", + "product": "Page verification: product page and live UI", + "community": "Page verification: public reports and community write-ups", + } + else: + mapping = { + "official": "页面核对:官网与官方页面", + "product": "页面核对:产品页面与实际界面", + "community": "页面核对:公开报道与社区文章", + } + base = mapping[source_kind] + if track_label: + connector = ", focusing on " if self._language == "en" else ",重点核对" + return f"- {base}{connector}{track_label}{'.' if self._language == 'en' else '。'}" + return f"- {base}{'.' if self._language == 'en' else '。'}" + + def _localized_image_line(self, topic: str) -> str: + if self._language == "en": + mapping = { + "diagram": "- Visual asset search: diagrams and explanatory graphics.", + "photo": "- Visual asset search: real-world comparison photos.", + "generic": "- Visual asset search: supporting image references.", + } + else: + mapping = { + "diagram": "- 视觉素材检索:示意图与结构说明素材。", + "photo": "- 视觉素材检索:实景对比图片。", + "generic": "- 视觉素材检索:补充说明图片。", + } + return mapping[topic] + + def _track_label(self, track: str) -> str: + labels = _ZH_LABELS if self._language != "en" else _EN_LABELS + return labels.get(track, track) + + def _infer_track(self, text: str) -> str: + lowered = self._compact_query(text).lower() + if not lowered: + return "" + for track, keywords in _TRACK_RULES: + if any(keyword in lowered for keyword in keywords): + return track + return "" + + def _classify_page_source(self, url: str, args: dict[str, Any]) -> tuple[str, str]: + lowered = url.lower() + instructions = str(args.get("instructions") or "") + track = self._pick_browse_track(f"{url} {instructions}") + if any(domain in lowered for domain in ("deepseek.ai", "deepseek.com")): + if "chat.deepseek.com" in lowered or "platform.deepseek.com" in lowered: + return "product", track or "ui_modes" + return "official", track or "official_confirmation" + if url: + return "community", track + return "", track + + def _pick_browse_track(self, text: str) -> str: + lowered = self._compact_query(text).lower() + priority = ( + ("ui_modes", ("expert", "vision", "mode", "界面", "ui")), + ("release_status", ("release", "released", "launch", "发布", "上线", "status")), + ("specs_architecture", ("spec", "parameter", "architecture", "context", "engram", "moe", "规格", "参数", "架构", "上下文")), + ("v4_lite", ("v4 lite", "sealion", "sealion-lite", "海狮")), + ("official_confirmation", ("official", "官网", "current models", "offering")), + ) + for track, keywords in priority: + if any(keyword in lowered for keyword in keywords): + return track + return self._infer_track(text) + + def _classify_image_topic(self, text: str) -> str: + lowered = text.lower() + if any(token in lowered for token in ("diagram", "示意图", "bulge")): + return "diagram" + if any(token in lowered for token in ("photo", "照片", "real", "high tide", "low tide", "高潮", "低潮")): + return "photo" + return "generic" + + def _looks_like_progress(self, text: str) -> bool: + lowered = text.lower() + return any(hint in lowered for hint in _PROGRESSIVE_HINTS) + + def _looks_like_verification(self, text: str) -> bool: + lowered = text.lower() + return any(token in lowered for token in ("确认", "核对", "浏览", "整合", "比对", "check", "verify", "browse", "integrat")) + + def _looks_like_finding(self, text: str) -> bool: + lowered = text.lower() + if self._looks_like_progress(text): + return False + return any(hint in lowered for hint in _FINDING_HINTS) + + def _clean_report_clause(self, raw_part: str) -> str: + clause = re.sub(r"\s+", " ", raw_part).strip(" -•\t") + if not clause: + return "" + delimiter = ":" if ":" in clause else ":" if ":" in clause else "" + if delimiter: + head, tail = clause.split(delimiter, 1) + head_lower = head.strip().lower() + if len(head.strip()) <= 18 or any(token in head_lower for token in ("总结", "最新", "关键", "补充", "latest", "summary", "note")): + clause = tail.strip() + clause = clause.strip(" -•\t") + clause = re.sub(r"^(?:我知道|我收集了可靠信息|我收集到的?信息|从搜索结果总结|详细解释要点(?:([^)]+))?|补充)\s*", "", clause) + clause = re.sub(r"^(?:that|it shows|it seems)\s+", "", clause, flags=re.IGNORECASE) + if len(clause) < 8: + return "" + lowered = clause.lower() + if any(lowered.startswith(prefix) for prefix in _LOW_VALUE_PREFIXES): + return "" + if "?" in clause or "?" in clause: + return "" + return self._compact_text(clause, limit=120) + + def _score_report_clause(self, clause: str) -> int: + lowered = clause.lower() + score = 0 + if any(hint in lowered for hint in _FINDING_HINTS): + score += 3 + if re.search(r"\b\d+(?:\.\d+)?\b", clause): + score += 2 + if any(token in clause for token in ("月", "日", "年", "小时", "分钟")): + score += 1 + if any(token in clause for token in ("重要", "航运", "渔业", "发电", "生态", "模式", "视觉")): + score += 1 + if any(token in lowered for token in ("可能", "rumor", "传闻", "widely believed", "believed")): + score -= 1 + if any(token in lowered for token in ("可以", "suggest", "建议", "should", "friendly", "reply")): + score -= 2 + if len(clause) > 150: + score -= 1 + return score + + def _infer_evidence_level(self, clause: str, *, default: int) -> int: + lowered = clause.lower() + if any(token in lowered for token in ("官网", "official", "chat ui", "界面更新", "页面")): + return 4 + if any(token in lowered for token in ("x平台", "x posts", "社区", "widely believed", "传闻", "rumor")): + return max(2, default - 1) + return default + + def _is_unconfirmed_signal(self, clause: str) -> bool: + lowered = clause.lower() + return any( + token in lowered + for token in ( + "x平台", "x posts", "社区", "community", "widely believed", "believed", + "传闻", "rumor", "曝光", "泄露", + ) + ) + + def _to_bullet_text(self, text: str) -> str: + stripped = text.strip() + if stripped.startswith("- "): + stripped = stripped[2:].strip() + stripped = self._ensure_terminal_punctuation(stripped) + return f"- {stripped}" + + def _ensure_terminal_punctuation(self, text: str) -> str: + stripped = text.strip() + if not stripped: + return "" + if stripped.endswith(("。", "!", "?", ".", "!", "?")): + return stripped + if re.search(r"[\u4e00-\u9fff]", stripped): + return stripped + "。" + return stripped + "." + + def _compact_query(self, text: str) -> str: + cleaned = re.sub(r"\b(?:or|and|site:[^\s]+|since:\S+|from:\S+|date:\S+)\b", " ", text, flags=re.IGNORECASE) + cleaned = re.sub(r"[()\"']", " ", cleaned) + cleaned = re.sub(r"\s+", " ", cleaned).strip() + return cleaned + + def _compact_text(self, text: str, *, limit: int) -> str: + compact = re.sub(r"\s+", " ", text).strip() + if len(compact) <= limit: + return compact + return compact[: limit - 3].rstrip() + "..." + + def _normalize_key(self, text: str) -> str: + lowered = text.lower() + lowered = re.sub(r"https?://\S+", "", lowered) + lowered = re.sub(r"[^\w\u4e00-\u9fff]+", "", lowered) + return lowered + + +__all__ = ["ReasoningAggregator", "ReasoningEvent"] diff --git a/app/dataplane/reverse/protocol/xai_console_chat.py b/app/dataplane/reverse/protocol/xai_console_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..b353b909c98f52ce4f55322b10c782b7727d6ddb --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_console_chat.py @@ -0,0 +1,366 @@ +"""XAI console.x.ai chat protocol — payload builder and SSE stream adapter. + +端点: POST https://console.x.ai/v1/responses +认证: Authorization: Bearer anonymous + Cookie: sso=; sso-rw= + +请求格式 (OpenAI Responses API): +{ + "model": "grok-4.3", + "input": [{"role": "user", "content": [{"type": "input_text", "text": "..."}]}], + "max_output_tokens": 1000000, + "temperature": 0.7, + "top_p": 0.95, + "reasoning": {"effort": "low"}, + "store": false, + "include": ["reasoning.encrypted_content"], + "stream": true +} + +响应 SSE 事件类型: +- response.created / response.in_progress — 忽略 +- response.output_item.added — 忽略 +- response.output_item.done — reasoning item,含 encrypted_content(不可读) +- response.content_part.added — 忽略 +- response.output_text.delta — 文本 token,delta 字段 +- response.output_text.done — 忽略 +- response.content_part.done — 忽略 +- response.output_item.done (message) — 忽略 +- response.completed — 含 usage 统计 +""" + +from typing import Any, AsyncGenerator + +import orjson + +from app.platform.errors import UpstreamError +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config + + +# --------------------------------------------------------------------------- +# 支持的模型名 → console.x.ai 实际 model 字段映射 +# --------------------------------------------------------------------------- + +# console.x.ai 上可用的模型(通过 grok.com SSO 免费访问) +# key = grok2api 对外暴露的模型名,value = console.x.ai 实际 model 字段 +CONSOLE_MODELS: dict[str, str] = { + "grok-4.3-console": "grok-4.3", + "grok-4.3-low": "grok-4.3", + "grok-4.3-medium": "grok-4.3", + "grok-4.3-high": "grok-4.3", + "grok-4.20-0309-reasoning-console": "grok-4.20-0309-reasoning", + "grok-4.20-0309-console": "grok-4.20-0309", + "grok-4.20-0309-non-reasoning-console": "grok-4.20-0309-non-reasoning", + "grok-4.20-multi-agent-console": "grok-4.20-multi-agent-0309", + "grok-4.20-multi-agent-low": "grok-4.20-multi-agent-0309", + "grok-4.20-multi-agent-medium": "grok-4.20-multi-agent-0309", + "grok-4.20-multi-agent-high": "grok-4.20-multi-agent-0309", + "grok-4.20-multi-agent-xhigh": "grok-4.20-multi-agent-0309", + "grok-build-console": "grok-build-0.1", +} + +# 需要附带 reasoning 字段的模型(grok-4.3 系列需要,grok-4.20 系列不需要) +_MODELS_WITH_REASONING_FIELD: frozenset[str] = frozenset({ + "grok-4.3", + "grok-4.20-multi-agent-0309", +}) + +# 模型名后缀 → 固定 effort 值(优先级高于用户传入的 reasoning_effort) +_MODEL_FIXED_EFFORT: dict[str, str] = { + "grok-4.3-low": "low", + "grok-4.3-medium": "medium", + "grok-4.3-high": "high", + "grok-4.20-multi-agent-low": "low", + "grok-4.20-multi-agent-medium": "medium", + "grok-4.20-multi-agent-high": "high", + "grok-4.20-multi-agent-xhigh": "xhigh", +} + +# 特殊 max_output_tokens(默认 1_000_000) +_MODEL_MAX_OUTPUT_TOKENS: dict[str, int] = { + "grok-4.20-multi-agent-0309": 2_000_000, + "grok-build-0.1": 256_000, +} + +# 支持 web_search / x_search 工具的模型 +_MODELS_WITH_SEARCH_TOOLS: frozenset[str] = frozenset({ + "grok-4.20-multi-agent-0309", + "grok-4.20-0309", + "grok-4.20-0309-reasoning", + "grok-4.20-0309-non-reasoning", + "grok-4.3", + "grok-build-0.1", +}) + +# reasoning effort 映射:OpenAI reasoning_effort → console API effort +_EFFORT_MAP: dict[str, str] = { + "none": "none", + "minimal": "low", + "low": "low", + "medium": "medium", + "high": "high", + "xhigh": "xhigh", +} + + +# --------------------------------------------------------------------------- +# Payload builder +# --------------------------------------------------------------------------- + +def build_console_payload( + *, + messages: list[dict[str, Any]], + model: str, + temperature: float = 0.7, + top_p: float = 0.95, + reasoning_effort: str | None = None, + stream: bool = True, +) -> dict[str, Any]: + """Build the JSON payload for POST console.x.ai/v1/responses. + + 将 OpenAI messages 格式转换为 Responses API input 格式。 + """ + # 转换 messages → input 数组 + input_items: list[dict[str, Any]] = [] + for msg in messages: + role = msg.get("role", "user") + content = msg.get("content", "") + + # 映射 role + if role in ("system", "developer"): + # system 消息作为 instructions 字段处理,这里先放入 input + api_role = "system" + elif role == "assistant": + api_role = "assistant" + else: + api_role = "user" + + # 处理 content + if isinstance(content, str): + content_blocks = [{"type": "input_text", "text": content}] + elif isinstance(content, list): + content_blocks = [] + for block in content: + if not isinstance(block, dict): + continue + btype = block.get("type", "") + if btype == "text": + content_blocks.append({"type": "input_text", "text": block.get("text", "")}) + elif btype == "image_url": + url = (block.get("image_url") or {}).get("url", "") + if url: + content_blocks.append({"type": "input_image", "image_url": url}) + else: + # 其他类型降级为文本 + text = block.get("text") or str(block) + content_blocks.append({"type": "input_text", "text": text}) + else: + content_blocks = [{"type": "input_text", "text": str(content)}] + + if content_blocks: + input_items.append({"role": api_role, "content": content_blocks}) + + # reasoning effort:模型名固定值优先,其次用户传入,最后默认 medium + effort = _MODEL_FIXED_EFFORT.get(model) or _EFFORT_MAP.get(reasoning_effort or "medium", "medium") + + # 获取 console 实际模型名 + console_model = CONSOLE_MODELS.get(model, model) + + payload: dict[str, Any] = { + "model": console_model, + "input": input_items, + "max_output_tokens": _MODEL_MAX_OUTPUT_TOKENS.get(console_model, 1_000_000), + "temperature": temperature, + "top_p": top_p, + "store": False, + "include": ["reasoning.encrypted_content"], + "stream": stream, + } + + # 只有 grok-4.3 需要附带 reasoning 字段,grok-4.20 系列不需要 + if console_model in _MODELS_WITH_REASONING_FIELD: + payload["reasoning"] = {"effort": effort} + + # 为 multi-agent 和支持搜索的模型添加 tools + if console_model in _MODELS_WITH_SEARCH_TOOLS: + payload["tools"] = [ + {"type": "web_search", "enable_image_understanding": True}, + {"type": "x_search", "enable_video_understanding": True}, + ] + payload["tool_choice"] = "auto" + + logger.debug( + "console payload built: model={} console_model={} input_items={} has_reasoning={}", + model, console_model, len(input_items), console_model in _MODELS_WITH_REASONING_FIELD, + ) + return payload + + +# --------------------------------------------------------------------------- +# SSE stream adapter +# --------------------------------------------------------------------------- + +class ConsoleStreamAdapter: + """Parse console.x.ai SSE events and yield text tokens. + + 只关心 response.output_text.delta 事件,其余忽略。 + response.completed 事件用于提取 usage 统计。 + """ + + __slots__ = ("text_buf", "usage", "_done") + + def __init__(self) -> None: + self.text_buf: list[str] = [] + self.usage: dict[str, Any] | None = None + self._done = False + + def feed(self, event_type: str, data: str) -> list[str]: + """解析一个 SSE 事件,返回文本 token 列表(通常 0 或 1 个)。""" + if self._done: + return [] + + try: + obj = orjson.loads(data) + except (orjson.JSONDecodeError, ValueError): + return [] + + if event_type == "response.output_text.delta": + delta = obj.get("delta", "") + if delta: + self.text_buf.append(delta) + return [delta] + + elif event_type == "response.completed": + resp = obj.get("response", {}) + self.usage = resp.get("usage") + self._done = True + + elif event_type == "error": + msg = obj.get("message") or str(obj) + raise UpstreamError(f"Console API error: {msg}", status=502) + + return [] + + @property + def full_text(self) -> str: + return "".join(self.text_buf) + + +def classify_console_line(line: str) -> tuple[str, str]: + """Parse a raw SSE line into (event_type, data). + + console.x.ai 使用标准 SSE 格式: + event: response.output_text.delta + data: {...} + """ + line = line.strip() + if not line: + return "skip", "" + if line.startswith("event:"): + return "event", line[6:].strip() + if line.startswith("data:"): + data = line[5:].strip() + if data == "[DONE]": + return "done", "" + return "data", data + return "skip", "" + + +async def stream_console_chat( + token: str, + payload: dict[str, Any], + *, + timeout_s: float = 120.0, +) -> AsyncGenerator[tuple[str, str], None]: + """POST to console.x.ai/v1/responses and yield (event_type, data) pairs. + + 走现有的 proxy lease + curl-cffi 体系,与 grok.com 共用 CF clearance。 + """ + from app.dataplane.proxy import get_proxy_runtime + from app.dataplane.proxy.adapters.headers import build_console_headers + from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs + from app.dataplane.reverse.runtime.endpoint_table import CONSOLE_RESPONSES + + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + + headers = build_console_headers(token, lease=lease) + payload_bytes = orjson.dumps(payload) + session_kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**session_kwargs) as session: + try: + response = await session.post( + CONSOLE_RESPONSES, + headers=headers, + data=payload_bytes, + timeout=timeout_s, + stream=True, + ) + except Exception as exc: + await proxy.feedback(lease, _transport_error_feedback()) + raise UpstreamError(f"Console transport failed: {exc}", status=502) from exc + + if response.status_code != 200: + try: + body = response.content.decode("utf-8", "replace")[:400] + except Exception: + body = "" + await proxy.feedback(lease, _status_feedback(response.status_code)) + raise UpstreamError( + f"Console API returned {response.status_code}", + status=response.status_code, + body=body, + ) + + await proxy.feedback(lease, _success_feedback()) + + current_event = "" + try: + async for raw_line in response.aiter_lines(): + # curl-cffi 的 aiter_lines 返回 bytes,先解码为 str + if isinstance(raw_line, bytes): + try: + raw_line = raw_line.decode("utf-8") + except UnicodeDecodeError: + raw_line = raw_line.decode("utf-8", errors="replace") + kind, value = classify_console_line(raw_line) + if kind == "event": + current_event = value + elif kind == "data": + yield current_event, value + current_event = "" + elif kind == "done": + return + except Exception as exc: + raise UpstreamError(f"Console stream read failed: {exc}", status=502) from exc + + +def _success_feedback(): + from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind + return ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200) + +def _transport_error_feedback(): + from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind + return ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR) + +def _status_feedback(status: int): + from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind + if status == 403: + kind = ProxyFeedbackKind.CHALLENGE + elif status == 429: + kind = ProxyFeedbackKind.RATE_LIMITED + elif status >= 500: + kind = ProxyFeedbackKind.UPSTREAM_5XX + else: + kind = ProxyFeedbackKind.FORBIDDEN + return ProxyFeedback(kind=kind, status_code=status) + + +__all__ = [ + "CONSOLE_MODELS", + "build_console_payload", + "ConsoleStreamAdapter", + "classify_console_line", + "stream_console_chat", +] diff --git a/app/dataplane/reverse/protocol/xai_image.py b/app/dataplane/reverse/protocol/xai_image.py new file mode 100644 index 0000000000000000000000000000000000000000..a6ce59f18ff038cac9edbf4e0c9a9ea474ef8d58 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_image.py @@ -0,0 +1,112 @@ +"""XAI Imagine WebSocket protocol — message builders and frame parsers.""" + +import re +import time +import uuid +from typing import Any + +_URL_PATTERN = re.compile(r"/images/([a-f0-9\-]+)\.(png|jpg|jpeg)", re.IGNORECASE) + +WS_IMAGINE_URL = "wss://grok.com/ws/imagine/listen" + + +# --------------------------------------------------------------------------- +# Client message builders +# --------------------------------------------------------------------------- + +def build_reset_message() -> dict[str, Any]: + """Build the reset message that must be sent before each prompt.""" + return { + "type": "conversation.item.create", + "timestamp": int(time.time() * 1000), + "item": {"type": "message", "content": [{"type": "reset"}]}, + } + + +def build_request_message( + request_id: str, + prompt: str, + aspect_ratio: str = "2:3", + enable_nsfw: bool = True, + enable_pro: bool = False, +) -> dict[str, Any]: + """Build the image generation request message.""" + return { + "type": "conversation.item.create", + "timestamp": int(time.time() * 1000), + "item": { + "type": "message", + "content": [{ + "requestId": request_id, + "text": prompt, + "type": "input_text", + "properties": { + "section_count": 0, + "is_kids_mode": False, + "enable_nsfw": enable_nsfw, + "skip_upsampler": False, + "enable_side_by_side": True, + "is_initial": False, + "aspect_ratio": aspect_ratio, + "enable_pro": enable_pro, + }, + }], + }, + } + + +# --------------------------------------------------------------------------- +# Server frame parsers +# --------------------------------------------------------------------------- + +def parse_image_url(url: str) -> tuple[str, str]: + """Extract (image_id, ext) from a /images/{id}.{ext} URL. + + Falls back to a random UUID and 'jpg' if pattern not found. + """ + match = _URL_PATTERN.search(url or "") + if match: + return match.group(1), match.group(2).lower() + return uuid.uuid4().hex, "jpg" + + +def parse_json_frame(msg: dict[str, Any]) -> dict[str, Any] | None: + """Parse a {type: "json"} frame. + + Returns a normalised dict on success, None if unrecognised status. + + Returned keys: + status "start_stage" | "completed" + image_id str + order int + width int + height int + moderated bool (only meaningful for "completed") + r_rated bool (only meaningful for "completed") + """ + status = msg.get("current_status") + if status not in ("start_stage", "completed"): + return None + + image_id = str(msg.get("image_id") or msg.get("job_id") or "") + if not image_id: + return None + + return { + "status": status, + "image_id": image_id, + "order": int(msg.get("order") or 0), + "width": int(msg.get("width") or 0), + "height": int(msg.get("height") or 0), + "moderated": bool(msg.get("moderated")), + "r_rated": bool(msg.get("r_rated")), + } + + +__all__ = [ + "WS_IMAGINE_URL", + "build_reset_message", + "build_request_message", + "parse_image_url", + "parse_json_frame", +] diff --git a/app/dataplane/reverse/protocol/xai_image_edit.py b/app/dataplane/reverse/protocol/xai_image_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0e86c1c130bb0687d9da1dbe49c55b9ee14f5a --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_image_edit.py @@ -0,0 +1,106 @@ +"""XAI image-edit protocol — payload builder and SSE field extractors.""" + +from typing import Any + +from app.platform.config.snapshot import get_config + +IMAGE_EDIT_MODEL_NAME = "imagine-image-edit" +IMAGE_EDIT_MODEL_KIND = "imagine" +IMAGE_POST_MEDIA_TYPE = "MEDIA_POST_TYPE_IMAGE" +IMAGE_EDIT_GENERATION_COUNT = 2 + + +def build_image_edit_payload( + *, + prompt: str, + image_references: list[str], + parent_post_id: str, +) -> dict[str, Any]: + """Build the JSON payload for imagine image-edit chat requests.""" + cfg = get_config() + return { + "temporary": cfg.get_bool("features.temporary", True), + "modelName": IMAGE_EDIT_MODEL_NAME, + "message": prompt, + "enableImageGeneration": True, + "returnImageBytes": False, + "returnRawGrokInXaiRequest": False, + "enableImageStreaming": True, + "imageGenerationCount": IMAGE_EDIT_GENERATION_COUNT, + "forceConcise": False, + "enableSideBySide": True, + "sendFinalMetadata": True, + "isReasoning": False, + "disableTextFollowUps": True, + "responseMetadata": { + "modelConfigOverride": { + "modelMap": { + "imageEditModel": IMAGE_EDIT_MODEL_KIND, + "imageEditModelConfig": { + "imageReferences": image_references, + "parentPostId": parent_post_id, + }, + } + } + }, + "disableMemory": not cfg.get_bool("features.memory", False), + "forceSideBySide": False, + } + + +def extract_streaming_response(data: dict[str, Any]) -> dict[str, Any] | None: + """Return ``response.streamingImageGenerationResponse`` when present.""" + result = data.get("result") + if not isinstance(result, dict): + return None + response = result.get("response") + if not isinstance(response, dict): + return None + stream = response.get("streamingImageGenerationResponse") + return stream if isinstance(stream, dict) else None + + +def extract_model_response_urls(data: dict[str, Any]) -> list[str]: + """Return fallback ``modelResponse.generatedImageUrls`` values.""" + result = data.get("result") + if not isinstance(result, dict): + return [] + response = result.get("response") + if not isinstance(response, dict): + return [] + model_response = response.get("modelResponse") + if not isinstance(model_response, dict): + return [] + urls = model_response.get("generatedImageUrls") + if not isinstance(urls, list): + return [] + return [url for url in urls if isinstance(url, str) and url] + + +def extract_model_response_file_attachments(data: dict[str, Any]) -> list[str]: + """Return fallback ``modelResponse.fileAttachments`` asset IDs.""" + result = data.get("result") + if not isinstance(result, dict): + return [] + response = result.get("response") + if not isinstance(response, dict): + return [] + model_response = response.get("modelResponse") + if not isinstance(model_response, dict): + return [] + attachments = model_response.get("fileAttachments") + if not isinstance(attachments, list): + return [] + return [attachment for attachment in attachments if isinstance(attachment, str) and attachment] + + +__all__ = [ + "IMAGE_EDIT_MODEL_NAME", + "IMAGE_EDIT_MODEL_KIND", + "IMAGE_POST_MEDIA_TYPE", + "IMAGE_EDIT_GENERATION_COUNT", + "build_image_edit_payload", + "extract_streaming_response", + "extract_model_response_urls", + "extract_model_response_file_attachments", +] diff --git a/app/dataplane/reverse/protocol/xai_livekit.py b/app/dataplane/reverse/protocol/xai_livekit.py new file mode 100644 index 0000000000000000000000000000000000000000..29f1dd4ce8b8f6f43a00f022dc5e8a9d17dc4e36 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_livekit.py @@ -0,0 +1,67 @@ +"""XAI LiveKit protocol — token endpoint and WebSocket URL. + +The token fetch sends a JSON payload to /rest/livekit/tokens and receives +a short-lived LiveKit access token. The WebSocket connection uses that +access token as a query parameter on wss://livekit.grok.com/rtc. +""" + +from typing import Any, Dict +from urllib.parse import urlencode + +import orjson + +LIVEKIT_TOKEN_URL = "https://grok.com/rest/livekit/tokens" +LIVEKIT_WS_BASE = "wss://livekit.grok.com" + +# SDK version parameters sent with every WebSocket connection. +_WS_PARAMS: Dict[str, str] = { + "auto_subscribe": "1", + "sdk": "js", + "version": "2.11.4", + "protocol": "15", +} + + +def build_token_request_payload( + voice: str = "ara", + personality: str = "assistant", + speed: float = 1.0, + custom_instruction: str = "", +) -> bytes: + """Return the JSON body for POST /rest/livekit/tokens.""" + payload_dict = { + "voice": voice, + "personality": None, + "playback_speed": speed, + "enable_vision": False, + "turn_detection": {"type": "server_vad"}, + } + if custom_instruction: + payload_dict["instructions"] = custom_instruction + payload_dict["is_raw_instructions"] = True + else: + payload_dict["personality"] = personality + + session_payload = orjson.dumps(payload_dict).decode() + + return orjson.dumps({ + "sessionPayload": session_payload, + "requestAgentDispatch": False, + "livekitUrl": LIVEKIT_WS_BASE, + "params": {"enable_markdown_transcript": "true"}, + }) + + +def build_ws_url(access_token: str) -> str: + """Build the wss:// URL for the LiveKit WebSocket connection.""" + base = LIVEKIT_WS_BASE.rstrip("/") + rtc = f"{base}/rtc" if not base.endswith("/rtc") else base + params = dict(_WS_PARAMS) + params["access_token"] = access_token + return f"{rtc}?{urlencode(params)}" + + +__all__ = [ + "LIVEKIT_TOKEN_URL", "LIVEKIT_WS_BASE", + "build_token_request_payload", "build_ws_url", +] diff --git a/app/dataplane/reverse/protocol/xai_usage.py b/app/dataplane/reverse/protocol/xai_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..4c93e093303302a6fad7d049c5eb23c4cab48c52 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_usage.py @@ -0,0 +1,255 @@ +"""XAI rate-limits API protocol — fetch live quota data per mode.""" + +import asyncio + +import orjson + +from app.platform.errors import UpstreamError +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_ms + + +# --------------------------------------------------------------------------- +# Mode → request model name +# --------------------------------------------------------------------------- + +# Each mode requires a separate POST request. +# The API returns a flat single-mode quota object per call. +_MODE_NAMES: dict[int, str] = { + 0: "auto", + 1: "fast", + 2: "expert", + 3: "heavy", + 4: "grok-420-computer-use-sa", +} + +# Default window durations used as fallback when API call fails. +_DEFAULT_WINDOW_SECS: dict[int, int] = { + 0: 7_200, # auto — 2 h (super/heavy only) + 1: 86_400, # fast — 24 h (basic; real value overrides for super/heavy) + 2: 7_200, # expert — 2 h (super/heavy only) + 3: 7_200, # heavy — 2 h (heavy-pool only) + 4: 7_200, # grok_4_3 — 2 h (super/heavy only) +} + + +def _build_payload(mode_name: str) -> bytes: + """Build rate-limits request payload: {"modelName": "fast"}""" + return orjson.dumps({"modelName": mode_name}) + + +# --------------------------------------------------------------------------- +# Response parser +# --------------------------------------------------------------------------- + + +def parse_rate_limits( + body: dict, *, default_window_seconds: int = 72_000 +) -> dict | None: + """Parse flat rate-limits response. + + Expected format:: + + { + "windowSizeSeconds": 72000, + "remainingQueries": 20, + "totalQueries": 20, + "lowEffortRateLimits": null, + "highEffortRateLimits": null + } + + Returns a dict with keys ``remaining``, ``total``, ``window_seconds`` + or ``None`` if the required fields are absent. + """ + remaining = body.get("remainingQueries") + if remaining is None: + return None + total = body.get("totalQueries") + window_secs = body.get("windowSizeSeconds") + return { + "remaining": int(remaining), + "total": int(total) if total is not None else int(remaining), + "window_seconds": int(window_secs) if window_secs else default_window_seconds, + } + + +# --------------------------------------------------------------------------- +# QuotaWindow builder +# --------------------------------------------------------------------------- + + +def _to_quota_window(data: dict, synced_at: int) -> object: + from app.control.account.models import QuotaWindow + from app.control.account.enums import QuotaSource + + ws = data["window_seconds"] + return QuotaWindow( + remaining=data["remaining"], + total=data["total"], + window_seconds=ws, + reset_at=synced_at + ws * 1000, # estimated end of current window + synced_at=synced_at, + source=QuotaSource.REAL, + ) + + +# --------------------------------------------------------------------------- +# HTTP fetch +# --------------------------------------------------------------------------- + + +async def _do_fetch(token: str, mode_name: str) -> dict: + """POST the rate-limits endpoint for one mode and return parsed JSON body.""" + from app.dataplane.reverse.transport.http import post_json + from app.dataplane.proxy import get_proxy_runtime + from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind + + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + try: + body = await post_json( + "https://grok.com/rest/rate-limits", + token, + _build_payload(mode_name), + lease=lease, + timeout_s=20.0, + ) + await proxy.feedback( + lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200) + ) + return body + except Exception as exc: + status = getattr(exc, "status", None) or getattr(exc, "status_code", None) + kind = _proxy_feedback_kind_for_error(exc, status=status) + await proxy.feedback(lease, ProxyFeedback(kind=kind, status_code=status)) + raise + + +async def _fetch_one(token: str, mode_id: int) -> object | None: + """Fetch quota window for a single mode. Returns QuotaWindow or None.""" + mode_name = _MODE_NAMES.get(mode_id, "auto") + try: + body = await asyncio.wait_for(_do_fetch(token, mode_name), timeout=25.0) + except asyncio.TimeoutError: + logger.debug( + "rate-limits fetch timed out: token={}... mode={}", token[:10], mode_name + ) + return None + except Exception as exc: + if is_invalid_credentials_error(exc): + raise + logger.debug( + "rate-limits fetch failed: token={}... mode={} error={}", + token[:10], + mode_name, + exc, + ) + return None + + data = parse_rate_limits( + body, + default_window_seconds=_DEFAULT_WINDOW_SECS.get(mode_id, 72_000), + ) + if data is None: + logger.debug( + "rate-limits response missing quota fields: token={}... mode={} body={}", + token[:10], + mode_name, + body, + ) + return None + + return _to_quota_window(data, now_ms()) + + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- + + +async def fetch_all_quotas( + token: str, mode_ids: tuple[int, ...] | None = None +) -> dict[int, object] | None: + """Fetch quota windows for the requested modes concurrently. + + ``mode_ids`` defaults to ``(0, 1, 2, 3, 4)``. Returns ``{mode_id: QuotaWindow}`` + for every mode that responded successfully, or ``None`` if every requested + mode failed. + """ + import asyncio + + requested = mode_ids or (0, 1, 2, 3, 4) + results = await asyncio.gather( + *(_fetch_one(token, mode_id) for mode_id in requested), return_exceptions=True + ) + for result in results: + if isinstance(result, Exception) and is_invalid_credentials_error(result): + raise result + windows = { + mode_id: win + for mode_id, win in zip(requested, results, strict=False) + if win is not None and not isinstance(win, Exception) + } + return windows if windows else None + + +async def fetch_mode_quota(token: str, mode_id: int) -> object | None: + """Fetch the quota window for a single mode. Returns QuotaWindow or None.""" + return await _fetch_one(token, mode_id) + + +def is_invalid_credentials_body(body: str) -> bool: + """Return whether *body* contains a Grok invalid/blocked account marker.""" + text = str(body or "").lower() + return ( + "invalid-credentials" in text + or "bad-credentials" in text + or "failed to look up session id" in text + or "blocked-user" in text + or "email-domain-rejected" in text + or "session not found" in text + or "account suspended" in text + or "token revoked" in text + or "token expired" in text + ) + + +def is_invalid_credentials_error(exc: BaseException) -> bool: + """Return whether *exc* indicates the account is invalid or blocked.""" + if not isinstance(exc, UpstreamError): + return False + if exc.status not in (400, 401, 403): + return False + return is_invalid_credentials_body(str(exc.details.get("body", "") or "")) + + +def _proxy_feedback_kind_for_error( + exc: BaseException, + *, + status: int | None, +): + """Map quota-fetch failures to proxy feedback without burning healthy clearance.""" + from app.control.proxy.models import ProxyFeedbackKind + + # Invalid or blocked accounts are account problems, not proxy problems. + if is_invalid_credentials_error(exc): + return ProxyFeedbackKind.FORBIDDEN + + if status == 429: + return ProxyFeedbackKind.RATE_LIMITED + if status == 403: + return ProxyFeedbackKind.CHALLENGE + if status == 401: + return ProxyFeedbackKind.UNAUTHORIZED + if status and status >= 500: + return ProxyFeedbackKind.UPSTREAM_5XX + return ProxyFeedbackKind.TRANSPORT_ERROR + + +__all__ = [ + "parse_rate_limits", + "fetch_all_quotas", + "fetch_mode_quota", + "is_invalid_credentials_body", + "is_invalid_credentials_error", +] diff --git a/app/dataplane/reverse/protocol/xai_video.py b/app/dataplane/reverse/protocol/xai_video.py new file mode 100644 index 0000000000000000000000000000000000000000..9575791005302e0bfbc01c632be68c01bd956ab0 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_video.py @@ -0,0 +1,42 @@ +"""XAI video creation protocol — payload builders for media/post/create endpoints.""" + +from typing import Any + +MEDIA_POST_URL = "https://grok.com/rest/media/post/create" +MEDIA_LINK_URL = "https://grok.com/rest/media/post/create-link" +VIDEO_UPSCALE_URL = "https://grok.com/rest/media/video/upscale" + + +def build_media_post_payload( + *, + media_type: str, + media_url: str = "", + prompt: str = "", +) -> dict[str, Any]: + """Build payload for POST /rest/media/post/create.""" + payload: dict[str, Any] = {"mediaType": media_type} + if media_url: + payload["mediaUrl"] = media_url + if prompt: + payload["prompt"] = prompt + return payload + + +def build_upscale_payload(video_id: str) -> dict[str, Any]: + return {"videoId": video_id} + + +def build_media_link_payload(post_id: str) -> dict[str, Any]: + """Build payload for POST /rest/media/post/create-link.""" + return { + "postId": post_id, + "source": "post-page", + "platform": "web", + } + + +__all__ = [ + "MEDIA_POST_URL", "MEDIA_LINK_URL", "VIDEO_UPSCALE_URL", + "build_media_post_payload", + "build_upscale_payload", "build_media_link_payload", +] diff --git a/app/dataplane/reverse/runtime/__init__.py b/app/dataplane/reverse/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/dataplane/reverse/runtime/endpoint_table.py b/app/dataplane/reverse/runtime/endpoint_table.py new file mode 100644 index 0000000000000000000000000000000000000000..54afad9abd810c96a77b22678c9392066046fd12 --- /dev/null +++ b/app/dataplane/reverse/runtime/endpoint_table.py @@ -0,0 +1,61 @@ +"""Static URL table for all upstream XAI / Grok endpoints. + +Canonical source of truth for every URL used by the reverse layer. +Protocol modules re-export the subset they need; transport modules +import from protocol — this file is the single shared reference. + +NOTE: gRPC-Web endpoints (accept_tos, nsfw_mgmt) live on different +hosts (accounts.x.ai, grok.com with gRPC path), listed separately. +""" + +BASE = "https://grok.com" +ASSETS_CDN = "https://assets.grok.com" +CONSOLE_BASE = "https://console.x.ai" + +# ── App-chat (SSE streaming, new conversation) ────────────────────────── +CHAT = f"{BASE}/rest/app-chat/conversations/new" + +# ── Asset management ───────────────────────────────────────────────────── +ASSETS_UPLOAD = f"{BASE}/rest/app-chat/upload-file" # POST (base64 upload) +ASSETS_LIST = f"{BASE}/rest/assets" # GET +ASSETS_DELETE = f"{BASE}/rest/assets-metadata" # DELETE /{asset_id} +ASSETS_DOWNLOAD = ASSETS_CDN # GET /{path} + +# ── Rate limits (usage / quota sync) ───────────────────────────────────── +RATE_LIMITS = f"{BASE}/rest/rate-limits" # POST + +# ── gRPC-Web endpoints ────────────────────────────────────────────────── +ACCEPT_TOS = "https://accounts.x.ai/auth_mgmt.AuthManagement/SetTosAcceptedVersion" +NSFW_MGMT = f"{BASE}/auth_mgmt.AuthManagement/UpdateUserFeatureControls" + +# ── Auth REST ──────────────────────────────────────────────────────────── +SET_BIRTH = f"{BASE}/rest/auth/set-birth-date" # POST + +# ── Media (video) ──────────────────────────────────────────────────────── +MEDIA_POST = f"{BASE}/rest/media/post/create" # POST +MEDIA_POST_LINK = f"{BASE}/rest/media/post/create-link" # POST +VIDEO_UPSCALE = f"{BASE}/rest/media/video/upscale" # POST + +# ── WebSocket endpoints ───────────────────────────────────────────────── +WS_IMAGINE = "wss://grok.com/ws/imagine/listen" +WS_LIVEKIT = "wss://livekit.grok.com" + +# ── LiveKit ───────────────────────────────────────────────────────────── +LIVEKIT_TOKENS = f"{BASE}/rest/livekit/tokens" # POST + +# ── Console API (console.x.ai) ─────────────────────────────────────────── +# 使用 Bearer token 认证,与 grok.com SSO token 共享同一套凭证 +CONSOLE_RESPONSES = f"{CONSOLE_BASE}/v1/responses" # POST (OpenAI Responses API) +CONSOLE_CHAT = f"{CONSOLE_BASE}/v1/chat/completions" # POST (OpenAI Chat API) + + +__all__ = [ + "BASE", "ASSETS_CDN", "CONSOLE_BASE", + "CHAT", + "ASSETS_UPLOAD", "ASSETS_LIST", "ASSETS_DELETE", "ASSETS_DOWNLOAD", + "RATE_LIMITS", + "ACCEPT_TOS", "NSFW_MGMT", "SET_BIRTH", + "MEDIA_POST", "MEDIA_POST_LINK", "VIDEO_UPSCALE", + "WS_IMAGINE", "WS_LIVEKIT", "LIVEKIT_TOKENS", + "CONSOLE_RESPONSES", "CONSOLE_CHAT", +] diff --git a/app/dataplane/reverse/runtime/profiles.py b/app/dataplane/reverse/runtime/profiles.py new file mode 100644 index 0000000000000000000000000000000000000000..b7976b9c76c8cb30563ff02b920e7e9433f14b69 --- /dev/null +++ b/app/dataplane/reverse/runtime/profiles.py @@ -0,0 +1,85 @@ +"""Per-operation timeout / retry profiles for the reverse pipeline. + +Pre-built profiles eliminate per-request config lookups in the hot path. +Each profile specifies timeout, max retries, and retry-eligible status codes. +""" + +from dataclasses import dataclass, field + + +@dataclass(slots=True, frozen=True) +class OperationProfile: + """Timeout and retry configuration for one operation type.""" + timeout_s: float = 30.0 + max_retries: int = 0 + retry_codes: frozenset[int] = frozenset() + retry_delay_s: float = 1.0 + idle_timeout_s: float = 0.0 # 0 = no idle timeout + + +# --------------------------------------------------------------------------- +# Pre-built profiles +# --------------------------------------------------------------------------- + +CHAT = OperationProfile( + timeout_s = 120.0, + max_retries = 1, + retry_codes = frozenset({502, 503}), + retry_delay_s = 2.0, + idle_timeout_s = 30.0, +) + +IMAGE = OperationProfile( + timeout_s = 300.0, + max_retries = 0, + idle_timeout_s = 60.0, +) + +IMAGE_EDIT = OperationProfile( + timeout_s = 120.0, + max_retries = 1, + retry_codes = frozenset({502, 503}), + retry_delay_s = 2.0, + idle_timeout_s = 30.0, +) + +VIDEO = OperationProfile( + timeout_s = 60.0, + max_retries = 1, + retry_codes = frozenset({502, 503, 429}), + retry_delay_s = 5.0, +) + +VOICE = OperationProfile( + timeout_s = 120.0, + max_retries = 0, + idle_timeout_s = 15.0, +) + +ASSET = OperationProfile( + timeout_s = 60.0, + max_retries = 2, + retry_codes = frozenset({502, 503}), + retry_delay_s = 1.0, +) + +GRPC = OperationProfile( + timeout_s = 15.0, + max_retries = 1, + retry_codes = frozenset({503}), + retry_delay_s = 0.5, +) + +# Lookup by name for programmatic access. +PROFILES: dict[str, OperationProfile] = { + "chat": CHAT, + "image": IMAGE, + "image_edit": IMAGE_EDIT, + "video": VIDEO, + "voice": VOICE, + "asset": ASSET, + "grpc": GRPC, +} + + +__all__ = ["OperationProfile", "PROFILES", "CHAT", "IMAGE", "IMAGE_EDIT", "VIDEO", "VOICE", "ASSET", "GRPC"] diff --git a/app/dataplane/reverse/transport/__init__.py b/app/dataplane/reverse/transport/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/dataplane/reverse/transport/_proxy_feedback.py b/app/dataplane/reverse/transport/_proxy_feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..b55b52928aa595a06d7416b1ea7ebca7a429e010 --- /dev/null +++ b/app/dataplane/reverse/transport/_proxy_feedback.py @@ -0,0 +1,35 @@ +"""Shared helper: map an UpstreamError to the correct ProxyFeedbackKind. + +All transport modules (assets, media, livekit, imagine_ws …) use this so the +mapping stays consistent and clearance bundles are properly invalidated. + +Rules +----- +401 → UNAUTHORIZED (invalidates clearance bundle) +403 → CHALLENGE (invalidates clearance bundle — treat all 403s as potential CF) +429 → RATE_LIMITED +≥500 → UPSTREAM_5XX +else → TRANSPORT_ERROR +""" + +from app.platform.errors import UpstreamError +from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind + + +def upstream_feedback(exc: UpstreamError) -> ProxyFeedback: + """Return a ``ProxyFeedback`` for an ``UpstreamError`` response.""" + status = exc.status or 0 + if status == 401: + kind = ProxyFeedbackKind.UNAUTHORIZED + elif status == 403: + kind = ProxyFeedbackKind.CHALLENGE + elif status == 429: + kind = ProxyFeedbackKind.RATE_LIMITED + elif status >= 500: + kind = ProxyFeedbackKind.UPSTREAM_5XX + else: + kind = ProxyFeedbackKind.TRANSPORT_ERROR + return ProxyFeedback(kind=kind, status_code=status or None) + + +__all__ = ["upstream_feedback"] diff --git a/app/dataplane/reverse/transport/asset_upload.py b/app/dataplane/reverse/transport/asset_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..891594424d633509cd8f06b5da23064247ce281c --- /dev/null +++ b/app/dataplane/reverse/transport/asset_upload.py @@ -0,0 +1,247 @@ +"""Asset upload transport — direct base64 upload to Grok. + +Calls POST /rest/app-chat/upload-file with base64-encoded content and +returns the file metadata ID used as a file attachment reference in chat. +""" + +import asyncio +import base64 +import mimetypes +import re +from urllib.parse import urlparse + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import UpstreamError, ValidationError +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.headers import build_sso_cookie +from app.dataplane.proxy.adapters.headers import build_http_headers +from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs +from app.dataplane.reverse.protocol.xai_assets import resolve_asset_reference +from app.control.proxy.feedback import build_feedback +from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind + +_UPLOAD_URL = "https://grok.com/rest/app-chat/upload-file" +_X_USER_ID_RE = re.compile(r"(?:^|;\s*)x-userid=([^;]+)") + +# Global semaphore — limits concurrent upload_file() calls across all requests. +# Initialised lazily on first call so the event loop is guaranteed to be running. +_upload_sem: asyncio.Semaphore | None = None + +def _get_upload_sem() -> asyncio.Semaphore: + global _upload_sem + if _upload_sem is None: + n = max(1, int(get_config("batch.asset_upload_concurrency", 10))) + _upload_sem = asyncio.Semaphore(n) + return _upload_sem + + +# --------------------------------------------------------------------------- +# File-input parsing +# --------------------------------------------------------------------------- + +def _is_url(value: str) -> bool: + try: + p = urlparse(value) + return bool(p.scheme in {"http", "https"} and p.netloc) + except Exception: + return False + + +def _mime_from_name(filename: str, fallback: str = "application/octet-stream") -> str: + mime, _ = mimetypes.guess_type(filename) + return mime or fallback + + +def parse_data_uri(data_uri: str) -> tuple[str, str, str]: + """Split a data URI into (filename, base64_content, mime_type). + + Raises ``ValidationError`` on invalid input. + """ + if not data_uri.startswith("data:"): + raise ValidationError("File input must be a URL or data URI", param="content") + + try: + header, b64 = data_uri.split(",", 1) + except ValueError: + raise ValidationError("Malformed data URI: missing comma separator", param="content") + + if ";base64" not in header: + raise ValidationError("Data URI must be base64-encoded", param="content") + + mime = header[5:].split(";", 1)[0].strip() or "application/octet-stream" + b64 = re.sub(r"\s+", "", b64) + if not b64: + raise ValidationError("Data URI has empty payload", param="content") + + ext = mime.split("/")[-1] if "/" in mime else "bin" + return f"file.{ext}", b64, mime + + +# --------------------------------------------------------------------------- +# Core upload function +# --------------------------------------------------------------------------- + +async def upload_file( + token: str, + filename: str, + mime: str, + b64: str, +) -> tuple[str, str]: + """Upload base64-encoded file content to Grok. + + Args: + token: SSO session token. + filename: Original file name (used for content-type inference). + mime: MIME type string (e.g. ``"image/png"``). + b64: Base64-encoded file content (no data-URI prefix). + + Returns: + ``(file_id, file_uri)`` — file_id is used as a file attachment ref. + + Raises: + ``UpstreamError`` on HTTP failure. + """ + async with _get_upload_sem(): + return await _upload_file_inner(token, filename, mime, b64) + + +async def _upload_file_inner( + token: str, + filename: str, + mime: str, + b64: str, +) -> tuple[str, str]: + cfg = get_config() + timeout_s = cfg.get_float("asset.upload_timeout", 60.0) + + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + + payload = orjson.dumps({ + "fileName": filename, + "fileMimeType": mime, + "content": b64, + }) + headers = build_http_headers(token, lease=lease) + kwargs = build_session_kwargs(lease=lease) + + try: + async with ResettableSession(**kwargs) as session: + response = await session.post( + _UPLOAD_URL, + headers = headers, + data = payload, + timeout = timeout_s, + ) + + body_bytes = response.content + if response.status_code != 200: + body_text = body_bytes.decode("utf-8", "replace")[:300] + logger.error( + "asset upload request failed: status={} body={}", + response.status_code, body_text, + ) + is_cloudflare = "just a moment" in body_text.lower() + await proxy.feedback( + lease, + build_feedback(response.status_code, is_cloudflare=is_cloudflare), + ) + raise UpstreamError( + f"Asset upload returned {response.status_code}", + status = response.status_code, + body = body_text, + ) + + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), + ) + + result = orjson.loads(body_bytes) + file_id = result.get("fileMetadataId") or result.get("fileId", "") + file_uri = result.get("fileUri", "") + logger.info("asset upload completed: filename={!r} file_id={}", filename, file_id) + return file_id, file_uri + + except UpstreamError: + raise + except Exception as exc: + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR), + ) + raise UpstreamError(f"Asset upload transport error: {exc}") from exc + + +async def upload_from_input(token: str, file_input: str) -> tuple[str, str]: + """High-level helper: parse *file_input* (URL or data URI) and upload. + + Returns ``(file_id, file_uri)``. + """ + if _is_url(file_input): + # Fetch the remote URL and re-upload as base64. + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + try: + headers = build_http_headers(token, lease=lease) + kwargs = build_session_kwargs(lease=lease) + async with ResettableSession(**kwargs) as session: + resp = await session.get(file_input, headers=headers, timeout=30.0) + raw = resp.content + if resp.status_code != 200: + await proxy.feedback( + lease, + ProxyFeedback( + kind = ProxyFeedbackKind.UPSTREAM_5XX if resp.status_code >= 500 + else ProxyFeedbackKind.FORBIDDEN, + status_code = resp.status_code, + ), + ) + raise UpstreamError( + f"Failed to fetch input URL: {resp.status_code}", + status = resp.status_code, + ) + mime = (resp.headers.get("content-type", "").split(";")[0].strip() + or "application/octet-stream") + filename = file_input.split("/")[-1].split("?")[0] or "download" + b64 = base64.b64encode(raw).decode() + except UpstreamError: + raise + except Exception as exc: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + raise UpstreamError(f"Asset fetch transport error: {exc}") from exc + + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS)) + return await upload_file(token, filename, mime, b64) + + # Data URI + filename, b64, mime = parse_data_uri(file_input) + return await upload_file(token, filename, mime, b64) + + +def resolve_uploaded_asset_reference(token: str, file_id: str, file_uri: str) -> str: + """Resolve an uploaded asset to the content URL required by image-edit.""" + user_id = _extract_user_id(token) + url = resolve_asset_reference(file_id, file_uri, user_id=user_id) + if url: + return url + raise UpstreamError("Could not resolve uploaded asset reference URL") + + +def _extract_user_id(token: str) -> str | None: + cookie = build_sso_cookie(token) + match = _X_USER_ID_RE.search(cookie) + if match: + return match.group(1) + return None + + +__all__ = [ + "upload_file", + "upload_from_input", + "parse_data_uri", + "resolve_uploaded_asset_reference", +] diff --git a/app/dataplane/reverse/transport/assets.py b/app/dataplane/reverse/transport/assets.py new file mode 100644 index 0000000000000000000000000000000000000000..b786447ff53ff879f846b4644bf5e5f95e138ed4 --- /dev/null +++ b/app/dataplane/reverse/transport/assets.py @@ -0,0 +1,232 @@ +"""Asset management transport — list, delete, download. + +All functions acquire a proxy lease internally, execute the upstream call, +give feedback, and return results to the caller. +""" + +import asyncio +from typing import Any, AsyncGenerator, Dict, Optional + +from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.reverse.protocol.xai_assets import ( + ASSETS_LIST_URL, + asset_delete_url, + infer_content_type, + resolve_download_url, +) +from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback +from app.dataplane.reverse.transport.http import ( + delete_json, + get_bytes_stream, + get_json, +) +from app.platform.config.snapshot import get_config +from app.platform.errors import UpstreamError +from app.platform.logging.logger import logger + +# Global semaphores — limit concurrent transport calls across all callers. +# Lazily initialised so the event loop is guaranteed to be running on first use. +_list_sem: asyncio.Semaphore | None = None +_delete_sem: asyncio.Semaphore | None = None + +def _get_list_sem() -> asyncio.Semaphore: + global _list_sem + if _list_sem is None: + n = max(1, int(get_config("batch.asset_list_concurrency", 50))) + _list_sem = asyncio.Semaphore(n) + return _list_sem + +def _get_delete_sem() -> asyncio.Semaphore: + global _delete_sem + if _delete_sem is None: + n = max(1, int(get_config("batch.asset_delete_concurrency", 50))) + _delete_sem = asyncio.Semaphore(n) + return _delete_sem + + +# ------------------------------------------------------------------ +# List assets +# ------------------------------------------------------------------ + +async def list_assets( + token: str, + params: Optional[Dict[str, Any]] = None, +) -> dict: + """GET /rest/assets and return the JSON response. + + Args: + token: SSO session token. + params: Optional query parameters (e.g. ``{"cursor": "...", "limit": 50}``). + """ + async with _get_list_sem(): + return await _list_assets_inner(token, params) + + +async def _list_assets_inner( + token: str, + params: Optional[Dict[str, Any]] = None, +) -> dict: + cfg = get_config() + timeout_s = cfg.get_float("asset.list_timeout", 30.0) + + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.ASSET, kind=RequestKind.HTTP) + + try: + result = await get_json( + ASSETS_LIST_URL, + token, + params = params, + lease = lease, + timeout_s = timeout_s, + origin = "https://grok.com", + referer = "https://grok.com/files", + ) + except UpstreamError as exc: + await proxy.feedback( + lease, + upstream_feedback(exc), + ) + raise + except Exception as exc: + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR), + ) + raise UpstreamError(f"list_assets: transport error: {exc}") from exc + + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), + ) + return result + + +# ------------------------------------------------------------------ +# Delete asset +# ------------------------------------------------------------------ + +async def delete_asset(token: str, asset_id: str) -> dict: + """DELETE /rest/assets-metadata/{asset_id} and return the JSON body (may be {}).""" + async with _get_delete_sem(): + return await _delete_asset_inner(token, asset_id) + + +async def _delete_asset_inner(token: str, asset_id: str) -> dict: + cfg = get_config() + timeout_s = cfg.get_float("asset.delete_timeout", 30.0) + + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.ASSET, kind=RequestKind.HTTP) + + try: + result = await delete_json( + asset_delete_url(asset_id), + token, + lease = lease, + timeout_s = timeout_s, + origin = "https://grok.com", + referer = "https://grok.com/files", + ) + except UpstreamError as exc: + await proxy.feedback( + lease, + upstream_feedback(exc), + ) + raise + except Exception as exc: + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR), + ) + raise UpstreamError(f"delete_asset: transport error: {exc}") from exc + + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), + ) + logger.debug("asset deletion completed: asset_id={}", asset_id) + return result + + +# ------------------------------------------------------------------ +# Download asset (streaming) +# ------------------------------------------------------------------ + +async def download_asset( + token: str, + file_path: str, +) -> tuple[AsyncGenerator[bytes, None], Optional[str]]: + """Stream asset bytes from assets.grok.com. + + Args: + token: SSO session token. + file_path: URL, absolute, or relative path of the asset. + + Returns: + ``(byte_stream, content_type)`` — an async generator of raw bytes and + a best-guess MIME type (may be ``None`` if unknown). + """ + cfg = get_config() + timeout_s = cfg.get_float("asset.download_timeout", 120.0) + + url, origin, referer = resolve_download_url(file_path) + content_type = infer_content_type(url) + + if content_type and content_type.startswith("video/"): + accept = "video/mp4,video/*,*/*;q=0.8" + elif content_type and content_type.startswith("image/"): + accept = "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8" + else: + accept = "*/*" + + extra: Dict[str, str] = { + "Accept": accept, + "Cache-Control": "no-cache", + "Pragma": "no-cache", + "Priority": "u=0, i", + "Sec-Fetch-Dest": "document", + "Sec-Fetch-Mode": "navigate", + "Sec-Fetch-Site": "none", + "Sec-Fetch-User": "?1", + "Upgrade-Insecure-Requests": "1", + } + + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.ASSET, kind=RequestKind.HTTP) + + try: + stream = await get_bytes_stream( + url, + token, + lease = lease, + timeout_s = timeout_s, + origin = origin, + referer = referer, + extra_headers = extra, + ) + except UpstreamError as exc: + await proxy.feedback( + lease, + upstream_feedback(exc), + ) + raise + except Exception as exc: + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR), + ) + raise UpstreamError(f"download_asset: transport error: {exc}") from exc + + # Feedback is deferred: the caller drains the stream and must not rely + # on the lease being reported here. We report success eagerly since + # the transport already confirmed 200. + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), + ) + return stream, content_type + + +__all__ = ["list_assets", "delete_asset", "download_asset"] diff --git a/app/dataplane/reverse/transport/grpc_web.py b/app/dataplane/reverse/transport/grpc_web.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc0a673c820feea9462e6b9bf64e657d7f75d6b --- /dev/null +++ b/app/dataplane/reverse/transport/grpc_web.py @@ -0,0 +1,77 @@ +"""gRPC-Web POST transport. + +Sends a pre-framed gRPC-Web request to *url* and returns the parsed +``(messages, trailers)`` tuple. Proxy lease is accepted from outside so +the caller controls acquisition and feedback. +""" + +from typing import Dict, List, Tuple + +from app.platform.logging.logger import logger +from app.platform.errors import UpstreamError +from app.platform.net.grpc import GrpcClient +from app.control.proxy.models import ProxyLease +from app.dataplane.proxy.adapters.headers import build_http_headers +from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs + +# Headers required by every gRPC-Web call. +_GRPC_WEB_HEADERS: Dict[str, str] = { + "Content-Type": "application/grpc-web+proto", + "Accept": "*/*", + "x-grpc-web": "1", + "x-user-agent": "connect-es/2.1.1", + "Cache-Control": "no-cache", + "Pragma": "no-cache", + "Sec-Fetch-Dest": "empty", +} + + +async def post_grpc_web( + url: str, + token: str, + payload: bytes, + *, + lease: ProxyLease | None = None, + timeout_s: float = 30.0, + origin: str = "https://grok.com", + referer: str = "https://grok.com/", + session: "ResettableSession | None" = None, +) -> Tuple[List[bytes], Dict[str, str]]: + """POST a gRPC-Web frame to *url*. + + Pass *session* to reuse an existing connection (avoids a new TLS handshake). + When *session* is ``None`` a fresh session is created and closed automatically. + + Returns: + ``(messages, trailers)`` — raw protobuf message payloads and the + gRPC trailer map (includes ``grpc-status``, ``grpc-message``). + + Raises: + ``UpstreamError`` if the HTTP response status is not 200. + """ + headers = build_http_headers( + token, + content_type = "application/grpc-web+proto", + origin = origin, + referer = referer, + lease = lease, + ) + headers.update(_GRPC_WEB_HEADERS) + + async def _do(s: "ResettableSession") -> Tuple[List[bytes], Dict[str, str]]: + response = await s.post(url, headers=headers, data=payload, timeout=timeout_s) + body_bytes = response.content + if response.status_code != 200: + body_text = body_bytes.decode("utf-8", "replace")[:300] + logger.error("grpc-web post failed: url={} status={} body={}", url, response.status_code, body_text) + raise UpstreamError(f"Upstream returned {response.status_code}", status=response.status_code, body=body_text) + return GrpcClient.parse_response(body_bytes, content_type=response.headers.get("content-type"), headers=response.headers) + + if session is not None: + return await _do(session) + + async with ResettableSession(**build_session_kwargs(lease=lease)) as s: + return await _do(s) + + +__all__ = ["post_grpc_web"] diff --git a/app/dataplane/reverse/transport/http.py b/app/dataplane/reverse/transport/http.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9686a34d08e99fb876c589ebf97fc672667d0b --- /dev/null +++ b/app/dataplane/reverse/transport/http.py @@ -0,0 +1,303 @@ +"""HTTP transport for reverse-proxy requests. + +Wraps curl_cffi AsyncSession; handles proxy selection, header building, +retry-on-reset, and timeout. +""" + +from typing import AsyncGenerator + +from app.platform.logging.logger import logger +from app.platform.errors import UpstreamError +from app.control.proxy.models import ProxyLease +from app.dataplane.proxy.adapters.headers import build_http_headers +from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs + + +async def post_stream( + url: str, + token: str, + payload: bytes, + *, + lease: ProxyLease | None = None, + timeout_s: float = 120.0, + content_type: str = "application/json", + origin: str = "https://grok.com", + referer: str = "https://grok.com/", +) -> AsyncGenerator[str, None]: + """POST *url* and yield SSE lines from the streaming response. + + Raises ``UpstreamError`` on non-200 status. + """ + headers = build_http_headers( + token, + content_type=content_type, + origin=origin, + referer=referer, + lease=lease, + ) + kwargs = build_session_kwargs(lease=lease) + + session = ResettableSession(**kwargs) + try: + response = await session.post( + url, + headers=headers, + data=payload, + timeout=timeout_s, + stream=True, + ) + + if response.status_code != 200: + try: + body = (response.content).decode("utf-8", "replace")[:400] + except Exception: + body = "" + logger.error( + "http stream post failed: url={} status={} body={}", + url, + response.status_code, + body, + ) + await session.close() + raise UpstreamError( + f"Upstream returned {response.status_code}", + status=response.status_code, + body=body, + ) + except Exception: + try: + await session.close() + except Exception: + pass + raise + + async def _lines() -> AsyncGenerator[str, None]: + try: + async for line in response.aiter_lines(): + yield line + finally: + try: + await session.close() + except Exception: + pass + + return _lines() + + +async def post_json( + url: str, + token: str, + payload: bytes, + *, + lease: ProxyLease | None = None, + timeout_s: float = 30.0, + content_type: str = "application/json", + origin: str = "https://grok.com", + referer: str = "https://grok.com/", + session: "ResettableSession | None" = None, +) -> dict: + """POST *url* and return parsed JSON response body. + + Pass *session* to reuse an existing connection (avoids a new TLS handshake). + When *session* is ``None`` a fresh session is created and closed automatically. + """ + headers = build_http_headers( + token, content_type=content_type, origin=origin, referer=referer, lease=lease + ) + + import orjson + + async def _do(s: "ResettableSession") -> dict: + response = await s.post(url, headers=headers, data=payload, timeout=timeout_s) + body_bytes = response.content + if response.status_code not in (200, 201, 204): + body_text = body_bytes.decode("utf-8", "replace")[:400] + logger.warning( + "http json post failed: url={} status={}", url, response.status_code + ) + raise UpstreamError( + f"Upstream returned {response.status_code}", + status=response.status_code, + body=body_text, + ) + return orjson.loads(body_bytes) if body_bytes.strip() else {} + + if session is not None: + return await _do(session) + + async with ResettableSession(**build_session_kwargs(lease=lease)) as s: + return await _do(s) + + +async def get_json( + url: str, + token: str, + *, + params: dict | None = None, + lease: ProxyLease | None = None, + timeout_s: float = 30.0, + origin: str = "https://grok.com", + referer: str = "https://grok.com/", +) -> dict: + """GET *url* and return parsed JSON response body.""" + headers = build_http_headers( + token, + content_type="application/json", + origin=origin, + referer=referer, + lease=lease, + ) + kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**kwargs) as session: + response = await session.get( + url, + headers=headers, + params=params, + timeout=timeout_s, + ) + + body_bytes = response.content + if response.status_code != 200: + body_text = body_bytes.decode("utf-8", "replace")[:400] + logger.error( + "http json get failed: url={} status={} body={}", + url, + response.status_code, + body_text, + ) + raise UpstreamError( + f"Upstream returned {response.status_code}", + status=response.status_code, + body=body_text, + ) + + import orjson + + return orjson.loads(body_bytes) + + +async def delete_json( + url: str, + token: str, + *, + lease: ProxyLease | None = None, + timeout_s: float = 30.0, + origin: str = "https://grok.com", + referer: str = "https://grok.com/", +) -> dict: + """DELETE *url* and return parsed JSON response body (may be empty → {}).""" + headers = build_http_headers( + token, + content_type="application/json", + origin=origin, + referer=referer, + lease=lease, + ) + kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**kwargs) as session: + response = await session.delete( + url, + headers=headers, + timeout=timeout_s, + ) + + body_bytes = response.content + if response.status_code not in (200, 204): + body_text = body_bytes.decode("utf-8", "replace")[:400] + logger.error( + "http json delete failed: url={} status={} body={}", + url, + response.status_code, + body_text, + ) + raise UpstreamError( + f"Upstream returned {response.status_code}", + status=response.status_code, + body=body_text, + ) + + if not body_bytes.strip(): + return {} + import orjson + + return orjson.loads(body_bytes) + + +async def get_bytes_stream( + url: str, + token: str, + *, + lease: ProxyLease | None = None, + timeout_s: float = 120.0, + origin: str = "https://assets.grok.com", + referer: str = "https://grok.com/", + extra_headers: dict | None = None, +) -> AsyncGenerator[bytes, None]: + """GET *url* and yield raw bytes chunks from the streaming response. + + Raises ``UpstreamError`` on non-200 status. + """ + headers = build_http_headers( + token, + content_type=None, + origin=origin, + referer=referer, + lease=lease, + ) + if extra_headers: + headers.update(extra_headers) + if headers.get("Sec-Fetch-Mode") == "navigate": + headers.pop("Content-Type", None) + headers.pop("Origin", None) + kwargs = build_session_kwargs(lease=lease) + + session = ResettableSession(**kwargs) + try: + response = await session.get( + url, + headers=headers, + timeout=timeout_s, + stream=True, + allow_redirects=True, + ) + if response.status_code != 200: + try: + body = (response.content).decode("utf-8", "replace")[:400] + except Exception: + body = "" + logger.error( + "http byte stream get failed: url={} status={} body={}", + url, + response.status_code, + body, + ) + await session.close() + raise UpstreamError( + f"Upstream returned {response.status_code}", + status=response.status_code, + body=body, + ) + except Exception: + try: + await session.close() + except Exception: + pass + raise + + async def _chunks() -> AsyncGenerator[bytes, None]: + try: + async for chunk in response.aiter_content(): + if chunk: + yield chunk + finally: + try: + await session.close() + except Exception: + pass + + return _chunks() + + +__all__ = ["post_stream", "post_json", "get_json", "delete_json", "get_bytes_stream"] diff --git a/app/dataplane/reverse/transport/imagine_ws.py b/app/dataplane/reverse/transport/imagine_ws.py new file mode 100644 index 0000000000000000000000000000000000000000..e817cc8120959ebdd7f77bc00defd47d5deff8d9 --- /dev/null +++ b/app/dataplane/reverse/transport/imagine_ws.py @@ -0,0 +1,381 @@ +"""Imagine WebSocket reverse transport. + +Protocol (per round): + Client → reset message + Client → prompt message + Server → N × (start_stage json → image frames → completed json) + Server → [may close WS, or keep open for next round] + +One WS connection is reused across rounds until the server closes it or n +images have been collected. This avoids a TLS handshake per round when +requesting more images than a single round produces (speed=6, quality=4). +""" + +import asyncio +import time +import uuid +from dataclasses import dataclass, field +from typing import Any, AsyncGenerator + +import aiohttp +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback +from app.dataplane.proxy.adapters.headers import build_ws_headers +from app.dataplane.reverse.protocol.xai_image import ( + WS_IMAGINE_URL, + build_reset_message, + build_request_message, + parse_image_url, + parse_json_frame, +) +from .websocket import WebSocketClient + +_client = WebSocketClient() +_INTER_ROUND_WAIT_S = 2.0 + + +# --------------------------------------------------------------------------- +# Slot state +# --------------------------------------------------------------------------- + +@dataclass +class _Slot: + """Tracks one in-flight image generation slot.""" + image_id: str + order: int + width: int + height: int + last_blob: str = field(default="", repr=False) + last_url: str = "" + done: bool = False + progress: int = 0 + + +# --------------------------------------------------------------------------- +# Internal helpers +# --------------------------------------------------------------------------- + +def _final_event(slot: _Slot, r_rated: bool = False) -> dict[str, Any]: + return { + "type": "image", + "image_id": slot.image_id, + "order": slot.order, + "stage": "final", + "blob": slot.last_blob, + "url": slot.last_url, + "width": slot.width, + "height": slot.height, + "is_final": True, + "moderated": False, + "r_rated": r_rated, + } + + +async def _probe_ws_closed(ws: aiohttp.ClientWebSocketResponse, wait_s: float) -> bool: + """Wait up to *wait_s* seconds for a CLOSE frame. + + Returns True if the server closed the connection, False if the connection + appears to still be alive (timeout expired with no CLOSE received). + """ + try: + msg = await asyncio.wait_for(ws.receive(), timeout=wait_s) + return msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR) + except asyncio.TimeoutError: + return False + except Exception: + return True + + +# --------------------------------------------------------------------------- +# Single-round generator +# --------------------------------------------------------------------------- + +async def _stream_round( + ws: aiohttp.ClientWebSocketResponse, + prompt: str, + *, + aspect_ratio: str, + enable_nsfw: bool, + enable_pro: bool, + needed: int, + stream_timeout_s: float, + round_timeout_s: float, + inter_round_wait_s: float, +) -> AsyncGenerator[dict[str, Any], None]: + """Drive one round of image generation on an already-open WS. + + Sends reset + prompt, then processes frames until all slots are completed + or the WS closes. Always yields a ``{type: "_meta", ws_closed: bool}`` + sentinel as the very last item so the caller knows whether to reconnect. + """ + request_id = str(uuid.uuid4()) + try: + await ws.send_json(build_reset_message()) + await ws.send_json(build_request_message( + request_id, prompt, aspect_ratio, enable_nsfw, enable_pro, + )) + except Exception as exc: + yield {"type": "error", "error_code": "send_failed", "error": str(exc)} + yield {"type": "_meta", "ws_closed": True} + return + + slots: dict[str, _Slot] = {} + round_completed: int = 0 + round_start = time.monotonic() + + while True: + elapsed = time.monotonic() - round_start + if elapsed >= round_timeout_s: + logger.warning("imagine round timed out: elapsed_s={:.1f}", elapsed) + for slot in slots.values(): + if not slot.done: + if slot.last_blob: + yield _final_event(slot) + else: + yield { + "type": "error", + "error_code": "slot_incomplete", + "error": f"slot {slot.image_id[:8]} timed out", + } + yield {"type": "_meta", "ws_closed": False} + return + + recv_timeout = min(stream_timeout_s, round_timeout_s - elapsed) + try: + ws_msg = await asyncio.wait_for(ws.receive(), timeout=recv_timeout) + except asyncio.TimeoutError: + # No frame arrived — check if all known slots are already done. + if slots and all(s.done for s in slots.values()): + ws_closed = await _probe_ws_closed(ws, inter_round_wait_s) + yield {"type": "_meta", "ws_closed": ws_closed} + return + continue + + # ── TEXT frames ────────────────────────────────────────────────────── + if ws_msg.type == aiohttp.WSMsgType.TEXT: + try: + msg = orjson.loads(ws_msg.data) + except Exception: + continue + + msg_type = msg.get("type") + + # JSON control frames (start_stage / completed) + if msg_type == "json": + parsed = parse_json_frame(msg) + if parsed is None: + continue + + if parsed["status"] == "start_stage": + iid = parsed["image_id"] + slots[iid] = _Slot( + image_id = iid, + order = parsed["order"], + width = parsed["width"], + height = parsed["height"], + ) + logger.debug( + "imagine slot started: image_id={} order={} width={} height={}", + iid[:8], parsed["order"], parsed["width"], parsed["height"], + ) + yield { + "type": "progress", + "image_id": iid, + "order": parsed["order"], + "progress": 10, + } + + elif parsed["status"] == "completed": + iid = parsed["image_id"] + slot = slots.get(iid) + if slot is None or slot.done: + continue + + slot.done = True + + if parsed["moderated"]: + logger.warning("imagine slot moderated: image_id={}", iid[:8]) + yield {"type": "moderated", "image_id": iid, "order": slot.order} + else: + logger.debug("imagine slot completed: image_id={} order={}", iid[:8], slot.order) + yield _final_event(slot, r_rated=parsed["r_rated"]) + round_completed += 1 + + all_done = slots and all(s.done for s in slots.values()) + if all_done: + ws_closed = await _probe_ws_closed(ws, inter_round_wait_s) + yield {"type": "_meta", "ws_closed": ws_closed} + return + + if round_completed >= needed: + # Have enough this round; leave remaining slots in flight. + yield {"type": "_meta", "ws_closed": False} + return + + # Image blob frames (intermediate previews) + elif msg_type == "image": + url = msg.get("url", "") + blob = msg.get("blob", "") + iid, _ext = parse_image_url(url) + slot = slots.get(iid) + if slot and not slot.done: + slot.last_blob = blob + slot.last_url = url + progress = msg.get("percentage_complete") + try: + parsed_progress = int(float(progress)) if progress is not None else 50 + except (TypeError, ValueError): + parsed_progress = 50 + parsed_progress = max(10, min(99, parsed_progress)) + if parsed_progress > slot.progress: + slot.progress = parsed_progress + yield { + "type": "progress", + "image_id": iid, + "order": slot.order, + "progress": parsed_progress, + } + + # Server-side error + elif msg_type == "error": + err_code = msg.get("err_code") or "upstream_error" + err_msg = msg.get("err_msg") or str(msg) + logger.warning("imagine websocket server error: code={} message={}", err_code, err_msg) + yield {"type": "error", "error_code": err_code, "error": err_msg} + yield {"type": "_meta", "ws_closed": True} + return + + # ── WS closed / error ──────────────────────────────────────────────── + elif ws_msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR): + # Yield best-effort finals for any slots that received a blob but + # never got a completed frame. + for slot in slots.values(): + if not slot.done: + if slot.last_blob: + logger.debug( + "imagine websocket closed with best-effort final: image_id={}", + slot.image_id[:8], + ) + yield _final_event(slot) + else: + logger.warning( + "imagine websocket closed before image data arrived: image_id={}", + slot.image_id[:8], + ) + yield {"type": "_meta", "ws_closed": True} + return + + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- + +async def stream_images( + token: str, + prompt: str, + *, + aspect_ratio: str = "2:3", + n: int = 1, + enable_nsfw: bool = True, + enable_pro: bool = False, +) -> AsyncGenerator[dict[str, Any], None]: + """Stream image events, collecting *n* final images. + + Reuses a single WS connection across multiple rounds when the server keeps + the connection open. Reconnects transparently if the server closes it. + + Yields: + ``{type: "image", is_final: True, ...}`` — final image per slot + ``{type: "moderated", ...}`` — censored slot + ``{type: "error", ...}`` — fatal error (stops iteration) + """ + cfg = get_config() + timeout_s = cfg.get_float("image.timeout", 120.0) + stream_timeout_s = cfg.get_float("image.stream_timeout", 10.0) + inter_round_wait_s = _INTER_ROUND_WAIT_S + + collected = 0 + + while collected < n: + needed = n - collected + + # ── Establish connection ────────────────────────────────────────────── + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.WEBSOCKET) + headers = build_ws_headers(token=token, lease=lease) + + try: + conn = await _client.connect( + WS_IMAGINE_URL, + headers = headers, + timeout = timeout_s, + ws_kwargs = {"heartbeat": 20, "receive_timeout": stream_timeout_s}, + lease = lease, + ) + except Exception as exc: + status = getattr(exc, "status", None) + logger.error("imagine websocket connect failed: error={}", exc) + from app.platform.errors import UpstreamError as _UE + fb = upstream_feedback(_UE("connect failed", status=status)) \ + if status else ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR) + await proxy.feedback(lease, fb) + yield { + "type": "error", + "error_code": "rate_limit_exceeded" if status == 429 else "connection_failed", + "error": str(exc), + } + return + + # ── Run rounds on this connection ───────────────────────────────────── + try: + async with conn as ws: + while collected < n: + needed = n - collected + async for ev in _stream_round( + ws, prompt, + aspect_ratio = aspect_ratio, + enable_nsfw = enable_nsfw, + enable_pro = enable_pro, + needed = needed, + stream_timeout_s = stream_timeout_s, + round_timeout_s = timeout_s, + inter_round_wait_s = inter_round_wait_s, + ): + if ev["type"] == "_meta": + ws_closed = ev["ws_closed"] + break # exit inner for-loop; handle ws_closed below + if ev.get("is_final"): + collected += 1 + yield ev + if ev["type"] == "error": + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + return + else: + # _stream_round exhausted without a _meta — shouldn't happen + ws_closed = True + + if ws_closed or collected >= n: + break # exit inner while; reconnect or finish + + except aiohttp.ClientError as exc: + logger.error("imagine websocket connection failed: error={}", exc) + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + yield {"type": "error", "error_code": "connection_failed", "error": str(exc)} + return + + if collected >= n: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200)) + return + + # Server closed the connection but we still need more images → reconnect. + # Give back the current lease before acquiring a new one on the next iteration. + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200)) + logger.info("imagine websocket reconnecting: remaining_images={} requested_images={}", n - collected, n) + + +__all__ = ["stream_images"] diff --git a/app/dataplane/reverse/transport/livekit.py b/app/dataplane/reverse/transport/livekit.py new file mode 100644 index 0000000000000000000000000000000000000000..7cd95d6f8c49b0411fe187091520228016cc1ea1 --- /dev/null +++ b/app/dataplane/reverse/transport/livekit.py @@ -0,0 +1,145 @@ +"""LiveKit transport — fetch session token and open the WebSocket. + +``fetch_livekit_token`` POSTs to /rest/livekit/tokens with proxy support. +``connect_livekit_ws`` opens the wss:// connection and returns a +``WebSocketConnection`` that the products layer can read/write. +""" + +from typing import Any, Dict, Optional + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import UpstreamError +from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.headers import build_http_headers, build_ws_headers +from app.dataplane.reverse.protocol.xai_livekit import ( + LIVEKIT_TOKEN_URL, + build_token_request_payload, + build_ws_url, +) +from app.dataplane.reverse.transport.http import post_json +from app.dataplane.reverse.transport.websocket import WebSocketClient, WebSocketConnection +from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback + + +# ------------------------------------------------------------------ +# Token fetch +# ------------------------------------------------------------------ + +async def fetch_livekit_token( + token: str, + *, + voice: str = "ara", + personality: str = "assistant", + speed: float = 1.0, + custom_instruction: str = "", +) -> Dict[str, Any]: + """Fetch a LiveKit session token for *token*. + + Returns the parsed JSON body from /rest/livekit/tokens. + Raises ``UpstreamError`` on failure. + """ + cfg = get_config() + timeout_s = cfg.get_float("voice.timeout", 60.0) + + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP) + + payload = build_token_request_payload( + voice = voice, + personality = personality, + speed = speed, + custom_instruction = custom_instruction, + ) + + try: + result = await post_json( + LIVEKIT_TOKEN_URL, + token, + payload, + lease = lease, + timeout_s = timeout_s, + origin = "https://grok.com", + referer = "https://grok.com/", + ) + except UpstreamError as exc: + await proxy.feedback(lease, upstream_feedback(exc)) + raise + except Exception as exc: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + raise UpstreamError(f"fetch_livekit_token: transport error: {exc}") from exc + + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), + ) + logger.debug("livekit session token fetched") + return result + + +# ------------------------------------------------------------------ +# WebSocket connect +# ------------------------------------------------------------------ + +async def connect_livekit_ws( + token: str, + access_token: str, + *, + timeout_s: Optional[float] = None, +) -> WebSocketConnection: + """Open a WebSocket connection to the LiveKit RTC endpoint. + + Args: + token: SSO session cookie — used for WebSocket headers. + access_token: Short-lived LiveKit token from ``fetch_livekit_token``. + timeout_s: Connection + read timeout; defaults to ``voice.timeout`` config. + + Returns: + ``WebSocketConnection`` wrapping the live aiohttp WS connection. + + Raises: + ``UpstreamError`` on connection failure. + """ + cfg = get_config() + timeout = timeout_s if timeout_s is not None else cfg.get_float("voice.timeout", 120.0) + + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.WEBSOCKET) + + url = build_ws_url(access_token) + headers = build_ws_headers(token=token, lease=lease) + client = WebSocketClient() + + async def _on_close() -> None: + try: + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), + ) + except Exception: + pass + + try: + connection = await client.connect( + url, + headers = headers, + timeout = timeout, + lease = lease, + on_close = _on_close, + ) + except Exception as exc: + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR), + ) + logger.error("livekit websocket connect failed: error={}", exc) + raise UpstreamError(f"connect_livekit_ws: {exc}") from exc + + logger.debug("livekit websocket connected: url={}", url) + return connection + + +__all__ = ["fetch_livekit_token", "connect_livekit_ws"] diff --git a/app/dataplane/reverse/transport/media.py b/app/dataplane/reverse/transport/media.py new file mode 100644 index 0000000000000000000000000000000000000000..4147fa72888208000b02d6bad8fed74b2b7a444f --- /dev/null +++ b/app/dataplane/reverse/transport/media.py @@ -0,0 +1,114 @@ +"""Media transport — create post, create link, upscale video. + +All three endpoints are simple JSON POST calls with proxy lifecycle. +""" + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import UpstreamError +from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind +from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.reverse.protocol.xai_video import ( + MEDIA_LINK_URL, + MEDIA_POST_URL, + VIDEO_UPSCALE_URL, + build_media_link_payload, + build_media_post_payload, + build_upscale_payload, +) +from app.dataplane.reverse.transport.http import post_json + + +async def _post_with_proxy( + url: str, + token: str, + payload: dict, + *, + label: str, + timeout_key: str = "video.timeout", + referer: str = "https://grok.com", +) -> dict: + """Shared helper: acquire proxy → POST JSON → feedback → return body.""" + cfg = get_config() + timeout_s = cfg.get_float(timeout_key, 60.0) + + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP) + + try: + result = await post_json( + url, + token, + orjson.dumps(payload), + lease = lease, + timeout_s = timeout_s, + origin = "https://grok.com", + referer = referer, + ) + except UpstreamError as exc: + await proxy.feedback( + lease, + upstream_feedback(exc), + ) + raise + except Exception as exc: + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR), + ) + raise UpstreamError(f"{label}: transport error: {exc}") from exc + + await proxy.feedback( + lease, + ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), + ) + logger.debug("media request completed: operation={}", label) + return result + + +# ------------------------------------------------------------------ +# Public API +# ------------------------------------------------------------------ + +async def create_media_post( + token: str, + media_type: str, + media_url: str = "", + prompt: str = "", + referer: str = "https://grok.com/imagine", +) -> dict: + """POST /rest/media/post/create — create a media post.""" + payload = build_media_post_payload( + media_type = media_type, + media_url = media_url, + prompt = prompt, + ) + return await _post_with_proxy( + MEDIA_POST_URL, token, payload, + label = "create_media_post", + referer = referer, + ) + + +async def create_media_link(token: str, post_id: str) -> dict: + """POST /rest/media/post/create-link — get a shareable link for a post.""" + payload = build_media_link_payload(post_id) + return await _post_with_proxy( + MEDIA_LINK_URL, token, payload, + label = "create_media_link", + ) + + +async def upscale_video(token: str, video_id: str) -> dict: + """POST /rest/media/video/upscale — upscale a video.""" + payload = build_upscale_payload(video_id) + return await _post_with_proxy( + VIDEO_UPSCALE_URL, token, payload, + label = "upscale_video", + ) + + +__all__ = ["create_media_post", "create_media_link", "upscale_video"] diff --git a/app/dataplane/reverse/transport/websocket.py b/app/dataplane/reverse/transport/websocket.py new file mode 100644 index 0000000000000000000000000000000000000000..1c0959df4008970ac6bf3621b591c9ffa81f442e --- /dev/null +++ b/app/dataplane/reverse/transport/websocket.py @@ -0,0 +1,139 @@ +"""WebSocket transport with proxy and SOCKS support.""" + +import ssl +from typing import Any, Awaitable, Callable, Mapping, Optional +from urllib.parse import urlparse + +import aiohttp +import certifi +from aiohttp_socks import ProxyConnector + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.control.proxy.models import ProxyLease + + +def _ssl_ctx() -> ssl.SSLContext: + ctx = ssl.create_default_context() + ctx.load_verify_locations(certifi.where()) + return ctx + + +def _normalize_socks(proxy_url: str) -> tuple[str, Optional[bool]]: + scheme = urlparse(proxy_url).scheme.lower() + rdns: Optional[bool] = None + base = scheme + if scheme == "socks": + base, rdns = "socks5", True + elif scheme == "socks5h": + base, rdns = "socks5", True + elif scheme == "socks4a": + base, rdns = "socks4", True + if base != scheme: + proxy_url = proxy_url.replace(f"{scheme}://", f"{base}://", 1) + return proxy_url, rdns + + +def _build_connector( + proxy_url: str, + ssl_ctx: ssl.SSLContext, +) -> tuple[aiohttp.BaseConnector, str | None]: + if not proxy_url: + return aiohttp.TCPConnector(ssl=ssl_ctx), None + scheme = urlparse(proxy_url).scheme.lower() + if scheme.startswith("socks"): + normalized, rdns = _normalize_socks(proxy_url) + kwargs: dict = {"ssl": ssl_ctx} + if rdns is not None: + kwargs["rdns"] = rdns + logger.debug("websocket connector selected: proxy_type=socks proxy_url={}", proxy_url) + return ProxyConnector.from_url(normalized, **kwargs), None + logger.debug("websocket connector selected: proxy_type=http proxy_url={}", proxy_url) + return aiohttp.TCPConnector(ssl=ssl_ctx), proxy_url + + +class WebSocketConnection: + """Wraps aiohttp WebSocketResponse with lifecycle cleanup.""" + + def __init__( + self, + session: aiohttp.ClientSession, + ws: aiohttp.ClientWebSocketResponse, + *, + on_close: Callable[[], Awaitable[None]] | None = None, + ) -> None: + self.session = session + self.ws = ws + self._on_close = on_close + + async def close(self) -> None: + if not self.ws.closed: + await self.ws.close() + await self.session.close() + if self._on_close: + await self._on_close() + self._on_close = None + + async def __aenter__(self) -> aiohttp.ClientWebSocketResponse: + return self.ws + + async def __aexit__(self, *_: Any) -> None: + await self.close() + + +class WebSocketClient: + """Establish WebSocket connections through optional proxy.""" + + def __init__(self, proxy: str | None = None) -> None: + self._proxy_override = proxy + self._ssl = _ssl_ctx() + + async def connect( + self, + url: str, + headers: Optional[Mapping[str, str]] = None, + timeout: Optional[float] = None, + ws_kwargs: Optional[Mapping[str, Any]] = None, + *, + lease: ProxyLease | None = None, + on_close: Callable[[], Awaitable[None]] | None = None, + ) -> WebSocketConnection: + proxy_url = self._proxy_override or (lease.proxy_url if lease else "") + connector, http_proxy = _build_connector(proxy_url, self._ssl) + + cfg = get_config() + total_s = float(timeout) if timeout is not None else cfg.get_float("voice.timeout", 120.0) + client_timeout = aiohttp.ClientTimeout(total=total_s) + session = aiohttp.ClientSession(connector=connector, timeout=client_timeout) + + try: + extra: dict[str, Any] = dict(ws_kwargs or {}) + skip_ssl = cfg.get_bool("proxy.egress.skip_ssl_verify", False) and bool(proxy_url) + + if skip_ssl and urlparse(proxy_url).scheme.lower() == "https": + proxy_ssl = ssl.create_default_context() + proxy_ssl.check_hostname = False + proxy_ssl.verify_mode = ssl.CERT_NONE + try: + ws = await session.ws_connect( + url, headers=headers, proxy=http_proxy, + ssl=self._ssl, proxy_ssl=proxy_ssl, **extra, + ) + except TypeError: + ws = await session.ws_connect( + url, headers=headers, proxy=http_proxy, + ssl=self._ssl, **extra, + ) + else: + ws = await session.ws_connect( + url, headers=headers, proxy=http_proxy, + ssl=self._ssl, **extra, + ) + + return WebSocketConnection(session, ws, on_close=on_close) + except Exception: + await session.close() + raise + + +__all__ = ["WebSocketClient", "WebSocketConnection"] diff --git a/app/dataplane/reverse/types.py b/app/dataplane/reverse/types.py new file mode 100644 index 0000000000000000000000000000000000000000..c14abd082aaee9c05abfbb27cce1dda34fea45aa --- /dev/null +++ b/app/dataplane/reverse/types.py @@ -0,0 +1,77 @@ +"""Reverse pipeline data types — ReversePlan, ReverseLeaseSet, ReverseResult.""" + +from dataclasses import dataclass, field +from enum import IntEnum, auto +from typing import Any + +from app.control.proxy.models import ProxyLease + + +# --------------------------------------------------------------------------- +# Result classification +# --------------------------------------------------------------------------- + +class ResultCategory(IntEnum): + """Outcome category for upstream responses.""" + SUCCESS = 0 + RATE_LIMITED = auto() + AUTH_FAILURE = auto() + FORBIDDEN = auto() + NOT_FOUND = auto() + UPSTREAM_5XX = auto() + TRANSPORT_ERR = auto() + UNKNOWN = auto() + + +# --------------------------------------------------------------------------- +# Transport type hint +# --------------------------------------------------------------------------- + +class TransportKind(IntEnum): + HTTP_SSE = 0 # streaming POST (SSE lines) + HTTP_JSON = 1 # single-shot POST → JSON + WEBSOCKET = 2 # WebSocket-based protocol + GRPC_WEB = 3 # gRPC-Web over HTTP + + +# --------------------------------------------------------------------------- +# Core dataclasses +# --------------------------------------------------------------------------- + +@dataclass(slots=True) +class ReversePlan: + """Describes how a single upstream call should be executed.""" + endpoint: str # full URL + transport_kind: TransportKind + pool_candidates: tuple[int, ...] # ordered pool IDs to try (e.g. (0,1,2)) + mode_id: int # 0=auto, 1=fast, 2=expert, 3=heavy + timeout_s: float = 120.0 + content_type: str = "application/json" + origin: str = "https://grok.com" + referer: str = "https://grok.com/" + extra: dict[str, Any] = field(default_factory=dict) + + +@dataclass(slots=True) +class ReverseLeaseSet: + """Holds both account and proxy leases for one request cycle.""" + account_idx: int # slot index in AccountRuntimeTable + account_token: str + proxy_lease: ProxyLease | None = None + + +@dataclass(slots=True) +class ReverseResult: + """Outcome of a single upstream request.""" + category: ResultCategory + status_code: int = 0 + body: str = "" + payload: Any = None # parsed response data (dict / list / None) + error: str = "" + latency_ms: int = 0 + + +__all__ = [ + "ResultCategory", "TransportKind", + "ReversePlan", "ReverseLeaseSet", "ReverseResult", +] diff --git a/app/dataplane/shared/__init__.py b/app/dataplane/shared/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/dataplane/shared/enums.py b/app/dataplane/shared/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..b195bd0479e5695b0352ae642e481c68d9ca7143 --- /dev/null +++ b/app/dataplane/shared/enums.py @@ -0,0 +1,66 @@ +"""Dataplane-local integer enumerations for hot-path array indexing. + +These mirror the control-plane enums but use IntEnum exclusively so they +can be used directly as array indices with zero overhead. +""" + +from enum import IntEnum + + +class ModeId(IntEnum): + AUTO = 0 + FAST = 1 + EXPERT = 2 + HEAVY = 3 + GROK_4_3 = 4 + CONSOLE = 5 # console.x.ai 独立配额 + + +class PoolId(IntEnum): + BASIC = 0 + SUPER = 1 + HEAVY = 2 + + +class StatusId(IntEnum): + ACTIVE = 0 + COOLING = 1 + EXPIRED = 2 + DISABLED = 3 + DELETED = 4 + + +# Map pool string → PoolId integer (used during sync from control plane). +POOL_STR_TO_ID: dict[str, int] = { + "basic": int(PoolId.BASIC), + "super": int(PoolId.SUPER), + "heavy": int(PoolId.HEAVY), +} + +POOL_ID_TO_STR: dict[int, str] = {v: k for k, v in POOL_STR_TO_ID.items()} + +STATUS_STR_TO_ID: dict[str, int] = { + "active": int(StatusId.ACTIVE), + "cooling": int(StatusId.COOLING), + "expired": int(StatusId.EXPIRED), + "disabled": int(StatusId.DISABLED), +} + +ALL_MODE_IDS: tuple[int, ...] = ( + int(ModeId.AUTO), + int(ModeId.FAST), + int(ModeId.EXPERT), + int(ModeId.HEAVY), + int(ModeId.GROK_4_3), + int(ModeId.CONSOLE), +) + +__all__ = [ + "ModeId", + "PoolId", + "StatusId", + "POOL_STR_TO_ID", + "POOL_ID_TO_STR", + "STATUS_STR_TO_ID", + "ALL_MODE_IDS", +] diff --git a/app/dataplane/shared/timing.py b/app/dataplane/shared/timing.py new file mode 100644 index 0000000000000000000000000000000000000000..4d80d6f22e89ec705009921f218770df8d89477b --- /dev/null +++ b/app/dataplane/shared/timing.py @@ -0,0 +1,9 @@ +"""Dataplane clock — re-exports from platform.runtime.clock. + +Provides a canonical import path for hot-path code that needs wall-clock +timestamps without pulling in the full platform package. +""" + +from app.platform.runtime.clock import now_ms, now_s, ms_to_s, s_to_ms + +__all__ = ["now_ms", "now_s", "ms_to_s", "s_to_ms"] diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd63324994fa5665bafd7866ab1dbcfc64f7fab --- /dev/null +++ b/app/main.py @@ -0,0 +1,484 @@ +"""Grok2API application entry point. + +Start with: + uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app + +Multi-worker notes: + - All workers run a lightweight account-directory sync loop (ACCOUNT_SYNC_INTERVAL env, default 30 s). + - Only the worker that wins the advisory file lock runs the heavy AccountRefreshScheduler. + On Linux/macOS this uses fcntl.flock; on Windows it falls back to "always be leader" + (i.e. every worker runs the scheduler — acceptable because Windows deployments are + almost always single-worker anyway). +""" + +import asyncio +import os +import platform +import sys +from contextlib import asynccontextmanager +from pathlib import Path + +from dotenv import load_dotenv +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse +from fastapi.staticfiles import StaticFiles + +from app.platform.logging.logger import logger, setup_logging, reload_logging +from app.platform.config.snapshot import config as _config +from app.platform.errors import AppError +from app.platform.meta import get_project_version +from app.platform.paths import data_path +from app.platform.storage import reconcile_local_media_cache_async + + +load_dotenv() + + +# --------------------------------------------------------------------------- +# Scheduler leader-election via advisory file lock +# --------------------------------------------------------------------------- + +_LOCK_FILE = data_path(".scheduler.lock") +_lock_fd: int | None = None + + +def _try_acquire_scheduler_lock() -> bool: + """Non-blocking attempt to become the scheduler leader. + + Returns True if this worker acquired the lock (i.e. is the leader). + Falls back to True on Windows where fcntl is unavailable. + """ + global _lock_fd + try: + import fcntl + + _LOCK_FILE.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(str(_LOCK_FILE), os.O_CREAT | os.O_WRONLY) + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + _lock_fd = fd + return True + except BlockingIOError: + # Another worker already holds the lock. + return False + except (ImportError, OSError, AttributeError): + # fcntl unavailable (Windows) or unexpected FS error — treat as leader. + return True + + +def _release_scheduler_lock() -> None: + global _lock_fd + if _lock_fd is None: + return + try: + import fcntl + + fcntl.flock(_lock_fd, fcntl.LOCK_UN) + os.close(_lock_fd) + except (ImportError, OSError): + pass + _lock_fd = None + + +# --------------------------------------------------------------------------- +# Early logging setup (before config is loaded) +# --------------------------------------------------------------------------- + +setup_logging( + level=os.getenv("LOG_LEVEL", "INFO"), + file_logging=os.getenv("LOG_FILE_ENABLED", "true").strip().lower() + in {"1", "true", "yes", "on"}, +) + + +# --------------------------------------------------------------------------- +# Lifespan +# --------------------------------------------------------------------------- + + +@asynccontextmanager +async def lifespan(app: FastAPI): + # 1. Load configuration. + await _config.load() + reload_logging( + level=os.getenv("LOG_LEVEL", "INFO"), + file_level=_config.get_str("logging.file_level", "") or None, + max_files=_config.get_int("logging.max_files", 7), + ) + logger.info( + "application startup: service=grok2api python={} platform={}", + sys.version.split()[0], + platform.system(), + ) + + # 2. Initialise account repository and bootstrap runtime table. + from app.control.account.backends.factory import ( + create_repository, + describe_repository_target, + ) + from app.control.account.runtime import ( + reconcile_refresh_runtime, + set_refresh_scheduler, + set_refresh_scheduler_leader, + set_refresh_service, + ) + from app.control.account.scheduler import get_account_refresh_scheduler + from app.dataplane.account import get_account_directory + + storage_backend, storage_target = describe_repository_target() + logger.info( + "account storage configured: backend={} target={}", + storage_backend, + storage_target, + ) + + repo = create_repository() + await repo.initialize() + + # 2a. First-boot migrations (config seed / account migration from SQLite). + from app.platform.startup import run_startup_migrations + + await run_startup_migrations( + config_backend=_config._get_backend(), + account_repo=repo, + ) + # Reload config in case it was just seeded/migrated into the backend. + await _config.load() + await reconcile_local_media_cache_async() + + directory = await get_account_directory(repo) + + # Expose repository on app.state for admin handlers. + app.state.repository = repo + app.state.directory = directory + + # 3. Account directory sync loop — all workers, lightweight incremental pull. + # Keeps each worker's in-memory table eventually consistent with the repo. + # + # Adaptive interval strategy: + # - After detecting changes → re-check in ACCOUNT_SYNC_ACTIVE_INTERVAL (default 3 s) + # so rapid back-to-back writes (bulk import, refresh cycle) are picked up quickly. + # - After N idle polls → back off toward ACCOUNT_SYNC_INTERVAL (default 30 s). + # scan_changes() is an indexed DB query that costs < 1 ms when nothing changed, + # so polling aggressively after a change is essentially free. + _SYNC_IDLE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_INTERVAL", "30")) + _SYNC_ACTIVE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_ACTIVE_INTERVAL", "3")) + _SYNC_IDLE_AFTER = 5 # consecutive empty polls before returning to idle pace + + async def _sync_loop() -> None: + idle_streak = 0 + while True: + interval = ( + _SYNC_ACTIVE_INTERVAL + if idle_streak < _SYNC_IDLE_AFTER + else _SYNC_IDLE_INTERVAL + ) + await asyncio.sleep(interval) + try: + changed = await directory.sync_if_changed() + idle_streak = 0 if changed else min(idle_streak + 1, _SYNC_IDLE_AFTER) + except asyncio.CancelledError: + raise + except Exception as exc: + logger.debug("account directory sync error: error={}", exc) + idle_streak = _SYNC_IDLE_AFTER # back off on errors + + sync_task = asyncio.create_task(_sync_loop(), name="account-dir-sync") + + # 4. Account refresh scheduler — only the leader worker. + # Uses an advisory file lock so exactly one process runs the heavy + # upstream quota-fetch loop regardless of worker count. + # + # ``account.refresh.enabled`` selects between two independent runtime + # strategies: + # - true → "quota" selector + scheduler running (default). + # - false → "random" selector + scheduler idle (no upstream probing). + from app.control.account.refresh import AccountRefreshService + + refresh_enabled = _config.get_bool("account.refresh.enabled", False) + + refresh_svc = AccountRefreshService(repo) + set_refresh_service(refresh_svc) + app.state.refresh_service = refresh_svc + + is_leader = _try_acquire_scheduler_lock() + scheduler = get_account_refresh_scheduler(refresh_svc) + set_refresh_scheduler(scheduler) + set_refresh_scheduler_leader(is_leader) + app.state.account_refresh_scheduler = scheduler + app.state.account_refresh_is_leader = is_leader + + strategy_name = reconcile_refresh_runtime(refresh_enabled) + if is_leader and strategy_name == "quota": + logger.info( + "scheduler leader: pid={} strategy=quota active_sync_s={} idle_sync_s={}", + os.getpid(), + _SYNC_ACTIVE_INTERVAL, + _SYNC_IDLE_INTERVAL, + ) + elif is_leader: + logger.info( + "scheduler leader: pid={} strategy=random (scheduler idle) " + "active_sync_s={} idle_sync_s={}", + os.getpid(), + _SYNC_ACTIVE_INTERVAL, + _SYNC_IDLE_INTERVAL, + ) + else: + logger.info( + "scheduler follower: pid={} strategy={} active_sync_s={} idle_sync_s={}", + os.getpid(), + strategy_name, + _SYNC_ACTIVE_INTERVAL, + _SYNC_IDLE_INTERVAL, + ) + + # 5. Initialise proxy directory and start clearance refresh scheduler. + from app.control.proxy import get_proxy_directory + from app.control.proxy.scheduler import ProxyClearanceScheduler + + proxy_dir = await get_proxy_directory() + proxy_scheduler = ProxyClearanceScheduler(proxy_dir) + if is_leader: + proxy_scheduler.start() + + # 6. Console 配额窗口自动重置任务(轻量巡检,每30秒扫描一次过期窗口) + _CONSOLE_RESET_INTERVAL = 30 # 秒 + + async def _console_reset_loop() -> None: + while True: + await asyncio.sleep(_CONSOLE_RESET_INTERVAL) + try: + await refresh_svc.reset_expired_console_windows() + except asyncio.CancelledError: + raise + except Exception as exc: + logger.debug("console quota reset loop error: error={}", exc) + + console_reset_task = asyncio.create_task( + _console_reset_loop(), name="console-quota-reset" + ) if is_leader else None + + # 7. Console 429 EXPIRED 账号自动恢复任务(每10分钟巡检一次) + # 恢复条件:状态 EXPIRED + 原因 console_429_threshold_exceeded + # + usage_use_count > 5 + expired_at <= now - 1小时 + _CONSOLE_RECOVERY_INTERVAL = 600 # 10 分钟 + + async def _console_recovery_loop() -> None: + while True: + await asyncio.sleep(_CONSOLE_RECOVERY_INTERVAL) + try: + await refresh_svc.recover_console_expired_accounts() + except asyncio.CancelledError: + raise + except Exception as exc: + logger.debug("console expired recovery loop error: error={}", exc) + + console_recovery_task = asyncio.create_task( + _console_recovery_loop(), name="console-expired-recovery" + ) if is_leader else None + + logger.info("application startup completed") + yield + + # ----------- + # Shutdown + # ----------- + logger.info("application shutdown started") + if console_reset_task is not None: + console_reset_task.cancel() + try: + await console_reset_task + except asyncio.CancelledError: + pass + if console_recovery_task is not None: + console_recovery_task.cancel() + try: + await console_recovery_task + except asyncio.CancelledError: + pass + sync_task.cancel() + try: + await sync_task + except asyncio.CancelledError: + pass + + if is_leader: + scheduler.stop() + proxy_scheduler.stop() + _release_scheduler_lock() + + set_refresh_scheduler(None) + set_refresh_scheduler_leader(False) + set_refresh_service(None) + await repo.close() + logger.info("application shutdown completed") + + +# --------------------------------------------------------------------------- +# Application factory +# --------------------------------------------------------------------------- + + +def create_app() -> FastAPI: + openapi_tags = [ + {"name": "OpenAI - Models", "description": "Model discovery endpoints."}, + { + "name": "OpenAI - Chat", + "description": "Chat Completions compatible endpoints.", + }, + { + "name": "OpenAI - Responses", + "description": "Responses API compatible endpoints.", + }, + { + "name": "OpenAI - Images", + "description": "Image generation and image edit endpoints.", + }, + { + "name": "OpenAI - Videos", + "description": "Video job creation and retrieval endpoints.", + }, + { + "name": "OpenAI - Files", + "description": "Locally cached media file endpoints.", + }, + { + "name": "Anthropic - Messages", + "description": "Anthropic Messages API compatible endpoints.", + }, + { + "name": "Admin - System", + "description": "Admin system status and runtime configuration endpoints.", + }, + { + "name": "Admin - Tokens", + "description": "Admin account token management endpoints.", + }, + {"name": "Admin - Batch", "description": "Admin batch operation endpoints."}, + { + "name": "Admin - Assets", + "description": "Admin online asset management endpoints.", + }, + { + "name": "Admin - Cache", + "description": "Admin local cache management endpoints.", + }, + { + "name": "WebUI - System", + "description": "WebUI authentication and system endpoints.", + }, + {"name": "WebUI - Chat", "description": "WebUI chat API endpoints."}, + {"name": "WebUI - Voice", "description": "WebUI voice API endpoints."}, + ] + app = FastAPI( + title="Grok2API", + version=get_project_version(), + description="OpenAI-compatible API gateway for Grok", + openapi_tags=openapi_tags, + lifespan=lifespan, + ) + + app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + + # Ensure config is loaded on every request. + @app.middleware("http") + async def _ensure_config(request: Request, call_next): + from app.control.account.runtime import reconcile_refresh_runtime + + await _config.load() + reconcile_refresh_runtime() + return await call_next(request) + + # Global exception handler — converts AppError to JSON. + @app.exception_handler(AppError) + async def _app_error_handler(request: Request, exc: AppError): + return JSONResponse(exc.to_dict(), status_code=exc.status) + + @app.exception_handler(RequestValidationError) + async def _request_validation_handler( + request: Request, + exc: RequestValidationError, + ): + errors = exc.errors() + first = errors[0] if errors else {} + loc = tuple(first.get("loc") or ()) + param_parts = [ + str(part) + for part in loc + if str(part) not in {"body", "query", "path", "header", "cookie"} + ] + param = ".".join(param_parts) + message = first.get("msg") or "Request validation failed" + logger.warning( + "request validation failed: method={} path={} param={} errors={}", + request.method, + request.url.path, + param or "-", + errors, + ) + payload = { + "error": { + "message": message, + "type": "invalid_request_error", + "code": "invalid_value", + } + } + if param: + payload["error"]["param"] = param + return JSONResponse(payload, status_code=400) + + @app.exception_handler(Exception) + async def _generic_error_handler(request: Request, exc: Exception): + logger.exception("unhandled application exception: error={}", exc) + return JSONResponse( + {"error": {"message": "Internal server error", "type": "server_error"}}, + status_code=500, + ) + + # Routers. + from app.products.web import router as web_router + from app.products.openai.router import router as openai_router + from app.products.anthropic.router import router as anthropic_router + + app.include_router(web_router) + app.include_router(openai_router) + app.include_router(anthropic_router) + + # Static assets — new statics only. + _statics_dir = Path(__file__).resolve().parent / "statics" + if _statics_dir.is_dir(): + app.mount("/static", StaticFiles(directory=_statics_dir), name="static") + + @app.get("/favicon.ico", include_in_schema=False) + def favicon(): + from fastapi.responses import FileResponse as _FR + + _ico = _statics_dir / "favicon.ico" + if _ico.exists(): + return _FR(_ico) + return JSONResponse({"error": "not found"}, status_code=404) + + @app.get("/health", include_in_schema=False) + def health(): + return {"status": "ok"} + + return app + + +app = create_app() + + +if __name__ == "__main__": + logger.error( + "direct startup is disabled: use " + "uv run granian --interface asgi --host 0.0.0.0 --port 8000 app.main:app" + ) + raise SystemExit(1) diff --git a/app/platform/__init__.py b/app/platform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/platform/auth/__init__.py b/app/platform/auth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/platform/auth/middleware.py b/app/platform/auth/middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..195c616dc5d0e0d7e192fab96743867e10cf1d81 --- /dev/null +++ b/app/platform/auth/middleware.py @@ -0,0 +1,127 @@ +"""API-key authentication dependencies for FastAPI routes.""" + +import hmac + +from fastapi import Header, HTTPException, Query, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer + +from app.platform.config.snapshot import get_config + +_security = HTTPBearer(auto_error=False, scheme_name="API Key") + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _get_keys() -> list[str]: + raw = get_config("app.api_key", "") + if not raw: + return [] + if isinstance(raw, list): + return [str(k).strip() for k in raw if str(k).strip()] + return [k.strip() for k in str(raw).split(",") if k.strip()] + + +def get_admin_key() -> str: + """Return configured ``app.app_key`` (admin password).""" + return str(get_config("app.app_key", "grok2api") or "") + + +def get_webui_key() -> str: + """Return configured ``app.webui_key`` (webui access key).""" + return str(get_config("app.webui_key", "") or "") + + +def is_webui_enabled() -> bool: + """Whether the webui entry is enabled.""" + val = get_config("app.webui_enabled", False) + if isinstance(val, bool): + return val + if isinstance(val, str): + return val.strip().lower() in {"1", "true", "yes", "on"} + return bool(val) + + +def _extract_bearer(authorization: str | None) -> str | None: + if not authorization: + return None + scheme, _, token = authorization.partition(" ") + if scheme.lower() != "bearer" or not token: + return None + return token + + +# --------------------------------------------------------------------------- +# Dependencies +# --------------------------------------------------------------------------- + +async def verify_api_key( + authorization: str | None = Header(default=None), + x_api_key: str | None = Header(default=None, alias="x-api-key"), +) -> None: + """Validate Bearer token against configured ``api_key``. + + Accepts either ``Authorization: Bearer `` (OpenAI / grok2api style) + or ``X-API-Key: `` (official Anthropic SDK style) so that agents + targeting the Anthropic-compatible endpoint work without reconfiguration. + """ + allowed_keys = _get_keys() + if not allowed_keys: + return + + token = _extract_bearer(authorization) or x_api_key or None + if token is None: + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Missing or invalid Authorization header.") + + if not any(hmac.compare_digest(token, k) for k in allowed_keys): + raise HTTPException(status.HTTP_403_FORBIDDEN, "Invalid API key.") + + +async def verify_admin_key( + authorization: str | None = Header(default=None), + app_key: str | None = Query(default=None), +) -> None: + """Validate Bearer token against ``app.app_key`` (admin access). + + Accepts either ``Authorization: Bearer `` header or ``?app_key=`` + query parameter (the latter is needed for EventSource which cannot send headers). + """ + key = get_admin_key() + if not key: + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Admin key is not configured.") + + token = _extract_bearer(authorization) or app_key + if token is None: + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Missing authentication token.") + + if not hmac.compare_digest(token, key): + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid authentication token.") + + +async def verify_webui_key( + authorization: str | None = Header(default=None), +) -> None: + """Validate Bearer token for webui endpoints.""" + webui_key = get_webui_key() + + if not webui_key: + if is_webui_enabled(): + return + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "WebUI access is disabled.") + + token = _extract_bearer(authorization) + if token is None: + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Missing authentication token.") + + if not hmac.compare_digest(token, webui_key): + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid authentication token.") + +__all__ = [ + "verify_api_key", + "verify_admin_key", + "verify_webui_key", + "get_admin_key", + "get_webui_key", + "is_webui_enabled", +] diff --git a/app/platform/config/__init__.py b/app/platform/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/platform/config/backends/__init__.py b/app/platform/config/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eae627de2c6006066cc29de7ff52a31d5b2edb3f --- /dev/null +++ b/app/platform/config/backends/__init__.py @@ -0,0 +1,5 @@ +"""Config storage backends.""" +from .base import ConfigBackend +from .factory import create_config_backend, get_config_backend_name + +__all__ = ["ConfigBackend", "create_config_backend", "get_config_backend_name"] diff --git a/app/platform/config/backends/_serde.py b/app/platform/config/backends/_serde.py new file mode 100644 index 0000000000000000000000000000000000000000..a437355849cc8513c410986851c1d8d31e741aab --- /dev/null +++ b/app/platform/config/backends/_serde.py @@ -0,0 +1,35 @@ +"""Flatten / unflatten helpers shared by all backends.""" + +import json +import logging +from typing import Any + +_log = logging.getLogger(__name__) + + +def flatten(nested: dict[str, Any], prefix: str = "") -> dict[str, str]: + """Recursively flatten *nested* to ``{"section.key": json_value, ...}``.""" + out: dict[str, str] = {} + for k, v in nested.items(): + full = f"{prefix}.{k}" if prefix else k + if isinstance(v, dict): + out.update(flatten(v, full)) + else: + out[full] = json.dumps(v, ensure_ascii=False) + return out + + +def unflatten(flat: dict[str, str]) -> dict[str, Any]: + """Rebuild a nested dict from ``{"section.key": json_value, ...}``.""" + result: dict[str, Any] = {} + for dotted, json_val in flat.items(): + parts = dotted.split(".") + node = result + for part in parts[:-1]: + node = node.setdefault(part, {}) + try: + node[parts[-1]] = json.loads(json_val) + except (json.JSONDecodeError, ValueError): + _log.warning("config: failed to deserialize key %r, treating as string", dotted) + node[parts[-1]] = json_val + return result diff --git a/app/platform/config/backends/base.py b/app/platform/config/backends/base.py new file mode 100644 index 0000000000000000000000000000000000000000..def00bc8c17762cd82ee1c34b72916f27751e267 --- /dev/null +++ b/app/platform/config/backends/base.py @@ -0,0 +1,28 @@ +"""Abstract config backend interface.""" + +from abc import ABC, abstractmethod +from typing import Any + + +class ConfigBackend(ABC): + """Persist and reload user config overrides. + + Storage model: flat key-value pairs (dotted keys → JSON-serialised values). + ``load()`` rebuilds the full nested dict from all stored pairs. + ``apply_patch()`` writes *only* the changed keys, leaving the rest untouched. + """ + + @abstractmethod + async def load(self) -> dict[str, Any]: + """Return the full stored user-overrides as a nested dict.""" + + @abstractmethod + async def apply_patch(self, patch: dict[str, Any]) -> None: + """Persist only the keys present in *patch* (nested dict).""" + + @abstractmethod + async def version(self) -> object: + """Return an opaque version token (cheap — called on every request).""" + + async def close(self) -> None: + """Release any resources held by the backend (optional).""" diff --git a/app/platform/config/backends/factory.py b/app/platform/config/backends/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..258b385eb6187ebb63320f6674a52fd6d9779e69 --- /dev/null +++ b/app/platform/config/backends/factory.py @@ -0,0 +1,79 @@ +"""Config backend factory — follows ACCOUNT_STORAGE automatically.""" + +import os +from pathlib import Path + +from app.platform.paths import data_path +from .base import ConfigBackend + + +def get_config_backend_name() -> str: + """Return the active config backend name (mirrors ACCOUNT_STORAGE).""" + return os.getenv("ACCOUNT_STORAGE", "local").strip().lower() + + +def create_config_backend() -> ConfigBackend: + """Instantiate the config backend that matches the account storage backend. + + ``ACCOUNT_STORAGE=local`` → TOML file (``${DATA_DIR}/config.toml``) + ``ACCOUNT_STORAGE=redis`` → Redis (ACCOUNT_REDIS_URL) + ``ACCOUNT_STORAGE=mysql`` → MySQL (ACCOUNT_MYSQL_URL) + ``ACCOUNT_STORAGE=postgresql`` → PostgreSQL (ACCOUNT_POSTGRESQL_URL) + + No extra env vars needed — reuses the same connection settings as accounts. + """ + backend = get_config_backend_name() + + if backend == "local": + return _make_toml() + if backend == "redis": + return _make_redis() + if backend in ("mysql", "postgresql"): + return _make_sql(backend) + + raise ValueError(f"Unknown account storage backend: {backend!r}") + + +def _make_toml() -> ConfigBackend: + from .toml import TomlConfigBackend + + path_str = os.getenv("CONFIG_LOCAL_PATH", str(data_path("config.toml"))).strip() + path = Path(path_str) + if not path.is_absolute(): + path = Path(__file__).resolve().parents[5] / path + return TomlConfigBackend(path) + + +def _make_redis() -> ConfigBackend: + from redis.asyncio import Redis + from .redis import RedisConfigBackend + + url = os.getenv("ACCOUNT_REDIS_URL", "").strip() + if not url: + raise ValueError("Redis config backend requires ACCOUNT_REDIS_URL") + r = Redis.from_url(url, decode_responses=False) + return RedisConfigBackend(r) + + +def _make_sql(dialect: str) -> ConfigBackend: + from .sql import SqlConfigBackend + from app.control.account.backends.sql import ( + create_mysql_engine, + create_pgsql_engine, + ) + + if dialect == "mysql": + url = os.getenv("ACCOUNT_MYSQL_URL", "").strip() + if not url: + raise ValueError("MySQL config backend requires ACCOUNT_MYSQL_URL") + engine = create_mysql_engine(url) + else: + url = os.getenv("ACCOUNT_POSTGRESQL_URL", "").strip() + if not url: + raise ValueError("PostgreSQL config backend requires ACCOUNT_POSTGRESQL_URL") + engine = create_pgsql_engine(url) + + return SqlConfigBackend(engine, dialect=dialect, dispose_engine=False) + + +__all__ = ["create_config_backend", "get_config_backend_name"] diff --git a/app/platform/config/backends/redis.py b/app/platform/config/backends/redis.py new file mode 100644 index 0000000000000000000000000000000000000000..65ca483cb8c27d0505a69f270e7d0b5fa6e83650 --- /dev/null +++ b/app/platform/config/backends/redis.py @@ -0,0 +1,51 @@ +"""Redis config backend (multi-replica / K8s).""" + +from typing import Any + +from .base import ConfigBackend +from ._serde import flatten, unflatten + +_DEFAULT_HASH_KEY = "config:user" +_DEFAULT_VERSION_KEY = "config:version" + + +class RedisConfigBackend(ConfigBackend): + """Flat key-value storage in a Redis Hash. + + Each dotted config key is one Hash field (JSON-encoded value). + ``apply_patch`` only writes the changed fields — all other fields + in the hash are untouched. + """ + + def __init__( + self, + redis, + hash_key: str = _DEFAULT_HASH_KEY, + version_key: str = _DEFAULT_VERSION_KEY, + ) -> None: + self._r = redis + self._hash_key = hash_key + self._version_key = version_key + + async def load(self) -> dict[str, Any]: + raw: dict[bytes, bytes] = await self._r.hgetall(self._hash_key) + if not raw: + return {} + flat = {k.decode(): v.decode() for k, v in raw.items()} + return unflatten(flat) + + async def apply_patch(self, patch: dict[str, Any]) -> None: + flat = flatten(patch) + if not flat: + return + async with self._r.pipeline(transaction=True) as pipe: + pipe.hset(self._hash_key, mapping=flat) + pipe.incr(self._version_key) + await pipe.execute() + + async def version(self) -> object: + v = await self._r.get(self._version_key) + return int(v) if v else 0 + + async def close(self) -> None: + await self._r.aclose() diff --git a/app/platform/config/backends/sql.py b/app/platform/config/backends/sql.py new file mode 100644 index 0000000000000000000000000000000000000000..e69843e7fa43c1970a56e1665b1faefdf398532d --- /dev/null +++ b/app/platform/config/backends/sql.py @@ -0,0 +1,130 @@ +"""SQL config backend (MySQL / PostgreSQL).""" + +from typing import Any + +import sqlalchemy as sa +from sqlalchemy.ext.asyncio import AsyncEngine + +from .base import ConfigBackend +from ._serde import flatten, unflatten + +_TABLE = "config_store" +_VERSION_KEY = "__version__" + +_metadata = sa.MetaData() + +config_store_table = sa.Table( + _TABLE, + _metadata, + sa.Column("key", sa.String(255), primary_key=True), + sa.Column("value", sa.Text, nullable=False, default=""), +) + + +class SqlConfigBackend(ConfigBackend): + """Flat key-value storage in a ``config_store`` table. + + Each dotted config key is one row. ``apply_patch`` only UPSERTs the + changed rows — the rest of the table is untouched. + Version token is stored as the integer value of the ``__version__`` row. + """ + + def __init__( + self, + engine: AsyncEngine, + *, + dialect: str = "postgresql", + dispose_engine: bool = True, + ) -> None: + self._engine = engine + self._dialect = dialect # "mysql" | "postgresql" + self._ready = False + self._dispose_engine = dispose_engine + + async def _ensure_table(self) -> None: + if self._ready: + return + async with self._engine.begin() as conn: + await conn.run_sync(_metadata.create_all) + self._ready = True + + async def load(self) -> dict[str, Any]: + await self._ensure_table() + async with self._engine.connect() as conn: + rows = await conn.execute( + sa.select(config_store_table) + .where(config_store_table.c.key != _VERSION_KEY) + ) + flat = {row.key: row.value for row in rows} + return unflatten(flat) + + async def apply_patch(self, patch: dict[str, Any]) -> None: + await self._ensure_table() + flat = flatten(patch) + if not flat: + return + async with self._engine.begin() as conn: + for k, v in flat.items(): + await conn.execute(self._upsert(k, v)) + # Atomically increment version counter (no read-modify-write race). + await conn.execute(self._upsert_incr_version()) + + async def version(self) -> object: + await self._ensure_table() + async with self._engine.connect() as conn: + row = await conn.execute( + sa.select(config_store_table.c.value) + .where(config_store_table.c.key == _VERSION_KEY) + ) + val = row.scalar() + return int(val) if val else 0 + + def _upsert(self, key: str, value: str) -> sa.Insert: + if self._dialect == "postgresql": + from sqlalchemy.dialects.postgresql import insert + return ( + insert(config_store_table) + .values(key=key, value=value) + .on_conflict_do_update(index_elements=["key"], set_={"value": value}) + ) + else: # mysql + from sqlalchemy.dialects.mysql import insert + return ( + insert(config_store_table) + .values(key=key, value=value) + .on_duplicate_key_update(value=value) + ) + + def _upsert_incr_version(self) -> sa.Insert: + """Atomically insert or increment the version counter row.""" + if self._dialect == "postgresql": + from sqlalchemy.dialects.postgresql import insert + return ( + insert(config_store_table) + .values(key=_VERSION_KEY, value="1") + .on_conflict_do_update( + index_elements=["key"], + set_={"value": sa.func.cast( + sa.func.cast(config_store_table.c.value, sa.Integer) + 1, + sa.Text, + )}, + ) + ) + else: # mysql + from sqlalchemy.dialects.mysql import insert + return ( + insert(config_store_table) + .values(key=_VERSION_KEY, value="1") + .on_duplicate_key_update( + value=sa.func.cast( + sa.func.cast(config_store_table.c.value, sa.Integer) + 1, + sa.Text, + ) + ) + ) + + async def close(self) -> None: + if self._dispose_engine: + from app.control.account.backends.sql import _evict_cached_engine + _evict_cached_engine(self._engine) + await self._engine.dispose() diff --git a/app/platform/config/backends/toml.py b/app/platform/config/backends/toml.py new file mode 100644 index 0000000000000000000000000000000000000000..7510ee19d063dd353697bf837db8ad1767f0b70f --- /dev/null +++ b/app/platform/config/backends/toml.py @@ -0,0 +1,56 @@ +"""TOML-file config backend (default, single-instance).""" + +import asyncio +import os +from pathlib import Path +from typing import Any + +import tomli_w +import tomllib + +from .base import ConfigBackend +from ..loader import _deep_merge as deep_merge + + +class TomlConfigBackend(ConfigBackend): + """Stores user overrides in a local TOML file. + + Flat-key concern doesn't apply here: TOML is the native format and the + file is small enough that a full rewrite is negligible for local use. + Version token = file mtime. + """ + + def __init__(self, path: Path) -> None: + self._path = path + + async def load(self) -> dict[str, Any]: + if not self._path.exists(): + return {} + return await asyncio.to_thread(self._read) + + async def apply_patch(self, patch: dict[str, Any]) -> None: + await asyncio.to_thread(self._merge_write, patch) + + async def version(self) -> object: + return _mtime(self._path) + + def _read(self) -> dict[str, Any]: + with open(self._path, "rb") as fh: + return tomllib.load(fh) + + def _merge_write(self, patch: dict[str, Any]) -> None: + existing = {} + if self._path.exists(): + with open(self._path, "rb") as fh: + existing = tomllib.load(fh) + merged = deep_merge(existing, patch) + self._path.parent.mkdir(parents=True, exist_ok=True) + with open(self._path, "wb") as fh: + tomli_w.dump(merged, fh) + + +def _mtime(path: Path) -> float: + try: + return os.stat(path).st_mtime + except OSError: + return 0.0 diff --git a/app/platform/config/loader.py b/app/platform/config/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..9337864528faea0ce68a63d89e267354b9aa2ec2 --- /dev/null +++ b/app/platform/config/loader.py @@ -0,0 +1,79 @@ +"""TOML configuration loader with environment-variable override support.""" + +import os +from pathlib import Path +from typing import Any + +import tomllib + + +def _flatten(mapping: dict[str, Any], prefix: str = "") -> dict[str, Any]: + """Flatten a nested dict into dotted keys.""" + out: dict[str, Any] = {} + for k, v in mapping.items(): + full = f"{prefix}.{k}" if prefix else k + if isinstance(v, dict): + out.update(_flatten(v, full)) + else: + out[full] = v + return out + + +def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]: + """Recursively merge *override* into *base* (non-destructive).""" + result = dict(base) + for k, v in override.items(): + if k in result and isinstance(result[k], dict) and isinstance(v, dict): + result[k] = _deep_merge(result[k], v) + else: + result[k] = v + return result + + +def load_toml(path: Path) -> dict[str, Any]: + """Load a TOML file and return the raw nested dict.""" + if not path.exists(): + return {} + with open(path, "rb") as fh: + return tomllib.load(fh) + + +def load_config( + defaults_path: Path, + user_path: Path | None = None, + env_prefix: str = "GROK_", +) -> dict[str, Any]: + """Load configuration: defaults → user file → environment overrides. + + Environment variables use the format ``GROK_SECTION_KEY=value``, + which maps to the dotted key ``section.key``. + """ + data = load_toml(defaults_path) + if user_path and user_path.exists(): + user = load_toml(user_path) + data = _deep_merge(data, user) + + # Environment overrides (GROK_PROXY_BASE_PROXY_URL → proxy.base_proxy_url) + prefix_len = len(env_prefix) + for env_key, env_val in os.environ.items(): + if not env_key.startswith(env_prefix): + continue + parts = env_key[prefix_len:].lower().split("_", 1) + if len(parts) == 2: + section, key = parts + data.setdefault(section, {})[key] = env_val + + return data + + +def get_nested(data: dict[str, Any], dotted_key: str, default: Any = None) -> Any: + """Retrieve a value from a nested dict using a dotted key path.""" + keys = dotted_key.split(".") + node: Any = data + for k in keys: + if not isinstance(node, dict): + return default + node = node.get(k) + if node is None: + return default + return node diff --git a/app/platform/config/snapshot.py b/app/platform/config/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..f489f01adfb549ee028465d660ca7308b10c2b69 --- /dev/null +++ b/app/platform/config/snapshot.py @@ -0,0 +1,165 @@ +"""Typed configuration snapshot — built once at startup, reloaded on change.""" + +import asyncio +import os +from pathlib import Path +from typing import Any + +from .loader import _deep_merge, get_nested, load_toml +from .backends import ConfigBackend, create_config_backend + +_BASE_DIR = Path(__file__).resolve().parents[3] # project root + + +def _resolve_defaults_path() -> Path: + return _BASE_DIR / "config.defaults.toml" + + +def _mtime(path: Path) -> float: + try: + return os.stat(path).st_mtime + except OSError: + return 0.0 + + +class ConfigSnapshot: + """Immutable view over the loaded configuration dict. + + Loading strategy (lowest → highest priority): + 1. ``config.defaults.toml`` — shipped defaults (read-only, ConfigMap) + 2. Backend user overrides — toml file or Redis (admin hot-update target) + 3. ``GROK_*`` env vars — always win + + Change detection is cheap: one stat() (toml) or one Redis GET (redis) per + request on the fast path. + """ + + def __init__(self, backend: ConfigBackend | None = None) -> None: + self._data: dict[str, Any] = {} + self._loaded = False + self._lock = asyncio.Lock() + self._mtime_defaults: float = 0.0 + self._version: object = None + self._backend: ConfigBackend | None = backend + + def _get_backend(self) -> ConfigBackend: + if self._backend is None: + self._backend = create_config_backend() + return self._backend + + async def load(self, defaults_path: Path | None = None) -> None: + """Reload config if defaults or backend overrides changed. + + Safe to call on every request — skips I/O when nothing changed. + Pass *defaults_path* only during testing. + """ + dp = defaults_path or _resolve_defaults_path() + backend = self._get_backend() + + mt_dp = _mtime(dp) + ver = await backend.version() + + # Fast path: nothing changed. + if self._loaded and mt_dp == self._mtime_defaults and ver == self._version: + return + + async with self._lock: + mt_dp = _mtime(dp) + ver = await backend.version() + if self._loaded and mt_dp == self._mtime_defaults and ver == self._version: + return + + if not dp.exists(): + raise RuntimeError(f"Missing required defaults config: {dp}") + + defaults = await asyncio.to_thread(load_toml, dp) + user_overrides = await backend.load() + self._data = _deep_merge(defaults, user_overrides) + self._data = _apply_env(self._data) + + self._loaded = True + self._mtime_defaults = mt_dp + self._version = ver + + async def ensure_loaded(self) -> None: + if not self._loaded: + await self.load() + + def get(self, key: str, default: Any = None) -> Any: + return get_nested(self._data, key, default) + + def get_int(self, key: str, default: int = 0) -> int: + val = self.get(key, default) + try: + return int(val) + except (TypeError, ValueError): + return default + + def get_float(self, key: str, default: float = 0.0) -> float: + val = self.get(key, default) + try: + return float(val) + except (TypeError, ValueError): + return default + + def get_bool(self, key: str, default: bool = False) -> bool: + val = self.get(key, default) + if isinstance(val, bool): + return val + if isinstance(val, str): + return val.strip().lower() in {"1", "true", "yes", "on"} + return bool(val) + + def get_str(self, key: str, default: str = "") -> str: + val = self.get(key, default) + return str(val) if val is not None else default + + def get_list(self, key: str, default: list | None = None) -> list: + val = self.get(key, default) + if val is None: + return [] if default is None else default + if isinstance(val, list): + return val + if isinstance(val, str): + return [p.strip() for p in val.split(",") if p.strip()] + return [val] + + async def update(self, patch: dict[str, Any]) -> None: + """Persist only the changed keys in *patch* via backend.""" + backend = self._get_backend() + async with self._lock: + await backend.apply_patch(patch) + # Invalidate so next load() call pulls the new version. + self._version = None + + def raw(self) -> dict[str, Any]: + return dict(self._data) + + +# --------------------------------------------------------------------------- +# Env-var override layer (GROK_SECTION_KEY → section.key) +# --------------------------------------------------------------------------- + +def _apply_env(data: dict[str, Any], prefix: str = "GROK_") -> dict[str, Any]: + prefix_len = len(prefix) + for env_key, env_val in os.environ.items(): + if not env_key.startswith(prefix): + continue + parts = env_key[prefix_len:].lower().split("_", 1) + if len(parts) == 2: + section, key = parts + data.setdefault(section, {})[key] = env_val + return data + + +# Module-level singleton — imported everywhere. +config = ConfigSnapshot() + + +def get_config(key: str | None = None, default: Any = None) -> Any: + if key is None: + return config + return config.get(key, default) + + +__all__ = ["ConfigSnapshot", "config", "get_config"] diff --git a/app/platform/errors.py b/app/platform/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc3bf81ea4b54efeaca9342f57102c4c97746c0 --- /dev/null +++ b/app/platform/errors.py @@ -0,0 +1,93 @@ +"""Platform-level exception hierarchy.""" + +from enum import StrEnum + + +class ErrorKind(StrEnum): + VALIDATION = "invalid_request_error" + AUTHENTICATION = "authentication_error" + RATE_LIMIT = "rate_limit_exceeded" + UPSTREAM = "upstream_error" + SERVER = "server_error" + + +class AppError(Exception): + """Base exception for all application errors.""" + + def __init__( + self, + message: str, + *, + kind: ErrorKind = ErrorKind.SERVER, + code: str = "internal_error", + status: int = 500, + details: dict | None = None, + ) -> None: + super().__init__(message) + self.message = message + self.kind = kind + self.code = code + self.status = status + self.details = details or {} + + def to_dict(self) -> dict: + err = { + "message": self.message, + "type": self.kind, + "code": self.code, + } + if "param" in self.details: + err["param"] = self.details["param"] + return {"error": err} + + +class ValidationError(AppError): + def __init__(self, message: str, *, param: str = "", code: str = "invalid_value") -> None: + super().__init__( + message, kind=ErrorKind.VALIDATION, code=code, status=400, + details={"param": param}, + ) + self.param = param + + +class AuthError(AppError): + def __init__(self, message: str = "Invalid or missing API key") -> None: + super().__init__( + message, kind=ErrorKind.AUTHENTICATION, code="invalid_api_key", status=401, + ) + + +class RateLimitError(AppError): + def __init__(self, message: str = "No available accounts") -> None: + super().__init__( + message, kind=ErrorKind.RATE_LIMIT, code="rate_limit_exceeded", status=429, + ) + + +class UpstreamError(AppError): + def __init__( + self, + message: str, + *, + status: int = 502, + body: str = "", + ) -> None: + super().__init__( + message, kind=ErrorKind.UPSTREAM, code="upstream_error", status=status, + details={"body": body}, + ) + + +class StreamIdleTimeout(AppError): + def __init__(self, timeout_s: float) -> None: + super().__init__( + f"Stream idle timeout after {timeout_s}s", + kind=ErrorKind.UPSTREAM, code="stream_idle_timeout", status=504, + ) + + +__all__ = [ + "ErrorKind", "AppError", + "ValidationError", "AuthError", "RateLimitError", + "UpstreamError", "StreamIdleTimeout", +] diff --git a/app/platform/logging/__init__.py b/app/platform/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/platform/logging/logger.py b/app/platform/logging/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..832700e21b437e05d481164f5b0a6c2066a886f4 --- /dev/null +++ b/app/platform/logging/logger.py @@ -0,0 +1,151 @@ +"""Application logger — loguru with structured-field support.""" + +import os +import sys +from pathlib import Path + +from loguru import logger as _loguru_logger + +from app.platform.paths import log_dir as get_log_dir + +# Re-export as the canonical logger so imports stay uniform. +logger = _loguru_logger + +_configured = False +_console_sink_id: int | None = None +_file_sink_id: int | None = None +_console_level = "INFO" +_json_console = False +_file_logging = True +_log_dir_override: Path | None = None + +_FMT_TEXT = ( + "{time:YYYY-MM-DD HH:mm:ss.SSS} | " + "{level: <8} | " + "{name}:{function}:{line} - " + "{message}" +) + + +def _get_env_bool(name: str, default: bool) -> bool: + value = os.getenv(name) + if value is None: + return default + return value.strip().lower() in {"1", "true", "yes", "on"} + + +def setup_logging( + *, + level: str = "INFO", + file_level: str | None = None, + json_console: bool = False, + file_logging: bool = True, + log_dir: Path | None = None, + max_files: int = 7, +) -> None: + """Configure loguru sinks. Safe to call multiple times (idempotent).""" + global _configured, _console_sink_id, _file_sink_id + global _console_level, _json_console, _file_logging, _log_dir_override + + logger.remove() + _console_sink_id = None + _file_sink_id = None + + fmt_json = "{time} | {level} | {name}:{function}:{line} | {message}" + + resolved_level = level.upper() + _console_sink_id = logger.add( + sys.stdout, + level=resolved_level, + format=fmt_json if json_console else _FMT_TEXT, + colorize=not json_console, + enqueue=False, + backtrace=False, + diagnose=False, + ) + + if file_logging: + _add_file_sink( + file_level=(file_level or resolved_level).upper(), + max_files=max_files, + log_dir=log_dir, + ) + + _configured = True + _console_level = resolved_level + _json_console = json_console + _file_logging = file_logging + _log_dir_override = log_dir + + +def reload_logging( + *, + level: str | None = None, + default_level: str = "INFO", + json_console: bool = False, + max_files: int = 7, + file_level: str | None = None, +) -> None: + """Re-configure logging from runtime values (called after config loads).""" + resolved_level = (level or "").strip() or os.getenv("LOG_LEVEL", default_level) + file_logging = _get_env_bool("LOG_FILE_ENABLED", True) + setup_logging( + level=resolved_level, + file_level=file_level or resolved_level, + json_console=json_console, + file_logging=file_logging, + max_files=max_files, + ) + + +def reload_file_logging( + *, + file_level: str | None = None, + max_files: int = 7, +) -> None: + """Re-configure only the file sink, preserving the current console output.""" + global _file_sink_id, _file_logging + + if not _configured: + reload_logging(file_level=file_level, max_files=max_files) + return + + if _file_sink_id is not None: + logger.remove(_file_sink_id) + _file_sink_id = None + + _file_logging = _get_env_bool("LOG_FILE_ENABLED", True) + if not _file_logging: + return + + _add_file_sink( + file_level=(file_level or _console_level).upper(), + max_files=max_files, + log_dir=_log_dir_override, + ) + + +def _add_file_sink( + *, + file_level: str, + max_files: int, + log_dir: Path | None, +) -> None: + global _file_sink_id + + _dir = log_dir or get_log_dir() + _dir.mkdir(parents=True, exist_ok=True) + _file_sink_id = logger.add( + str(_dir / "app_{time:YYYY-MM-DD}.log"), + level=file_level, + format=_FMT_TEXT, + rotation="00:00", # new file every day at midnight + retention=max_files, # keep the last N daily files + enqueue=True, + encoding="utf-8", + backtrace=False, + diagnose=False, + ) + + +__all__ = ["logger", "setup_logging", "reload_logging", "reload_file_logging"] diff --git a/app/platform/meta.py b/app/platform/meta.py new file mode 100644 index 0000000000000000000000000000000000000000..538925205c79606d6d896e4de78bc1da11ba22c0 --- /dev/null +++ b/app/platform/meta.py @@ -0,0 +1,29 @@ +"""Project metadata helpers sourced from pyproject.toml.""" + +from functools import lru_cache +from pathlib import Path +import tomllib + + +_ROOT = Path(__file__).resolve().parents[2] +_PYPROJECT = _ROOT / "pyproject.toml" + + +@lru_cache(maxsize=1) +def get_project_meta() -> dict[str, str]: + data: dict[str, str] = {"name": "grok2api", "version": "0.0.0"} + if not _PYPROJECT.exists(): + return data + with _PYPROJECT.open("rb") as fh: + parsed = tomllib.load(fh) + project = parsed.get("project") or {} + name = str(project.get("name") or data["name"]).strip() or data["name"] + version = str(project.get("version") or data["version"]).strip() or data["version"] + return {"name": name, "version": version} + + +def get_project_version() -> str: + return get_project_meta()["version"] + + +__all__ = ["get_project_meta", "get_project_version"] diff --git a/app/platform/net/__init__.py b/app/platform/net/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/platform/net/grpc.py b/app/platform/net/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..bc4ac3747836c32f8b1f7ddeb4ef98186099fd89 --- /dev/null +++ b/app/platform/net/grpc.py @@ -0,0 +1,163 @@ +"""gRPC-Web framing and status helpers. + +Encodes data frames for gRPC-Web requests and parses response frames, +including trailer extraction and gRPC status code mapping. +""" + +import base64 +import json +import re +import struct +from dataclasses import dataclass +from typing import Dict, List, Mapping, Optional, Tuple +from urllib.parse import unquote + +from app.platform.logging.logger import logger + +_B64_RE = re.compile(rb"^[A-Za-z0-9+/=\r\n]+$") + +# gRPC status code → HTTP equivalent (best-effort mapping). +_GRPC_HTTP: Dict[int, int] = { + 0: 200, + 4: 504, + 7: 403, + 8: 429, + 14: 503, + 16: 401, +} + + +@dataclass(frozen=True) +class GrpcStatus: + code: int + message: str = "" + + @property + def ok(self) -> bool: + return self.code == 0 + + @property + def http_equiv(self) -> int: + return _GRPC_HTTP.get(self.code, 502) + + +class GrpcClient: + """gRPC-Web framing helpers. + + All methods are static; instantiate only if you want a namespace handle. + """ + + # ------------------------------------------------------------------ + # Encoding + # ------------------------------------------------------------------ + + @staticmethod + def encode_payload(data: bytes) -> bytes: + """Wrap *data* in a gRPC-Web data frame (flag=0x00).""" + return b"\x00" + struct.pack(">I", len(data)) + data + + # ------------------------------------------------------------------ + # Decoding + # ------------------------------------------------------------------ + + @staticmethod + def _maybe_decode_base64(body: bytes, content_type: Optional[str]) -> bytes: + ct = (content_type or "").lower() + if "grpc-web-text" in ct: + return base64.b64decode(b"".join(body.split()), validate=False) + head = body[: min(len(body), 2048)] + if head and _B64_RE.fullmatch(head): + compact = b"".join(body.split()) + try: + return base64.b64decode(compact, validate=True) + except ValueError: + pass + return body + + @staticmethod + def _parse_trailers(payload: bytes) -> Dict[str, str]: + text = payload.decode("utf-8", errors="replace") + result: Dict[str, str] = {} + for line in re.split(r"\r\n|\n", text): + if ":" not in line: + continue + k, v = line.split(":", 1) + result[k.strip().lower()] = v.strip() + if "grpc-message" in result: + result["grpc-message"] = unquote(result["grpc-message"]) + return result + + @classmethod + def parse_response( + cls, + body: bytes, + content_type: Optional[str] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> Tuple[List[bytes], Dict[str, str]]: + """Parse a gRPC-Web response body. + + Returns ``(messages, trailers)`` where *messages* is a list of + raw protobuf payloads and *trailers* contains gRPC metadata + (including ``grpc-status`` and ``grpc-message``). + """ + decoded = cls._maybe_decode_base64(body, content_type) + + messages: List[bytes] = [] + trailers: Dict[str, str] = {} + + i, n = 0, len(decoded) + while i < n: + if n - i < 5: + break + flag = decoded[i] + length = int.from_bytes(decoded[i + 1: i + 5], "big") + i += 5 + if n - i < length: + break + payload = decoded[i: i + length] + i += length + + if flag & 0x80: + trailers.update(cls._parse_trailers(payload)) + elif flag & 0x01: + raise ValueError("grpc-web compressed frame is not supported") + else: + messages.append(payload) + + # Supplement from HTTP headers (some servers send trailers as headers). + if headers: + lower = {k.lower(): v for k, v in headers.items()} + for key in ("grpc-status", "grpc-message"): + if key in lower and key not in trailers: + val = str(lower[key]).strip() + trailers[key] = unquote(val) if key == "grpc-message" else val + + raw_code = str(trailers.get("grpc-status", "")).strip() + try: + code = int(raw_code) + except ValueError: + code = -1 + + if code not in (0, -1): + logger.error( + "grpc response reported error: grpc_status={} grpc_message={} content_type={}", + code, + trailers.get("grpc-message", ""), + content_type or "", + ) + + return messages, trailers + + @staticmethod + def get_status(trailers: Mapping[str, str]) -> GrpcStatus: + """Extract ``GrpcStatus`` from parsed trailers.""" + raw = str(trailers.get("grpc-status", "")).strip() + msg = str(trailers.get("grpc-message", "")).strip() + try: + code = int(raw) + except ValueError: + code = -1 + return GrpcStatus(code=code, message=msg) + + +__all__ = ["GrpcClient", "GrpcStatus"] diff --git a/app/platform/paths.py b/app/platform/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..fc9efb43b21519c7c0a431ae2da8ca33c5f7234a --- /dev/null +++ b/app/platform/paths.py @@ -0,0 +1,34 @@ +"""Shared runtime paths derived from environment variables.""" + +import os +from pathlib import Path + + +_ROOT_DIR = Path(__file__).resolve().parents[2] + + +def _resolve_env_path(name: str, default: str) -> Path: + raw = os.getenv(name, default).strip() or default + path = Path(raw) + if not path.is_absolute(): + path = _ROOT_DIR / path + return path + + +def data_dir() -> Path: + return _resolve_env_path("DATA_DIR", "data") + + +def log_dir() -> Path: + return _resolve_env_path("LOG_DIR", "logs") + + +def data_path(*parts: str) -> Path: + return data_dir().joinpath(*parts) + + +def log_path(*parts: str) -> Path: + return log_dir().joinpath(*parts) + + +__all__ = ["data_dir", "log_dir", "data_path", "log_path"] diff --git a/app/platform/runtime/__init__.py b/app/platform/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/platform/runtime/batch.py b/app/platform/runtime/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..d5649b1a43056d66e2e9bc059986fc393739739d --- /dev/null +++ b/app/platform/runtime/batch.py @@ -0,0 +1,70 @@ +"""Bounded-concurrency batch processing utility.""" + +import asyncio +from collections.abc import Awaitable, Callable, Iterable +from typing import Any, TypeVar + +T = TypeVar("T") +R = TypeVar("R") + + +async def run_batch( + items: Iterable[T], + handler: Callable[[T], Awaitable[R]], + *, + concurrency: int = 10, + pause_sec: float = 0.0, + batch_size: int = 0, +) -> list[R]: + """Process *items* with bounded concurrency. + + Args: + items: Input sequence. + handler: Async callable applied to each item. + concurrency: Maximum simultaneous tasks. + pause_sec: Sleep between batches (only when *batch_size* > 0). + batch_size: Group size for inter-batch pauses; 0 = no grouping. + + Returns: + Results in the same order as *items*. + """ + item_list = list(items) + if not item_list: + return [] + + worker_count = max(1, concurrency) + + async def _run_chunk(chunk: list[T]) -> list[Any]: + results: list[Any] = [None] * len(chunk) + next_index = 0 + + async def _worker() -> None: + nonlocal next_index + while True: + index = next_index + if index >= len(chunk): + return + next_index += 1 + results[index] = await handler(chunk[index]) + + tasks = [asyncio.create_task(_worker()) for _ in range(min(worker_count, len(chunk)))] + try: + await asyncio.gather(*tasks) + except Exception: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + raise + return results + + if not batch_size or batch_size >= len(item_list): + return list(await _run_chunk(item_list)) + + results: list[Any] = [] + for start in range(0, len(item_list), batch_size): + chunk = item_list[start : start + batch_size] + chunk_results = await _run_chunk(chunk) + results.extend(chunk_results) + if pause_sec > 0 and start + batch_size < len(item_list): + await asyncio.sleep(pause_sec) + return results diff --git a/app/platform/runtime/clock.py b/app/platform/runtime/clock.py new file mode 100644 index 0000000000000000000000000000000000000000..3f276a9dbeb90cc2fbe5d5e08efb0dc151d34b3c --- /dev/null +++ b/app/platform/runtime/clock.py @@ -0,0 +1,23 @@ +"""Monotonic-safe time utilities for hot-path and control-plane use.""" + +import time + + +def now_ms() -> int: + """Return current wall-clock time in milliseconds.""" + return int(time.time() * 1000) + + +def now_s() -> int: + """Return current wall-clock time in whole seconds.""" + return int(time.time()) + + +def ms_to_s(ms: int) -> int: + """Convert millisecond timestamp to second timestamp.""" + return ms // 1000 + + +def s_to_ms(s: int) -> int: + """Convert second timestamp to millisecond timestamp.""" + return s * 1000 diff --git a/app/platform/runtime/ids.py b/app/platform/runtime/ids.py new file mode 100644 index 0000000000000000000000000000000000000000..34ddd2ffff65dca10e450896b3ae19869e485bac --- /dev/null +++ b/app/platform/runtime/ids.py @@ -0,0 +1,19 @@ +"""Compact, monotonic lease-id generation without UUID overhead.""" + +import threading + +_lock = threading.Lock() +_counter: int = 0 + + +def next_id() -> int: + """Return a process-local monotonically increasing integer id.""" + global _counter + with _lock: + _counter += 1 + return _counter + + +def next_hex(length: int = 12) -> str: + """Return a zero-padded hex string derived from the monotonic counter.""" + return format(next_id(), f"0{length}x") diff --git a/app/platform/runtime/task.py b/app/platform/runtime/task.py new file mode 100644 index 0000000000000000000000000000000000000000..46c5a47cb809f851f97b27885c250a18d4594782 --- /dev/null +++ b/app/platform/runtime/task.py @@ -0,0 +1,169 @@ +"""Async batch task model + in-memory store for SSE progress streaming.""" + +import asyncio +import time +import uuid +from typing import Any, Dict, List, Optional + + +class AsyncTask: + """Tracks progress of an async batch operation with fan-out SSE support.""" + + __slots__ = ( + "id", "total", "processed", "ok", "fail", "status", + "warning", "result", "error", "created_at", + "cancelled", "_queues", "_final_event", + ) + + def __init__(self, total: int) -> None: + self.id = uuid.uuid4().hex + self.total = int(total) + self.processed = 0 + self.ok = 0 + self.fail = 0 + self.status = "running" + self.warning: Optional[str] = None + self.result: Optional[Dict[str, Any]] = None + self.error: Optional[str] = None + self.created_at = time.time() + self.cancelled = False + self._queues: List[asyncio.Queue] = [] + self._final_event: Optional[Dict[str, Any]] = None + + # -- Fan-out pub/sub --------------------------------------------------- + + def _publish(self, event: Dict[str, Any]) -> None: + for q in list(self._queues): + try: + q.put_nowait(event) + except Exception: + pass + + def attach(self) -> asyncio.Queue: + q: asyncio.Queue = asyncio.Queue(maxsize=200) + self._queues.append(q) + return q + + def detach(self, q: asyncio.Queue) -> None: + if q in self._queues: + self._queues.remove(q) + + # -- Recording --------------------------------------------------------- + + def record( + self, + success: bool, + *, + item: Any = None, + detail: Any = None, + error: str = "", + ) -> None: + self.processed += 1 + if success: + self.ok += 1 + else: + self.fail += 1 + event: Dict[str, Any] = { + "type": "progress", + "task_id": self.id, + "total": self.total, + "processed": self.processed, + "ok": self.ok, + "fail": self.fail, + } + if item is not None: + event["item"] = item + if detail is not None: + event["detail"] = detail + if error: + event["error"] = error + self._publish(event) + + def finish(self, result: Dict[str, Any], *, warning: Optional[str] = None) -> None: + self.status = "done" + self.result = result + self.warning = warning + event = { + "type": "done", + "task_id": self.id, + "total": self.total, + "processed": self.processed, + "ok": self.ok, + "fail": self.fail, + "warning": self.warning, + "result": result, + } + self._final_event = event + self._publish(event) + + def fail_task(self, msg: str) -> None: + self.status = "error" + self.error = msg + event = { + "type": "error", + "task_id": self.id, + "total": self.total, + "processed": self.processed, + "ok": self.ok, + "fail": self.fail, + "error": msg, + } + self._final_event = event + self._publish(event) + + def cancel(self) -> None: + self.cancelled = True + + def finish_cancelled(self) -> None: + self.status = "cancelled" + event = { + "type": "cancelled", + "task_id": self.id, + "total": self.total, + "processed": self.processed, + "ok": self.ok, + "fail": self.fail, + } + self._final_event = event + self._publish(event) + + # -- Snapshots --------------------------------------------------------- + + def snapshot(self) -> Dict[str, Any]: + return { + "task_id": self.id, + "status": self.status, + "total": self.total, + "processed": self.processed, + "ok": self.ok, + "fail": self.fail, + "warning": self.warning, + } + + def final_event(self) -> Optional[Dict[str, Any]]: + return self._final_event + + +# --------------------------------------------------------------------------- +# In-memory task store +# --------------------------------------------------------------------------- + +_TASKS: Dict[str, AsyncTask] = {} + + +def create_task(total: int) -> AsyncTask: + task = AsyncTask(total) + _TASKS[task.id] = task + return task + + +def get_task(task_id: str) -> Optional[AsyncTask]: + return _TASKS.get(task_id) + + +async def expire_task(task_id: str, ttl_s: int = 300) -> None: + await asyncio.sleep(ttl_s) + _TASKS.pop(task_id, None) + + +__all__ = ["AsyncTask", "create_task", "get_task", "expire_task"] diff --git a/app/platform/startup/__init__.py b/app/platform/startup/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2b0ac7687bbbb3c2c9a421096e249dd9c8a154ed --- /dev/null +++ b/app/platform/startup/__init__.py @@ -0,0 +1,4 @@ +"""Startup utilities — migration, seeding, first-boot checks.""" +from .migration import run_startup_migrations + +__all__ = ["run_startup_migrations"] diff --git a/app/platform/startup/migration.py b/app/platform/startup/migration.py new file mode 100644 index 0000000000000000000000000000000000000000..356b4f5db166170294aeeab4328fa809441b5dd9 --- /dev/null +++ b/app/platform/startup/migration.py @@ -0,0 +1,339 @@ +"""First-boot data migration. + +Config migration +---------------- +local : seeds ``${DATA_DIR}/config.toml`` from ``config.defaults.toml`` if + the file does not exist yet — gives users an editable copy on first run. +redis / sql : if the backend is empty (version == 0) AND + ``${DATA_DIR}/config.toml`` exists, migrates the user overrides into + the DB backend. If it does not exist either, nothing is written + (defaults are always loaded from ``config.defaults.toml`` at runtime). + +Account migration +----------------- +Runs only when ACCOUNT_STORAGE != "local". +If ``${DATA_DIR}/accounts.db`` (the previous local SQLite store) exists AND the +target backend is empty (revision == 0), all accounts are copied into the +new backend — preserving pool, status, quota, usage stats, and timestamps. +After a successful migration the SQLite file is renamed to +``${DATA_DIR}/accounts.db.migrated`` so the same migration is never re-run. +""" + +from __future__ import annotations + +import asyncio +import shutil +from pathlib import Path +from typing import TYPE_CHECKING + +from loguru import logger + +from app.platform.paths import data_path + +if TYPE_CHECKING: + from app.control.account.commands import AccountPatch + from app.control.account.repository import AccountRepository + from app.platform.config.backends.base import ConfigBackend + +_BASE_DIR = Path(__file__).resolve().parents[3] +_DEFAULTS_PATH = _BASE_DIR / "config.defaults.toml" +_USER_CFG_PATH = data_path("config.toml") +_LOCAL_DB_PATH = data_path("accounts.db") +_BATCH = 500 # accounts per upsert/patch batch + + +# --------------------------------------------------------------------------- +# Public entry point +# --------------------------------------------------------------------------- + +async def run_startup_migrations( + config_backend: "ConfigBackend", + account_repo: "AccountRepository", +) -> None: + """Run all first-boot migrations. Safe to call on every startup.""" + await _migrate_config(config_backend) + await _migrate_basic_refresh_interval(config_backend) + await _migrate_accounts(account_repo) + await _backfill_grok_4_3_quota(account_repo) + await _normalize_basic_fast_only_quota(account_repo) + await _backfill_console_quota(account_repo) + + +# --------------------------------------------------------------------------- +# Config migration +# --------------------------------------------------------------------------- + +async def _migrate_config(backend: "ConfigBackend") -> None: + from app.platform.config.backends.factory import get_config_backend_name + from app.platform.config.loader import load_toml + + backend_name = get_config_backend_name() + + if backend_name == "local": + # Seed ${DATA_DIR}/config.toml from defaults so users have an editable file. + if not _USER_CFG_PATH.exists() and _DEFAULTS_PATH.exists(): + await asyncio.to_thread(shutil.copy2, _DEFAULTS_PATH, _USER_CFG_PATH) + logger.info("config: seeded {} from config.defaults.toml", _USER_CFG_PATH) + return + + # DB / Redis backends — migrate only if backend is empty. + if await backend.version() != 0: + return # already has data, skip + + if _USER_CFG_PATH.exists(): + user_data = await asyncio.to_thread(load_toml, _USER_CFG_PATH) + if user_data: + await backend.apply_patch(user_data) + logger.info( + "config: migrated {} -> {} backend ({} keys)", + _USER_CFG_PATH, + backend_name, + _count_keys(user_data), + ) + return + + logger.debug("config: {} backend is empty, no local overrides to migrate", backend_name) + + +async def _migrate_basic_refresh_interval(backend: "ConfigBackend") -> None: + data = await backend.load() + account = data.get("account", {}) + refresh = account.get("refresh", {}) if isinstance(account, dict) else {} + value = refresh.get("basic_interval_sec") if isinstance(refresh, dict) else None + try: + old_default = int(value) + except (TypeError, ValueError): + return + if old_default != 36_000: + return + await backend.apply_patch({"account": {"refresh": {"basic_interval_sec": 86_400}}}) + logger.info("config: updated basic refresh interval default from 36000s to 86400s") + + +# --------------------------------------------------------------------------- +# Account migration +# --------------------------------------------------------------------------- + +async def _migrate_accounts(target_repo: "AccountRepository") -> None: + from app.control.account.backends.factory import get_repository_backend + + if get_repository_backend() == "local": + return # already on local, nothing to migrate + + sqlite_path = _LOCAL_DB_PATH + if not sqlite_path.exists(): + return # no previous local data + + # Check whether the target already has data. + snapshot = await target_repo.runtime_snapshot() + if snapshot.revision > 0 or snapshot.items: + logger.debug("account: target backend not empty (revision={}), skipping migration", snapshot.revision) + return + + logger.info("account: migrating accounts from {} → {} backend", sqlite_path, get_repository_backend()) + count = await _copy_accounts(sqlite_path, target_repo) + + # Rename the SQLite file so this migration is never re-run. + done_path = sqlite_path.with_suffix(".db.migrated") + await asyncio.to_thread(sqlite_path.rename, done_path) + logger.info("account: migration complete ({} accounts), renamed {} → {}", count, sqlite_path.name, done_path.name) + + +async def _copy_accounts(sqlite_path: Path, target: "AccountRepository") -> int: + """Read all accounts from the local SQLite file and write to *target*.""" + from app.control.account.backends.local import LocalAccountRepository + from app.control.account.commands import AccountUpsert, ListAccountsQuery + + source = LocalAccountRepository(sqlite_path) + await source.initialize() + + total = 0 + page = 1 + + try: + while True: + result = await source.list_accounts( + ListAccountsQuery(page=page, page_size=_BATCH, include_deleted=True) + ) + records = result.items + if not records: + break + + # Step 1: upsert — creates records with token / pool / tags / ext. + upserts = [ + AccountUpsert(token=r.token, pool=r.pool, tags=r.tags, ext=r.ext) + for r in records + ] + await target.upsert_accounts(upserts) + + # Step 2: patch — fills status, quota, usage counters, timestamps. + patches = [_record_to_patch(r) for r in records] + await target.patch_accounts(patches) + + # Step 3: soft-delete records that were deleted in the source. + deleted_tokens = [r.token for r in records if r.deleted_at is not None] + if deleted_tokens: + await target.delete_accounts(deleted_tokens) + + total += len(records) + if page >= result.total_pages: + break + page += 1 + finally: + await source.close() + + return total + + +def _record_to_patch(r) -> "AccountPatch": + from app.control.account.commands import AccountPatch + + qs = r.quota_set() + return AccountPatch( + token=r.token, + status=r.status, + quota_auto=qs.auto.to_dict() if qs.auto else None, + quota_fast=qs.fast.to_dict() if qs.fast else None, + quota_expert=qs.expert.to_dict() if qs.expert else None, + quota_heavy=qs.heavy.to_dict() if qs.heavy else None, + quota_grok_4_3=qs.grok_4_3.to_dict() if qs.grok_4_3 else None, + quota_console=qs.console.to_dict() if qs.console else None, + # Usage counts — target starts at 0, so actual value == delta. + usage_use_delta=r.usage_use_count or None, + usage_fail_delta=r.usage_fail_count or None, + usage_sync_delta=r.usage_sync_count or None, + last_use_at=r.last_use_at, + last_fail_at=r.last_fail_at, + last_fail_reason=r.last_fail_reason, + last_sync_at=r.last_sync_at, + last_clear_at=r.last_clear_at, + state_reason=r.state_reason, + ext_merge=r.ext or None, + ) + + +# --------------------------------------------------------------------------- +# Backfill quota_grok_4_3 for super/heavy accounts imported before the field existed. +# --------------------------------------------------------------------------- + +async def _backfill_grok_4_3_quota(repo: "AccountRepository") -> None: + from app.control.account.commands import AccountPatch, ListAccountsQuery + from app.control.account.quota_defaults import default_quota_window + + patches: list[AccountPatch] = [] + page = 1 + while True: + result = await repo.list_accounts( + ListAccountsQuery(page=page, page_size=_BATCH, include_deleted=False) + ) + for record in result.items: + if record.pool not in ("super", "heavy"): + continue + if record.quota_set().grok_4_3 is not None: + continue + window = default_quota_window(record.pool, 4) + if window is None: + continue + patches.append(AccountPatch(token=record.token, quota_grok_4_3=window.to_dict())) + if page >= result.total_pages: + break + page += 1 + + if not patches: + return + + total = 0 + for i in range(0, len(patches), _BATCH): + batch = patches[i : i + _BATCH] + res = await repo.patch_accounts(batch) + total += res.patched + logger.info("account: backfilled quota_grok_4_3 for {} super/heavy accounts", total) + + +async def _normalize_basic_fast_only_quota(repo: "AccountRepository") -> None: + from app.control.account.commands import AccountPatch, ListAccountsQuery + from app.control.account.quota_defaults import normalize_quota_set + + patches: list[AccountPatch] = [] + page = 1 + while True: + result = await repo.list_accounts( + ListAccountsQuery( + page=page, + page_size=_BATCH, + pool="basic", + include_deleted=False, + ) + ) + for record in result.items: + normalized = normalize_quota_set("basic", record.quota_set()) + if normalized.to_dict() == record.quota_set().to_dict(): + continue + patches.append( + AccountPatch( + token=record.token, + quota_auto=normalized.auto.to_dict(), + quota_fast=normalized.fast.to_dict(), + quota_expert=normalized.expert.to_dict(), + ) + ) + if page >= result.total_pages: + break + page += 1 + + if not patches: + return + + total = 0 + for i in range(0, len(patches), _BATCH): + batch = patches[i : i + _BATCH] + res = await repo.patch_accounts(batch) + total += res.patched + logger.info("account: normalized {} basic accounts to fast-only quota", total) + + +async def _backfill_console_quota(repo: "AccountRepository") -> None: + """Backfill quota_console for all accounts that don't have it yet.""" + from app.control.account.commands import AccountPatch, ListAccountsQuery + from app.control.account.quota_defaults import default_quota_window + + patches: list[AccountPatch] = [] + page = 1 + while True: + result = await repo.list_accounts( + ListAccountsQuery(page=page, page_size=_BATCH, include_deleted=False) + ) + for record in result.items: + if record.quota_set().console is not None: + continue + window = default_quota_window(record.pool, 5) + if window is None: + continue + patches.append(AccountPatch(token=record.token, quota_console=window.to_dict())) + if page >= result.total_pages: + break + page += 1 + + if not patches: + return + + total = 0 + for i in range(0, len(patches), _BATCH): + batch = patches[i : i + _BATCH] + res = await repo.patch_accounts(batch) + total += res.patched + logger.info("account: backfilled quota_console for {} accounts", total) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _count_keys(nested: dict, prefix: str = "") -> int: + count = 0 + for v in nested.values(): + if isinstance(v, dict): + count += _count_keys(v) + else: + count += 1 + return count diff --git a/app/platform/storage/__init__.py b/app/platform/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..895f9a58ee36c895e53c585f6d9f208ec2593f55 --- /dev/null +++ b/app/platform/storage/__init__.py @@ -0,0 +1,20 @@ +"""Platform storage helpers.""" + +from .media_cache import ( + clear_local_media_files, + delete_local_media_file, + reconcile_local_media_cache_async, + save_local_image, + save_local_video, +) +from .media_paths import image_files_dir, video_files_dir + +__all__ = [ + "clear_local_media_files", + "delete_local_media_file", + "image_files_dir", + "reconcile_local_media_cache_async", + "save_local_image", + "save_local_video", + "video_files_dir", +] diff --git a/app/platform/storage/contract.py b/app/platform/storage/contract.py new file mode 100644 index 0000000000000000000000000000000000000000..632a785d0bb9795dbb48baa5a19c0b5b4fe4438b --- /dev/null +++ b/app/platform/storage/contract.py @@ -0,0 +1,22 @@ +"""Abstract storage contract used by all persistence backends.""" + +from typing import Any, Protocol, runtime_checkable + + +@runtime_checkable +class LockHandle(Protocol): + """Async context manager representing a distributed lock.""" + + async def __aenter__(self) -> "LockHandle": ... + async def __aexit__(self, *_: Any) -> None: ... + + +class StorageError(Exception): + """Base class for all storage-layer errors.""" + + +class LockAcquisitionError(StorageError): + """Raised when a lock cannot be acquired within the timeout.""" + + +__all__ = ["LockHandle", "StorageError", "LockAcquisitionError"] diff --git a/app/platform/storage/media_cache.py b/app/platform/storage/media_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..f91b06d3fa36b2647be91117dafe93b39e4ac41e --- /dev/null +++ b/app/platform/storage/media_cache.py @@ -0,0 +1,501 @@ +"""Local media cache helpers with optional capacity enforcement.""" + +import asyncio +import os +import sqlite3 +import threading +import time +import uuid +from contextlib import closing, contextmanager +from pathlib import Path +from typing import Any, Callable, Literal + +from app.platform.config.snapshot import get_config +from app.platform.logging.logger import logger + +from .media_paths import ( + image_files_dir, + local_media_cache_db_path, + local_media_lock_path, + video_files_dir, +) + +MediaType = Literal["image", "video"] + +_LOW_WATERMARK_RATIO = 0.60 +_TABLE = "local_media_files" +_IMAGE_EXTS = frozenset({".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}) +_VIDEO_EXTS = frozenset({".mp4", ".mov", ".m4v", ".webm", ".avi", ".mkv"}) + + +class LocalMediaCacheStore: + """Manage local media files and enforce per-type cache limits.""" + + def __init__(self, *, config_provider: Callable[[], Any] = get_config) -> None: + self._config_provider = config_provider + self._init_lock = threading.Lock() + self._thread_locks = { + "image": threading.Lock(), + "video": threading.Lock(), + } + self._initialized_dbs: set[Path] = set() + + def save_image(self, raw: bytes, mime: str, file_id: str) -> str: + """Persist an image and return the stable local file ID.""" + ext = ".png" if "png" in mime.lower() else ".jpg" + self._save("image", file_id=file_id, raw=raw, suffix=ext) + return file_id + + def save_video(self, raw: bytes, file_id: str) -> Path: + """Persist a video and return the final file path.""" + return self._save("video", file_id=file_id, raw=raw, suffix=".mp4") + + def reconcile(self, media_type: MediaType) -> None: + """Rebuild the on-disk index for one media type and enforce limits.""" + max_bytes = self._limit_bytes(media_type) + if max_bytes <= 0: + return + with self._guard(media_type), closing(self._connect()) as conn: + rows = [] + for path in self._iter_files(media_type): + try: + stat = path.stat() + except OSError: + continue + rows.append( + ( + media_type, + path.name, + int(stat.st_size), + int(stat.st_mtime_ns), + int(stat.st_mtime_ns), + ) + ) + conn.execute(f"DELETE FROM {_TABLE} WHERE media_type = ?", (media_type,)) + if rows: + conn.executemany( + f""" + INSERT INTO {_TABLE} ( + media_type, + name, + size_bytes, + created_at_ns, + updated_at_ns + ) VALUES (?, ?, ?, ?, ?) + """, + rows, + ) + self._enforce_limit_locked(conn, media_type) + conn.commit() + + def delete(self, media_type: MediaType, name: str) -> bool: + """Delete a single local media file and keep the index consistent.""" + safe_name = self._validate_name(media_type, name) + path = self._path_for_name(media_type, safe_name) + with self._guard(media_type): + existed = path.is_file() + if existed: + path.unlink(missing_ok=True) + self._delete_index_row_if_present(media_type, safe_name) + return existed + + def clear(self, media_type: MediaType) -> int: + """Delete all tracked local media files for one media type.""" + removed = 0 + with self._guard(media_type): + for path in self._iter_files(media_type): + if path.is_file(): + path.unlink(missing_ok=True) + removed += 1 + self._delete_index_rows_if_present(media_type) + return removed + + # ------------------------------------------------------------------ + # Internal helpers + # ------------------------------------------------------------------ + + def _save( + self, + media_type: MediaType, + *, + file_id: str, + raw: bytes, + suffix: str, + ) -> Path: + path = self._media_dir(media_type) / f"{file_id}{suffix}" + if self._limit_bytes(media_type) <= 0: + self._write_if_missing(path, raw) + return path + + with self._guard(media_type), closing(self._connect()) as conn: + if path.exists(): + self._upsert_existing_row(conn, media_type, path) + else: + self._atomic_write(path, raw) + self._upsert_new_row(conn, media_type, path) + self._enforce_limit_locked(conn, media_type, protected_names={path.name}) + conn.commit() + return path + + def _limit_bytes(self, media_type: MediaType) -> int: + cfg = self._config_provider() + limit_mb = max(0, int(cfg.get_int(f"cache.local.{media_type}_max_mb", 0))) + return limit_mb * 1024 * 1024 + + def _target_bytes(self, max_bytes: int) -> int: + return max(0, int(max_bytes * _LOW_WATERMARK_RATIO)) + + def _media_dir(self, media_type: MediaType) -> Path: + return image_files_dir() if media_type == "image" else video_files_dir() + + def _allowed_exts(self, media_type: MediaType) -> frozenset[str]: + return _IMAGE_EXTS if media_type == "image" else _VIDEO_EXTS + + def _iter_files(self, media_type: MediaType): + allowed = self._allowed_exts(media_type) + for path in self._media_dir(media_type).glob("*"): + if path.is_file() and path.suffix.lower() in allowed: + yield path + + def _path_for_name(self, media_type: MediaType, name: str) -> Path: + return self._media_dir(media_type) / name + + def _validate_name(self, media_type: MediaType, name: str) -> str: + value = (name or "").strip() + if not value: + raise ValueError("missing file name") + if Path(value).name != value: + raise ValueError("invalid file name") + if Path(value).suffix.lower() not in self._allowed_exts(media_type): + raise ValueError("unsupported file type") + return value + + def _write_if_missing(self, path: Path, raw: bytes) -> None: + if path.exists(): + return + self._atomic_write(path, raw) + + def _atomic_write(self, path: Path, raw: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + if path.exists(): + return + tmp = path.parent / f".{path.name}.{uuid.uuid4().hex}.part" + try: + with tmp.open("wb") as handle: + handle.write(raw) + if path.exists(): + return + os.replace(tmp, path) + finally: + tmp.unlink(missing_ok=True) + + @contextmanager + def _guard(self, media_type: MediaType): + thread_lock = self._thread_locks[media_type] + thread_lock.acquire() + fd: int | None = None + try: + lock_path = local_media_lock_path(media_type) + lock_path.parent.mkdir(parents=True, exist_ok=True) + try: + import fcntl + + fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o644) + fcntl.flock(fd, fcntl.LOCK_EX) + except (ImportError, OSError, AttributeError): + fd = None + yield + finally: + if fd is not None: + try: + import fcntl + + fcntl.flock(fd, fcntl.LOCK_UN) + os.close(fd) + except (ImportError, OSError): + pass + thread_lock.release() + + def _connect(self) -> sqlite3.Connection: + db_path = local_media_cache_db_path() + db_path.parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(db_path, check_same_thread=False) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA synchronous=NORMAL") + conn.execute("PRAGMA busy_timeout=5000") + self._ensure_schema(conn, db_path) + return conn + + def _ensure_schema(self, conn: sqlite3.Connection, db_path: Path) -> None: + if db_path in self._initialized_dbs: + return + with self._init_lock: + if db_path in self._initialized_dbs: + return + conn.executescript( + f""" + CREATE TABLE IF NOT EXISTS {_TABLE} ( + media_type TEXT NOT NULL, + name TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + created_at_ns INTEGER NOT NULL, + updated_at_ns INTEGER NOT NULL, + PRIMARY KEY (media_type, name) + ); + CREATE INDEX IF NOT EXISTS idx_local_media_order + ON {_TABLE} (media_type, created_at_ns, name); + """ + ) + conn.commit() + self._initialized_dbs.add(db_path) + + def _upsert_existing_row( + self, + conn: sqlite3.Connection, + media_type: MediaType, + path: Path, + ) -> None: + try: + stat = path.stat() + except OSError: + return + created_at_ns = self._lookup_created_at_ns( + conn, + media_type, + path.name, + fallback=int(stat.st_mtime_ns), + ) + conn.execute( + f""" + INSERT INTO {_TABLE} ( + media_type, + name, + size_bytes, + created_at_ns, + updated_at_ns + ) VALUES (?, ?, ?, ?, ?) + ON CONFLICT(media_type, name) DO UPDATE SET + size_bytes = excluded.size_bytes, + updated_at_ns = excluded.updated_at_ns + """, + ( + media_type, + path.name, + int(stat.st_size), + created_at_ns, + int(stat.st_mtime_ns), + ), + ) + + def _upsert_new_row( + self, + conn: sqlite3.Connection, + media_type: MediaType, + path: Path, + ) -> None: + stat = path.stat() + now_ns = time.time_ns() + conn.execute( + f""" + INSERT INTO {_TABLE} ( + media_type, + name, + size_bytes, + created_at_ns, + updated_at_ns + ) VALUES (?, ?, ?, ?, ?) + ON CONFLICT(media_type, name) DO UPDATE SET + size_bytes = excluded.size_bytes, + created_at_ns = excluded.created_at_ns, + updated_at_ns = excluded.updated_at_ns + """, + ( + media_type, + path.name, + int(stat.st_size), + now_ns, + now_ns, + ), + ) + + def _lookup_created_at_ns( + self, + conn: sqlite3.Connection, + media_type: MediaType, + name: str, + *, + fallback: int, + ) -> int: + row = conn.execute( + f""" + SELECT created_at_ns + FROM {_TABLE} + WHERE media_type = ? AND name = ? + """, + (media_type, name), + ).fetchone() + return int(row["created_at_ns"]) if row else int(fallback) + + def _usage_bytes(self, conn: sqlite3.Connection, media_type: MediaType) -> int: + row = conn.execute( + f"SELECT COALESCE(SUM(size_bytes), 0) AS total FROM {_TABLE} WHERE media_type = ?", + (media_type,), + ).fetchone() + return int(row["total"]) if row else 0 + + def _newest_name(self, conn: sqlite3.Connection, media_type: MediaType) -> str: + row = conn.execute( + f""" + SELECT name + FROM {_TABLE} + WHERE media_type = ? + ORDER BY created_at_ns DESC, name DESC + LIMIT 1 + """, + (media_type,), + ).fetchone() + return str(row["name"]) if row else "" + + def _enforce_limit_locked( + self, + conn: sqlite3.Connection, + media_type: MediaType, + *, + protected_names: set[str] | None = None, + ) -> None: + max_bytes = self._limit_bytes(media_type) + if max_bytes <= 0: + return + + usage_bytes = self._usage_bytes(conn, media_type) + if usage_bytes <= max_bytes: + return + + protected = set(protected_names or ()) + newest_name = self._newest_name(conn, media_type) + if newest_name: + protected.add(newest_name) + + target_bytes = self._target_bytes(max_bytes) + rows = conn.execute( + f""" + SELECT name, size_bytes + FROM {_TABLE} + WHERE media_type = ? + ORDER BY created_at_ns ASC, name ASC + """, + (media_type,), + ).fetchall() + + removed = 0 + for row in rows: + if usage_bytes <= target_bytes: + break + + name = str(row["name"]) + if name in protected: + continue + + path = self._path_for_name(media_type, name) + size_bytes = int(row["size_bytes"]) + + if path.exists(): + try: + path.unlink(missing_ok=True) + except OSError as exc: + logger.warning( + "local media cache delete failed: media_type={} name={} error={}", + media_type, + name, + exc, + ) + continue + + conn.execute( + f"DELETE FROM {_TABLE} WHERE media_type = ? AND name = ?", + (media_type, name), + ) + usage_bytes = max(0, usage_bytes - size_bytes) + removed += 1 + + if removed: + logger.info( + "local media cache trimmed: media_type={} removed={} usage_bytes={} limit_bytes={} target_bytes={}", + media_type, + removed, + usage_bytes, + max_bytes, + target_bytes, + ) + elif usage_bytes > max_bytes: + logger.info( + "local media cache kept newest oversized file: media_type={} usage_bytes={} limit_bytes={}", + media_type, + usage_bytes, + max_bytes, + ) + + def _delete_index_row_if_present(self, media_type: MediaType, name: str) -> None: + db_path = local_media_cache_db_path() + if not db_path.exists(): + return + with closing(self._connect()) as conn: + conn.execute( + f"DELETE FROM {_TABLE} WHERE media_type = ? AND name = ?", + (media_type, name), + ) + conn.commit() + + def _delete_index_rows_if_present(self, media_type: MediaType) -> None: + db_path = local_media_cache_db_path() + if not db_path.exists(): + return + with closing(self._connect()) as conn: + conn.execute(f"DELETE FROM {_TABLE} WHERE media_type = ?", (media_type,)) + conn.commit() + + +local_media_cache = LocalMediaCacheStore() + + +def save_local_image(raw: bytes, mime: str, file_id: str) -> str: + """Persist an image to local cache and return the file ID.""" + return local_media_cache.save_image(raw, mime, file_id) + + +def save_local_video(raw: bytes, file_id: str) -> Path: + """Persist a video to local cache and return the file path.""" + return local_media_cache.save_video(raw, file_id) + + +def clear_local_media_files(media_type: MediaType) -> int: + """Delete all local media files for the requested type.""" + return local_media_cache.clear(media_type) + + +def delete_local_media_file(media_type: MediaType, name: str) -> bool: + """Delete one local media file by file name.""" + return local_media_cache.delete(media_type, name) + + +async def reconcile_local_media_cache_async( + media_type: MediaType | None = None, +) -> None: + """Rebuild local media cache indexes and enforce configured limits.""" + if media_type is None: + for item in ("image", "video"): + await asyncio.to_thread(local_media_cache.reconcile, item) + return + await asyncio.to_thread(local_media_cache.reconcile, media_type) + + +__all__ = [ + "LocalMediaCacheStore", + "clear_local_media_files", + "delete_local_media_file", + "local_media_cache", + "reconcile_local_media_cache_async", + "save_local_image", + "save_local_video", +] diff --git a/app/platform/storage/media_paths.py b/app/platform/storage/media_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..360f4327085d37f73632ed06e55a110b8be8c6d1 --- /dev/null +++ b/app/platform/storage/media_paths.py @@ -0,0 +1,49 @@ +"""Shared local media storage paths.""" + +from pathlib import Path + +from app.platform.paths import data_path + + +def _files_dir() -> Path: + return data_path("files") + + +def _cache_dir() -> Path: + return data_path("cache") + + +def image_files_dir() -> Path: + """Return the local image storage directory.""" + path = _files_dir() / "images" + path.mkdir(parents=True, exist_ok=True) + return path + + +def video_files_dir() -> Path: + """Return the local video storage directory.""" + path = _files_dir() / "videos" + path.mkdir(parents=True, exist_ok=True) + return path + + +def local_media_cache_db_path() -> Path: + """Return the SQLite index path for local media cache bookkeeping.""" + path = _cache_dir() + path.mkdir(parents=True, exist_ok=True) + return path / "local_media_cache.db" + + +def local_media_lock_path(media_type: str) -> Path: + """Return the advisory lock file used by one media-type cache operation.""" + path = _cache_dir() / "locks" + path.mkdir(parents=True, exist_ok=True) + return path / f"local_media_{media_type}.lock" + + +__all__ = [ + "image_files_dir", + "local_media_cache_db_path", + "local_media_lock_path", + "video_files_dir", +] diff --git a/app/platform/storage/revision.py b/app/platform/storage/revision.py new file mode 100644 index 0000000000000000000000000000000000000000..1e7c5e22b17211d86fd56ed96889bab6ec0c790b --- /dev/null +++ b/app/platform/storage/revision.py @@ -0,0 +1,50 @@ +"""Revision semantics for storage backends. + +## Contract + +- A **revision** is a monotonically increasing integer scoped to a single + storage domain (e.g. accounts, proxies). +- Every mutation that changes persisted state **must** increment the revision + by exactly 1. +- Readers compare their last-seen revision against the current value to detect + whether new data is available (``scan_changes(since_revision=...)``). +- Revisions are **not** globally ordered across domains — only within one. + +## RevisionTracker mixin + +Backends that manage their own revision counter (e.g. SQLite, in-memory) +can inherit from ``RevisionTracker`` to get a thread-safe bump + read helper. +""" + +import threading + + +class RevisionTracker: + """Thread-safe monotonic revision counter. + + Subclass or mix into a storage backend to provide ``bump()`` and + ``current`` without touching the database. + """ + + def __init__(self, initial: int = 0) -> None: + self._revision = initial + self._lock = threading.Lock() + + @property + def current(self) -> int: + with self._lock: + return self._revision + + def bump(self) -> int: + """Increment and return the new revision.""" + with self._lock: + self._revision += 1 + return self._revision + + def set(self, value: int) -> None: + """Force-set the revision (e.g. after loading from DB).""" + with self._lock: + self._revision = value + + +__all__ = ["RevisionTracker"] diff --git a/app/platform/tokens.py b/app/platform/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..dd87c96be006a44a0112962076097200ee3736e9 --- /dev/null +++ b/app/platform/tokens.py @@ -0,0 +1,73 @@ +"""Unified token estimation utilities. + +All API surfaces share the same tokenizer-backed approximation so usage +reporting stays consistent across OpenAI-compatible and Anthropic-compatible +responses. +""" + +from functools import lru_cache +from typing import Any + +import orjson +import tiktoken + +PROMPT_OVERHEAD = 4 +_ENCODING_NAME = "o200k_base" + + +@lru_cache(maxsize=1) +def _get_encoding() -> tiktoken.Encoding: + return tiktoken.get_encoding(_ENCODING_NAME) + + +def _coerce_text(value: Any) -> str: + if value is None: + return "" + if isinstance(value, str): + return value + try: + return orjson.dumps(value).decode() + except (TypeError, ValueError): + return str(value) + + +def estimate_tokens(value: Any) -> int: + text = _coerce_text(value).strip() + if not text: + return 0 + return len(_get_encoding().encode(text, disallowed_special=())) + + +def estimate_prompt_tokens(value: Any, *, overhead: int = PROMPT_OVERHEAD) -> int: + base = estimate_tokens(value) + if base <= 0: + return 0 + return base + max(0, overhead) + + +def estimate_tool_call_tokens(tool_calls: list[Any]) -> int: + normalized: list[Any] = [] + for call in tool_calls: + if isinstance(call, dict): + normalized.append(call) + continue + name = getattr(call, "name", None) + arguments = getattr(call, "arguments", None) + call_id = getattr(call, "call_id", None) + if name is not None and arguments is not None: + normalized.append({ + "id": call_id or "", + "name": name, + "arguments": arguments, + }) + continue + normalized.append(call) + return estimate_tokens(normalized) + + +__all__ = [ + "PROMPT_OVERHEAD", + "estimate_tokens", + "estimate_prompt_tokens", + "estimate_tool_call_tokens", +] diff --git a/app/platform/update_check.py b/app/platform/update_check.py new file mode 100644 index 0000000000000000000000000000000000000000..39e7c894e6ab31ccc2961404a87fa05aa5db0771 --- /dev/null +++ b/app/platform/update_check.py @@ -0,0 +1,159 @@ +"""GitHub release update checks with lightweight in-process caching.""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timezone +import re +import time +from typing import Any + +import aiohttp + +from app.platform.meta import get_project_version + +_RELEASES_URL = "https://api.github.com/repos/jiujiu532/grok2api/releases" +_CACHE_TTL_SECONDS = 86400.0 +_ERROR_TTL_SECONDS = 300.0 +_LOCK = asyncio.Lock() +_CACHE: dict[str, Any] = {"expires_at": 0.0, "payload": None} + + +def _utc_now_iso() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _normalize_version(value: str) -> str: + text = str(value or "").strip() + if text.lower().startswith("v"): + text = text[1:] + return text + + +def _parse_version(value: str) -> tuple[int, int, int, int, int] | None: + normalized = _normalize_version(value) + match = re.match(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:(?:\.|-)?rc(\d+))?$", normalized, re.IGNORECASE) + if not match: + return None + major, minor, patch, rc = match.groups() + is_final = 1 if rc is None else 0 + rc_number = int(rc or 0) + return int(major or 0), int(minor or 0), int(patch or 0), is_final, rc_number + + +def _is_newer(latest: str, current: str) -> bool: + latest_parsed = _parse_version(latest) + current_parsed = _parse_version(current) + if latest_parsed and current_parsed: + return latest_parsed > current_parsed + return _normalize_version(latest) > _normalize_version(current) + + +def _release_version_key(release: dict[str, Any]) -> tuple[int, int, int, int, int] | None: + version = str(release.get("tag_name") or release.get("name") or "").strip() + return _parse_version(version) + + +def _select_latest_release(releases: list[dict[str, Any]]) -> dict[str, Any] | None: + candidates: list[tuple[tuple[int, int, int, int, int], dict[str, Any]]] = [] + for release in releases: + if not isinstance(release, dict) or bool(release.get("draft")): + continue + version_key = _release_version_key(release) + if version_key is None: + continue + candidates.append((version_key, release)) + if not candidates: + return None + candidates.sort(key=lambda item: item[0], reverse=True) + return candidates[0][1] + + +def _normalize_error_message(value: str) -> str: + text = str(value or "").strip() + lowered = text.lower() + if "rate limit exceeded" in lowered: + return "GitHub API rate limit exceeded." + if text.startswith("GitHub release query failed:"): + status_match = re.search(r"GitHub release query failed:\s*(\d{3})", text) + if status_match: + return f"GitHub release query failed ({status_match.group(1)})." + return "GitHub release query failed." + if text == "GitHub releases response invalid": + return "GitHub releases response invalid." + if text == "No valid GitHub releases found": + return "No valid GitHub releases found." + return text or "Update check failed." + + +def _build_payload(release: dict[str, Any] | None = None, error: str = "") -> dict[str, Any]: + current_version = get_project_version() + release = release or {} + latest_version = _normalize_version(str(release.get("tag_name") or release.get("name") or "")) + release_name = str(release.get("name") or "").strip() + release_url = str(release.get("html_url") or "").strip() + published_at = str(release.get("published_at") or "").strip() + release_notes = str(release.get("body") or "").strip() + has_remote = bool(release) + return { + "current_version": current_version, + "latest_version": latest_version, + "release_name": release_name, + "release_url": release_url, + "published_at": published_at, + "release_notes": release_notes, + "update_available": has_remote and bool(latest_version) and _is_newer(latest_version, current_version), + "checked_at": _utc_now_iso(), + "status": "error" if error else "ok", + "error": _normalize_error_message(error), + } + + +async def _fetch_latest_release() -> dict[str, Any]: + timeout = aiohttp.ClientTimeout(total=10) + headers = { + "Accept": "application/vnd.github+json", + "User-Agent": "grok2api-update-check", + } + async with aiohttp.ClientSession(timeout=timeout) as session: + async with session.get(_RELEASES_URL, headers=headers, params={"per_page": "100"}) as response: + if response.status != 200: + detail = (await response.text()).strip() + raise RuntimeError(f"GitHub release query failed: {response.status} {detail}".strip()) + data = await response.json() + if not isinstance(data, list): + raise RuntimeError("GitHub releases response invalid") + release = _select_latest_release(data) + if not release: + raise RuntimeError("No valid GitHub releases found") + return release + + +async def get_latest_release_info(force: bool = False) -> dict[str, Any]: + now = time.monotonic() + cached = _CACHE.get("payload") + expires_at = float(_CACHE.get("expires_at") or 0.0) + if not force and cached and expires_at > now: + return cached + + async with _LOCK: + cached = _CACHE.get("payload") + expires_at = float(_CACHE.get("expires_at") or 0.0) + now = time.monotonic() + if not force and cached and expires_at > now: + return cached + + try: + release = await _fetch_latest_release() + payload = _build_payload(release=release) + ttl = _CACHE_TTL_SECONDS + except Exception as exc: + payload = _build_payload(error=str(exc)) + ttl = _ERROR_TTL_SECONDS + + _CACHE["payload"] = payload + _CACHE["expires_at"] = now + ttl + return payload + + +__all__ = ["get_latest_release_info"] diff --git a/app/products/__init__.py b/app/products/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/products/_account_selection.py b/app/products/_account_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f9423d973bf299fd1fef11912f93a2a8943362 --- /dev/null +++ b/app/products/_account_selection.py @@ -0,0 +1,85 @@ +"""Shared account selection helpers for products-layer request handlers.""" + +from app.control.model.enums import ModeId +from app.control.model.spec import ModelSpec +from app.control.account.runtime import get_refresh_service +from app.dataplane.account.selector import current_strategy +from app.platform.config.snapshot import get_config + +# Random strategy has no config key for retry count; it is pinned here so that +# every retry-driven call site (chat / images / video / anthropic) sees the same +# value without introducing scattered magic numbers. +_RANDOM_MAX_RETRIES = 5 + + +def selection_max_retries() -> int: + """Retry count for account-swap loops, aware of the active selection strategy. + + - ``random`` strategy: fixed at :data:`_RANDOM_MAX_RETRIES` (=5). + - ``quota`` strategy: reads ``retry.max_retries`` (default 1), preserving + the historical behaviour. + """ + if current_strategy() == "random": + return _RANDOM_MAX_RETRIES + return int(get_config("retry.max_retries", 1)) + + +def mode_candidates(spec: ModelSpec) -> tuple[int, ...]: + """Return mode IDs to try for *spec* in priority order. + + Chat models using ``AUTO`` can optionally fall back to ``FAST`` and then + ``EXPERT`` when the upstream ``auto`` quota window is exhausted but the + account still has usable quota in the other chat windows. + """ + primary = int(spec.mode_id) + if ( + spec.is_chat() + and spec.mode_id == ModeId.AUTO + and get_config("features.auto_chat_mode_fallback", True) + ): + return (primary, int(ModeId.FAST), int(ModeId.EXPERT)) + return (primary,) + + +async def reserve_account( + directory, + spec: ModelSpec, + *, + exclude_tokens: list[str] | None = None, + now_s_override: int | None = None, +): + """Reserve an account and return ``(lease, selected_mode_id)``. + + Returns ``(None, original_mode_id)`` when no account is available. Under the + random strategy no on-demand refresh fallback is attempted — upstream quota + data is never probed. + """ + original_mode_id = int(spec.mode_id) + + async def _try_reserve(): + for candidate_mode_id in mode_candidates(spec): + lease = await directory.reserve( + pool_candidates=spec.pool_candidates(), + mode_id=candidate_mode_id, + now_s_override=now_s_override, + exclude_tokens=exclude_tokens, + ) + if lease is not None: + return lease, candidate_mode_id + return None, original_mode_id + + lease, selected_mode_id = await _try_reserve() + if lease is not None: + return lease, selected_mode_id + + if current_strategy() == "random": + return None, original_mode_id + + refresh_svc = get_refresh_service() + if refresh_svc is not None: + await refresh_svc.refresh_on_demand() + lease, selected_mode_id = await _try_reserve() + if lease is not None: + return lease, selected_mode_id + + return None, original_mode_id diff --git a/app/products/anthropic/__init__.py b/app/products/anthropic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2b9714b8329c7b987f38c33939d4634ba931f9 --- /dev/null +++ b/app/products/anthropic/__init__.py @@ -0,0 +1 @@ +"""Anthropic Messages API product (/v1/messages).""" diff --git a/app/products/anthropic/console_messages.py b/app/products/anthropic/console_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..9904414387e99082f8cf95114129d59dd9b0ed41 --- /dev/null +++ b/app/products/anthropic/console_messages.py @@ -0,0 +1,319 @@ +"""Console Messages API handler — /v1/messages for console.x.ai models. + +将 console.x.ai 上游 SSE 转换为 Anthropic Messages API 格式输出。 +""" + +import asyncio +from typing import Any, AsyncGenerator + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError +from app.platform.runtime.clock import now_s +from app.platform.tokens import estimate_prompt_tokens, estimate_tokens +from app.control.account.enums import FeedbackKind +from app.control.account.invalid_credentials import feedback_kind_for_error +from app.control.account.runtime import get_refresh_service +from app.control.model.registry import resolve as resolve_model +from app.dataplane.account.selector import current_strategy +from app.dataplane.reverse.protocol.xai_console_chat import ( + build_console_payload, + ConsoleStreamAdapter, + stream_console_chat, +) +from app.products._account_selection import reserve_account, selection_max_retries +from app.products.openai.chat import _configured_retry_codes, _should_retry_upstream + + +def _sse(event: str, data: dict) -> str: + return f"event: {event}\ndata: {orjson.dumps(data).decode()}\n\n" + + +def _log_task_exception(task: "asyncio.Task") -> None: + exc = task.exception() if not task.cancelled() else None + if exc: + logger.warning("background task failed: task={} error={}", task.get_name(), exc) + + +async def _quota_sync(token: str, mode_id: int) -> None: + """Fire-and-forget: 成功调用后持久化配额扣减和 usage_use_count。 + + Console 配额(mode_id=5)为本地管理,不依赖上游 API, + 无论 random/quota 策略都需要执行扣减和窗口重置。 + """ + try: + if current_strategy() != "quota" and mode_id != 5: + return + svc = get_refresh_service() + if svc: + await svc.refresh_call_async(token, mode_id) + except Exception as exc: + logger.warning( + "console messages quota sync failed: token={}... mode_id={} error={}", + token[:10], + mode_id, + exc, + ) + + +async def _fail_sync(token: str, mode_id: int, exc: BaseException | None = None) -> None: + """Fire-and-forget: 失败后持久化失败计数。""" + try: + svc = get_refresh_service() + if svc: + await svc.record_failure_async(token, mode_id, exc) + except Exception as e: + logger.warning( + "console messages fail sync error: token={}... mode_id={} error={}", + token[:10], + mode_id, + e, + ) + + +async def create( + *, + model: str, + messages: list[dict], + stream: bool, + emit_think: bool, + temperature: float, + top_p: float, + msg_id: str, +) -> dict | AsyncGenerator[str, None]: + """Console models /v1/messages handler (Anthropic format).""" + + cfg = get_config() + spec = resolve_model(model) + timeout_s = cfg.get_float("chat.timeout", 120.0) + max_retries = selection_max_retries() + retry_codes = _configured_retry_codes(cfg) + effort = "low" if emit_think else "none" + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + directory = _acct_dir + + # ── Streaming ───────────────────────────────────────────────────────────── + if stream: + async def _run_stream() -> AsyncGenerator[str, None]: + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, spec, now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + fail_exc: BaseException | None = None + _retry = False + adapter = ConsoleStreamAdapter() + text_buf: list[str] = [] + + try: + payload = build_console_payload( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=effort, + stream=True, + ) + + try: + # message_start + yield _sse("message_start", { + "type": "message_start", + "message": { + "id": msg_id, + "type": "message", + "role": "assistant", + "model": model, + "content": [], + "stop_reason": None, + "usage": {"input_tokens": estimate_prompt_tokens(messages), "output_tokens": 0}, + }, + }) + yield _sse("ping", {"type": "ping"}) + + # content_block_start + yield _sse("content_block_start", { + "type": "content_block_start", + "index": 0, + "content_block": {"type": "text", "text": ""}, + }) + + yield ": heartbeat\n\n" + async for event_type, data in stream_console_chat( + token, payload, timeout_s=timeout_s + ): + tokens = adapter.feed(event_type, data) + for tok in tokens: + text_buf.append(tok) + yield _sse("content_block_delta", { + "type": "content_block_delta", + "index": 0, + "delta": {"type": "text_delta", "text": tok}, + }) + + # content_block_stop + yield _sse("content_block_stop", { + "type": "content_block_stop", + "index": 0, + }) + + # message_delta + full_text = "".join(text_buf) + output_tokens = ( + adapter.usage.get("output_tokens", 0) if adapter.usage + else estimate_tokens(full_text) + ) + yield _sse("message_delta", { + "type": "message_delta", + "delta": {"stop_reason": "end_turn", "stop_sequence": None}, + "usage": {"output_tokens": output_tokens}, + }) + + # message_stop + yield _sse("message_stop", {"type": "message_stop"}) + yield "data: [DONE]\n\n" + success = True + logger.info( + "console messages stream completed: model={} text_len={} attempt={}/{}", + model, len(full_text), attempt + 1, max_retries + 1, + ) + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + _retry = True + logger.warning( + "console messages retry: attempt={}/{} status={}", + attempt + 1, max_retries, exc.status, + ) + else: + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS if success + else feedback_kind_for_error(fail_exc) if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task( + _quota_sync(token, selected_mode_id) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, selected_mode_id, fail_exc) + ).add_done_callback(_log_task_exception) + + if success or not _retry: + return + excluded.append(token) + + return _run_stream() + + # ── Non-streaming ───────────────────────────────────────────────────────── + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, spec, now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + fail_exc: BaseException | None = None + adapter = ConsoleStreamAdapter() + + try: + payload = build_console_payload( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=effort, + stream=True, + ) + + try: + async for event_type, data in stream_console_chat( + token, payload, timeout_s=timeout_s + ): + adapter.feed(event_type, data) + + full_text = adapter.full_text + usage_data = adapter.usage + input_tokens = ( + usage_data.get("input_tokens", 0) if usage_data + else estimate_prompt_tokens(messages) + ) + output_tokens = ( + usage_data.get("output_tokens", 0) if usage_data + else estimate_tokens(full_text) + ) + + result = { + "id": msg_id, + "type": "message", + "role": "assistant", + "model": model, + "content": [{"type": "text", "text": full_text}], + "stop_reason": "end_turn", + "stop_sequence": None, + "usage": { + "input_tokens": input_tokens, + "output_tokens": output_tokens, + }, + } + success = True + logger.info( + "console messages non-stream completed: model={} text_len={}", + model, len(full_text), + ) + return result + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + logger.warning( + "console messages non-stream retry: attempt={}/{} status={}", + attempt + 1, max_retries, exc.status, + ) + excluded.append(token) + continue + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS if success + else feedback_kind_for_error(fail_exc) if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task( + _quota_sync(token, selected_mode_id) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, selected_mode_id, fail_exc) + ).add_done_callback(_log_task_exception) + + raise RateLimitError("No available accounts after retries") + + +__all__ = ["create"] diff --git a/app/products/anthropic/messages.py b/app/products/anthropic/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..dd37451efd57853399ca1186e6201fa3749f96e3 --- /dev/null +++ b/app/products/anthropic/messages.py @@ -0,0 +1,779 @@ +"""Anthropic Messages API handler (/v1/messages). + +Adapts Anthropic SDK requests to the internal Grok reverse-proxy pipeline, +then converts the response back to Anthropic Messages API format. + +Reuses the same _stream_chat / StreamAdapter / ToolSieve machinery as +responses.py — only the input/output format conversion differs. +""" + +import asyncio +import os +import time +from typing import Any, AsyncGenerator + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError +from app.platform.runtime.clock import now_s +from app.platform.tokens import estimate_prompt_tokens, estimate_tokens, estimate_tool_call_tokens +from app.control.model.enums import ModeId +from app.control.model.registry import resolve as resolve_model +from app.control.account.enums import FeedbackKind +from app.dataplane.reverse.protocol.xai_chat import classify_line, StreamAdapter +from app.dataplane.reverse.protocol.tool_prompt import ( + build_tool_system_prompt, extract_tool_names, inject_into_message, +) +from app.dataplane.reverse.protocol.tool_parser import parse_tool_calls + +from app.products.openai.chat import ( + _stream_chat, _extract_message, _resolve_image, + _quota_sync, _fail_sync, _parse_retry_codes, _feedback_kind, _log_task_exception, + _configured_retry_codes, _should_retry_upstream, +) +from app.products._account_selection import reserve_account, selection_max_retries +from app.products.openai._tool_sieve import ToolSieve + + +# --------------------------------------------------------------------------- +# ID helpers +# --------------------------------------------------------------------------- + +def _make_msg_id() -> str: + return f"msg_{int(time.time() * 1000)}{os.urandom(4).hex()}" + + +def _make_tool_id() -> str: + return f"toolu_{int(time.time() * 1000)}{os.urandom(3).hex()}" + + +# --------------------------------------------------------------------------- +# SSE encoding (Anthropic event format) +# --------------------------------------------------------------------------- + +def _sse(event: str, data: dict) -> str: + return f"event: {event}\ndata: {orjson.dumps(data).decode()}\n\n" + + +# --------------------------------------------------------------------------- +# Request conversion: Anthropic → internal format +# --------------------------------------------------------------------------- + +def _anthropic_content_to_internal(content: Any, role: str) -> list[dict]: + """Convert Anthropic content (string or block list) to internal message list. + + Returns a list of internal messages (may be multiple when tool_result + blocks need to become separate tool-role messages). + """ + if isinstance(content, str): + return [{"role": role, "content": content}] + + if not isinstance(content, list): + return [] + + # Check if content contains tool_use blocks (assistant calling tools) + has_tool_use = any( + isinstance(b, dict) and b.get("type") == "tool_use" + for b in content + ) + + # Check if content contains tool_result blocks (user returning results) + tool_result_blocks = [ + b for b in content + if isinstance(b, dict) and b.get("type") == "tool_result" + ] + + if tool_result_blocks: + # Each tool_result → a separate tool-role message + messages = [] + for block in tool_result_blocks: + result_content = block.get("content", "") + if isinstance(result_content, list): + # array of text blocks → join + result_content = "\n".join( + b.get("text", "") for b in result_content + if isinstance(b, dict) and b.get("type") == "text" + ) + messages.append({ + "role": "tool", + "tool_call_id": block.get("tool_use_id", ""), + "content": result_content or "", + }) + return messages + + if has_tool_use: + # Build assistant message with tool_calls + text_parts: list[str] = [] + tool_calls: list[dict] = [] + for block in content: + if not isinstance(block, dict): + continue + btype = block.get("type") + if btype == "text": + text_parts.append(block.get("text", "")) + elif btype == "tool_use": + tool_calls.append({ + "id": block.get("id", _make_tool_id()), + "type": "function", + "function": { + "name": block.get("name", ""), + "arguments": orjson.dumps(block.get("input") or {}).decode(), + }, + }) + msg: dict = { + "role": "assistant", + "content": " ".join(text_parts) if text_parts else None, + "tool_calls": tool_calls, + } + return [msg] + + # Normal content: text + image + document blocks + normalized: list[dict] = [] + for block in content: + if not isinstance(block, dict): + continue + btype = block.get("type") + if btype == "text": + text = (block.get("text") or "").strip() + if text: + normalized.append({"type": "text", "text": text}) + elif btype == "image": + source = block.get("source") or {} + src_type = source.get("type", "") + if src_type == "base64": + media = source.get("media_type", "image/jpeg") + data = source.get("data", "") + normalized.append({ + "type": "image_url", + "image_url": {"url": f"data:{media};base64,{data}"}, + }) + elif src_type == "url": + normalized.append({ + "type": "image_url", + "image_url": {"url": source.get("url", "")}, + }) + elif btype == "document": + source = block.get("source") or {} + src_type = source.get("type", "") + if src_type == "base64": + media = source.get("media_type", "application/pdf") + data = source.get("data", "") + normalized.append({ + "type": "file", + "file": {"data": f"data:{media};base64,{data}"}, + }) + + if not normalized: + return [] + return [{"role": role, "content": normalized}] + + +def _parse_anthropic_messages( + messages: list[dict], + system: str | list | None, +) -> list[dict]: + """Convert Anthropic messages + system prompt to internal format.""" + internal: list[dict] = [] + + # System prompt + if system: + if isinstance(system, str): + system_text = system + elif isinstance(system, list): + system_text = "\n".join( + b.get("text", "") for b in system + if isinstance(b, dict) and b.get("type") == "text" + ) + else: + system_text = str(system) + if system_text.strip(): + internal.append({"role": "system", "content": system_text}) + + for msg in messages: + role = msg.get("role", "user") + content = msg.get("content", "") + internal.extend(_anthropic_content_to_internal(content, role)) + + return internal + + +def _convert_tools(tools: list[dict]) -> list[dict]: + """Convert Anthropic tool definitions to internal Chat Completions format. + + Anthropic: {name, description, input_schema} + Internal: {type:"function", function:{name, description, parameters}} + """ + result = [] + for tool in tools: + result.append({ + "type": "function", + "function": { + "name": tool.get("name", ""), + "description": tool.get("description", ""), + "parameters": tool.get("input_schema"), + }, + }) + return result + + +def _convert_tool_choice(tool_choice: Any) -> Any: + """Map Anthropic tool_choice → internal format.""" + if tool_choice is None: + return "auto" + if isinstance(tool_choice, str): + return tool_choice + if isinstance(tool_choice, dict): + tc_type = tool_choice.get("type", "auto") + if tc_type == "auto": + return "auto" + if tc_type == "any": + return "required" + if tc_type == "tool": + return {"type": "function", "function": {"name": tool_choice.get("name", "")}} + return "auto" + + +# --------------------------------------------------------------------------- +# Response format helpers +# --------------------------------------------------------------------------- + +def _finish_reason_to_stop_reason(finish_reason: str | None) -> str: + mapping = {"stop": "end_turn", "tool_calls": "tool_use", "length": "max_tokens"} + return mapping.get(finish_reason or "stop", "end_turn") + + +def _build_message_response( + msg_id: str, + model: str, + content: list[dict], + stop_reason: str, + input_tokens: int, + output_tokens: int, +) -> dict: + return { + "id": msg_id, + "type": "message", + "role": "assistant", + "model": model, + "content": content, + "stop_reason": stop_reason, + "stop_sequence": None, + "usage": { + "input_tokens": input_tokens, + "output_tokens": output_tokens, + }, + } + + +# --------------------------------------------------------------------------- +# Main handler +# --------------------------------------------------------------------------- + +async def create( + *, + model: str, + messages: list[dict], + system: str | list | None = None, + stream: bool, + emit_think: bool, + temperature: float, + top_p: float, + tools: list[dict] | None = None, + tool_choice: Any = None, +) -> dict | AsyncGenerator[str, None]: + + cfg = get_config() + spec = resolve_model(model) + mode_id = int(spec.mode_id) + + # Build internal message list + internal_messages = _parse_anthropic_messages(messages, system) + internal_message, files = _extract_message(internal_messages) + if not internal_message.strip(): + raise UpstreamError("Empty message after extraction", status=400) + + # Tool injection + tool_names: list[str] = [] + internal_tool_choice: Any = None + if tools: + chat_tools = _convert_tools(tools) + tool_names = extract_tool_names(chat_tools) + internal_tool_choice = _convert_tool_choice(tool_choice) + tool_prompt = build_tool_system_prompt(chat_tools, internal_tool_choice) + internal_message = inject_into_message(internal_message, tool_prompt) + logger.info("messages tool injection: tool_names={} choice={}", tool_names, internal_tool_choice) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + directory = _acct_dir + + max_retries = selection_max_retries() + retry_codes = _configured_retry_codes(cfg) + timeout_s = cfg.get_float("chat.timeout", 120.0) + msg_id = _make_msg_id() + + # ------------------------------------------------------------------------- + # Console 模型路由 — 走 console.x.ai,输出转为 Anthropic Messages 格式 + # ------------------------------------------------------------------------- + if spec.is_console_chat(): + from .console_messages import create as console_messages_create + return await console_messages_create( + model=model, + messages=internal_messages, + stream=stream, + emit_think=emit_think, + temperature=temperature, + top_p=top_p, + msg_id=msg_id, + ) + + # ------------------------------------------------------------------------- + # Streaming (grok.com path) + # ------------------------------------------------------------------------- + async def _run_stream() -> AsyncGenerator[str, None]: + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, + spec, + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() + think_buf: list[str] = [] + text_buf: list[str] = [] + think_started = False + think_closed = False + text_started = False + sieve = ToolSieve(tool_names) if tool_names else None + tool_calls_emitted = False + tool_output_tokens = 0 + block_index = 0 # tracks next content_block index + collected_annotations: list[dict] = [] + + try: + try: + # message_start + yield _sse("message_start", { + "type": "message_start", + "message": { + "id": msg_id, + "type": "message", + "role": "assistant", + "model": model, + "content": [], + "stop_reason": None, + "usage": {"input_tokens": estimate_prompt_tokens(internal_message), "output_tokens": 0}, + }, + }) + yield _sse("ping", {"type": "ping"}) + + ended = False + yield ": heartbeat\n\n" + async for line in _stream_chat( + token = token, + mode_id = ModeId(selected_mode_id), + message = internal_message, + files = files, + timeout_s = timeout_s, + ): + if tool_calls_emitted: + break + + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + + for ev in adapter.feed(data): + + if ev.kind == "thinking" and emit_think and not think_closed: + if not think_started: + think_started = True + yield _sse("content_block_start", { + "type": "content_block_start", + "index": block_index, + "content_block": {"type": "thinking", "thinking": ""}, + }) + think_buf.append(ev.content) + yield _sse("content_block_delta", { + "type": "content_block_delta", + "index": block_index, + "delta": {"type": "thinking_delta", "thinking": ev.content}, + }) + + elif ev.kind == "text": + # Close thinking block if open + if think_started and not think_closed: + think_closed = True + yield _sse("content_block_stop", { + "type": "content_block_stop", + "index": block_index, + }) + block_index += 1 + + # Feed through ToolSieve if tools active + if sieve is not None: + safe_text, calls = sieve.feed(ev.content) + if calls is not None: + # Emit tool_use blocks + for call in calls: + yield _sse("content_block_start", { + "type": "content_block_start", + "index": block_index, + "content_block": { + "type": "tool_use", + "id": call.call_id, + "name": call.name, + "input": {}, + }, + }) + yield _sse("content_block_delta", { + "type": "content_block_delta", + "index": block_index, + "delta": { + "type": "input_json_delta", + "partial_json": call.arguments, + }, + }) + yield _sse("content_block_stop", { + "type": "content_block_stop", + "index": block_index, + }) + block_index += 1 + tool_output_tokens = estimate_tool_call_tokens(calls) + tool_calls_emitted = True + ended = True + break + text_chunk = safe_text + else: + text_chunk = ev.content + + if text_chunk: + if not text_started: + text_started = True + yield _sse("content_block_start", { + "type": "content_block_start", + "index": block_index, + "content_block": {"type": "text", "text": ""}, + }) + text_buf.append(text_chunk) + yield _sse("content_block_delta", { + "type": "content_block_delta", + "index": block_index, + "delta": {"type": "text_delta", "text": text_chunk}, + }) + + elif ev.kind == "annotation" and ev.annotation_data: + collected_annotations.append(ev.annotation_data) + + elif ev.kind == "soft_stop": + ended = True + break + + if ended: + break + + # Flush sieve — incomplete XML at end of stream + if sieve is not None and not tool_calls_emitted: + calls = sieve.flush() + if calls: + # Close text block if open + if text_started: + yield _sse("content_block_stop", { + "type": "content_block_stop", + "index": block_index, + }) + block_index += 1 + text_started = False + for call in calls: + yield _sse("content_block_start", { + "type": "content_block_start", + "index": block_index, + "content_block": { + "type": "tool_use", + "id": call.call_id, + "name": call.name, + "input": {}, + }, + }) + yield _sse("content_block_delta", { + "type": "content_block_delta", + "index": block_index, + "delta": { + "type": "input_json_delta", + "partial_json": call.arguments, + }, + }) + yield _sse("content_block_stop", { + "type": "content_block_stop", + "index": block_index, + }) + block_index += 1 + tool_output_tokens = estimate_tool_call_tokens(calls) + tool_calls_emitted = True + + if tool_calls_emitted: + # 构建 tool_use 的 message_delta,注入搜索信源 + tool_delta: dict = {"stop_reason": "tool_use", "stop_sequence": None} + sources = adapter.search_sources_list() + if sources: + tool_delta["search_sources"] = sources + yield _sse("message_delta", { + "type": "message_delta", + "delta": tool_delta, + "usage": {"output_tokens": tool_output_tokens}, + }) + yield _sse("message_stop", {"type": "message_stop"}) + yield "data: [DONE]\n\n" + success = True + logger.info("messages stream tool_calls: attempt={}/{} model={}", + attempt + 1, max_retries + 1, model) + else: + # Resolve image attachments and references + for url, img_id in adapter.image_urls: + img_text = await _resolve_image(token, url, img_id) + if isinstance(img_text, str): + chunk = img_text + "\n" + text_buf.append(chunk) + if text_started: + yield _sse("content_block_delta", { + "type": "content_block_delta", + "index": block_index, + "delta": {"type": "text_delta", "text": chunk}, + }) + + references = adapter.references_suffix() + if references: + text_buf.append(references) + if text_started: + yield _sse("content_block_delta", { + "type": "content_block_delta", + "index": block_index, + "delta": {"type": "text_delta", "text": references}, + }) + + # Close open blocks + if think_started and not think_closed: + yield _sse("content_block_stop", { + "type": "content_block_stop", + "index": block_index, + }) + block_index += 1 + + if text_started: + yield _sse("content_block_stop", { + "type": "content_block_stop", + "index": block_index, + }) + + full_text = "".join(text_buf) + full_think = "".join(think_buf) + out_tokens = estimate_tokens(full_text) + if full_think: + out_tokens += estimate_tokens(full_think) + + # 构建 message_delta,注入结构化搜索信源和 annotations + msg_delta: dict = {"stop_reason": "end_turn", "stop_sequence": None} + sources = adapter.search_sources_list() + if sources: + msg_delta["search_sources"] = sources + if collected_annotations: + msg_delta["annotations"] = collected_annotations + yield _sse("message_delta", { + "type": "message_delta", + "delta": msg_delta, + "usage": {"output_tokens": out_tokens}, + }) + yield _sse("message_stop", {"type": "message_stop"}) + yield "data: [DONE]\n\n" + success = True + logger.info( + "messages stream completed: attempt={}/{} model={} text_len={} think_len={} images={}", + attempt + 1, max_retries + 1, model, + len(full_text), len(full_think), len(adapter.image_urls), + ) + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + _retry = True + logger.warning( + "messages stream retry: attempt={}/{} status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8], + ) + else: + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS if success + else _feedback_kind(fail_exc) if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task(_quota_sync(token, selected_mode_id)).add_done_callback(_log_task_exception) + else: + asyncio.create_task(_fail_sync(token, selected_mode_id, fail_exc)).add_done_callback(_log_task_exception) + + if success or not _retry: + return + excluded.append(token) + + if stream: + return _run_stream() + + # ------------------------------------------------------------------------- + # Non-streaming + # ------------------------------------------------------------------------- + excluded: list[str] = [] + token = "" + adapter = StreamAdapter() + + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, + spec, + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() + + try: + try: + ended = False + async for line in _stream_chat( + token = token, + mode_id = ModeId(selected_mode_id), + message = internal_message, + files = files, + timeout_s = timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + for ev in adapter.feed(data): + if ev.kind == "soft_stop": + ended = True + break + if ended: + break + success = True + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + _retry = True + logger.warning( + "messages retry: attempt={}/{} status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8], + ) + else: + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS if success + else _feedback_kind(fail_exc) if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task(_quota_sync(token, selected_mode_id)).add_done_callback(_log_task_exception) + else: + asyncio.create_task(_fail_sync(token, selected_mode_id, fail_exc)).add_done_callback(_log_task_exception) + + if success or not _retry: + break + excluded.append(token) + + full_text = "".join(adapter.text_buf) + + # Resolve image attachments + if adapter.image_urls: + img_texts = await asyncio.gather( + *[_resolve_image(token, url, img_id) for url, img_id in adapter.image_urls], + return_exceptions=True, + ) + for img_text in img_texts: + if isinstance(img_text, BaseException): + logger.warning("messages image resolve failed: error={}", img_text) + elif isinstance(img_text, str): + full_text = (full_text + "\n\n" if full_text else "") + img_text + + references = adapter.references_suffix() + if references: + full_text += references + + full_think = ("".join(adapter.thinking_buf) or "") if emit_think else "" + + in_tokens = estimate_prompt_tokens(internal_message) + out_tokens = estimate_tokens(full_text) + if full_think: + out_tokens += estimate_tokens(full_think) + + # Check for tool calls + if tool_names: + tc_result = parse_tool_calls(full_text, tool_names) + if tc_result.calls: + content: list[dict] = [] + for call in tc_result.calls: + try: + parsed_input = orjson.loads(call.arguments) + except (orjson.JSONDecodeError, ValueError): + parsed_input = {} + content.append({ + "type": "tool_use", + "id": call.call_id, + "name": call.name, + "input": parsed_input, + }) + ct = estimate_tool_call_tokens(tc_result.calls) + logger.info("messages tool_calls: model={} calls={}", model, len(tc_result.calls)) + resp = _build_message_response(msg_id, model, content, "tool_use", in_tokens, ct) + # 注入结构化搜索信源(tool_use 场景) + sources = adapter.search_sources_list() + if sources: + resp["search_sources"] = sources + return resp + + logger.info( + "messages request completed: model={} text_len={} think_len={} images={}", + model, len(full_text), len(full_think), len(adapter.image_urls), + ) + + content = [{"type": "text", "text": full_text}] + anns = adapter.annotations_list() + if anns: + content[0]["annotations"] = anns + resp = _build_message_response(msg_id, model, content, "end_turn", in_tokens, out_tokens) + sources = adapter.search_sources_list() + if sources: + resp["search_sources"] = sources + return resp + + +__all__ = ["create"] diff --git a/app/products/anthropic/router.py b/app/products/anthropic/router.py new file mode 100644 index 0000000000000000000000000000000000000000..34b1f2126a2bfcd7200678ea36d45dcda400c5bb --- /dev/null +++ b/app/products/anthropic/router.py @@ -0,0 +1,128 @@ +"""Anthropic Messages API router (/v1/messages).""" + +from typing import Any + +import orjson +from fastapi import APIRouter, Depends, Request +from fastapi.responses import JSONResponse, StreamingResponse +from pydantic import BaseModel, Field + +from app.platform.auth.middleware import verify_api_key +from app.platform.errors import AppError, ValidationError +from app.platform.logging.logger import logger +from app.control.model import registry as model_registry + + +router = APIRouter(prefix="/v1", dependencies=[Depends(verify_api_key)]) +_TAG_MESSAGES = "Anthropic - Messages" + +_SSE_HEADERS = {"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"} + + +# --------------------------------------------------------------------------- +# Request schema +# --------------------------------------------------------------------------- + +class _ContentBlock(BaseModel): + model_config = {"extra": "allow"} + type: str = "text" + + +class _Message(BaseModel): + model_config = {"extra": "allow"} + role: str + content: Any = "" + + +class MessagesRequest(BaseModel): + model_config = {"extra": "ignore"} + + model: str + messages: list[_Message] + system: Any = None # string or array of content blocks + max_tokens: int | None = None # ignored (Grok doesn't expose this param) + stream: bool | None = None + temperature: float | None = None + top_p: float | None = None + tools: list[dict] | None = None + tool_choice: Any = None + thinking: Any = None # {type:"enabled", budget_tokens:N} — used to enable thinking output + + +# --------------------------------------------------------------------------- +# SSE error wrapper +# --------------------------------------------------------------------------- + +async def _safe_sse_anthropic(stream): + """Wrap an Anthropic SSE stream, converting exceptions to error events.""" + try: + async for chunk in stream: + yield chunk + except AppError as exc: + err = exc.to_dict()["error"] + payload = orjson.dumps({"type": "error", "error": err}).decode() + yield f"event: error\ndata: {payload}\n\n" + yield "data: [DONE]\n\n" + except Exception as exc: + payload = orjson.dumps({ + "type": "error", + "error": {"type": "api_error", "message": str(exc)}, + }).decode() + yield f"event: error\ndata: {payload}\n\n" + yield "data: [DONE]\n\n" + + +# --------------------------------------------------------------------------- +# /v1/messages +# --------------------------------------------------------------------------- + +@router.post("/messages", tags=[_TAG_MESSAGES]) +async def messages_endpoint(req: MessagesRequest): + from app.platform.config.snapshot import get_config + + # Model validation + spec = model_registry.get(req.model) + if spec is None or not spec.enabled: + raise ValidationError( + f"Model {req.model!r} does not exist or you do not have access to it.", + param="model", code="model_not_found", + ) + + if not req.messages: + raise ValidationError("messages cannot be empty", param="messages") + + cfg = get_config() + is_stream = req.stream if req.stream is not None else cfg.get_bool("features.stream", True) + + # thinking flag: enable when request has thinking config or config default + if req.thinking is not None and isinstance(req.thinking, dict): + emit_think = req.thinking.get("type") != "disabled" + else: + emit_think = cfg.get_bool("features.thinking", True) + + # Convert Pydantic models → plain dicts + messages = [m.model_dump() for m in req.messages] + + from .messages import create as messages_create + result = await messages_create( + model = req.model, + messages = messages, + system = req.system, + stream = is_stream, + emit_think = emit_think, + temperature = req.temperature or 0.8, + top_p = req.top_p or 0.95, + tools = req.tools or None, + tool_choice = req.tool_choice, + ) + + if isinstance(result, dict): + return JSONResponse(result) + return StreamingResponse( + _safe_sse_anthropic(result), + media_type = "text/event-stream", + headers = _SSE_HEADERS, + ) + + +__all__ = ["router"] diff --git a/app/products/openai/__init__.py b/app/products/openai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5bc0c2e6d2a80e722fadb85839ca1fe3083e3a6d --- /dev/null +++ b/app/products/openai/__init__.py @@ -0,0 +1,3 @@ +from .router import router + +__all__ = ["router"] diff --git a/app/products/openai/_format.py b/app/products/openai/_format.py new file mode 100644 index 0000000000000000000000000000000000000000..fa0b8592e3463ef6ec60a86876af01476c61e4cc --- /dev/null +++ b/app/products/openai/_format.py @@ -0,0 +1,302 @@ +"""Response formatting utilities — pure functions, no async, no IO. + +Two sections: + - Chat Completions format (make_response_id, make_stream_chunk, …) + - Responses API format (make_resp_id, make_resp_object, …) +""" + +import os +import time +from typing import Any + +import orjson +from app.platform.tokens import estimate_prompt_tokens, estimate_tokens, estimate_tool_call_tokens + + +# --------------------------------------------------------------------------- +# Chat Completions format +# --------------------------------------------------------------------------- + +def make_response_id() -> str: + return f"chatcmpl-{int(time.time() * 1000)}{os.urandom(4).hex()}" + + +def build_usage(prompt_tokens: int, completion_tokens: int, *, reasoning_tokens: int = 0) -> dict: + pt = max(0, prompt_tokens) + ct = max(0, completion_tokens) + rt = max(0, reasoning_tokens) + return { + "prompt_tokens": pt, + "completion_tokens": ct, + "total_tokens": pt + ct, + "prompt_tokens_details": { + "cached_tokens": 0, "text_tokens": pt, + "audio_tokens": 0, "image_tokens": 0, + }, + "completion_tokens_details": { + "text_tokens": ct - rt, "audio_tokens": 0, "reasoning_tokens": rt, + }, + } + + +def make_stream_chunk( + response_id: str, + model: str, + content: str, + *, + index: int = 0, + role: str = "assistant", + is_final: bool = False, + finish_reason: str | None = None, + usage: dict | None = None, + annotations: list[dict] | None = None, +) -> dict: + choice: dict = { + "index": index, + "delta": {"role": role, "content": content}, + } + if is_final: + choice["finish_reason"] = finish_reason or "stop" + # annotations 仅在 final chunk 的 delta 中发送(Vercel AI SDK 读 delta.annotations) + if annotations: + choice["delta"]["annotations"] = annotations + + chunk: dict = { + "id": response_id, + "object": "chat.completion.chunk", + "created": int(time.time()), + "model": model, + "choices": [choice], + } + if usage is not None: + chunk["usage"] = usage + return chunk + + +def make_thinking_chunk( + response_id: str, + model: str, + content: str, + *, + index: int = 0, + role: str = "assistant", +) -> dict: + """Stream chunk carrying reasoning_content (DeepSeek-R1 style thinking delta).""" + return { + "id": response_id, + "object": "chat.completion.chunk", + "created": int(time.time()), + "model": model, + "choices": [{ + "index": index, + "delta": {"role": role, "reasoning_content": content}, + }], + } + + +def make_chat_response( + model: str, + content: str, + *, + prompt_content: Any | None = None, + response_id: str | None = None, + usage: dict | None = None, + reasoning_content: str | None = None, + search_sources: list[dict] | None = None, + annotations: list[dict] | None = None, +) -> dict: + rid = response_id or make_response_id() + pt = estimate_prompt_tokens(prompt_content) + ct = estimate_tokens(content) + rt = estimate_tokens(reasoning_content) if reasoning_content else 0 + ct += rt + + msg: dict = {"role": "assistant", "content": content} + if reasoning_content: + msg["reasoning_content"] = reasoning_content + if annotations: + msg["annotations"] = annotations + resp = { + "id": rid, + "object": "chat.completion", + "created": int(time.time()), + "model": model, + "choices": [{ + "index": 0, + "message": msg, + "finish_reason": "stop", + }], + "usage": usage or build_usage(pt, ct, reasoning_tokens=rt), + } + # search_sources 放在响应根对象(避免 Vercel AI SDK 的 message strict schema 拒绝未知字段) + if search_sources: + resp["search_sources"] = search_sources + return resp + + +# --------------------------------------------------------------------------- +# Responses API format +# --------------------------------------------------------------------------- + +def make_resp_id(prefix: str) -> str: + """Generate a Responses API item ID, e.g. resp_xxx / rs_xxx / msg_xxx / fc_xxx.""" + return f"{prefix}_{int(time.time() * 1000)}{os.urandom(4).hex()}" + + +def build_resp_usage(input_tokens: int, output_tokens: int, reasoning_tokens: int = 0) -> dict: + return { + "input_tokens": max(0, input_tokens), + "output_tokens": max(0, output_tokens), + "total_tokens": max(0, input_tokens + output_tokens), + "output_tokens_details": {"reasoning_tokens": max(0, reasoning_tokens)}, + } + + +def make_resp_object( + response_id: str, + model: str, + status: str, + output: list[dict], + usage: dict | None = None, +) -> dict: + obj: dict = { + "id": response_id, + "object": "response", + "created_at": int(time.time()), + "status": status, + "model": model, + "output": output, + } + if usage is not None: + obj["usage"] = usage + return obj + + +def format_sse(event: str, data: dict) -> str: + """Encode a single Responses API SSE event frame.""" + return f"event: {event}\ndata: {orjson.dumps(data).decode()}\n\n" + + +# --------------------------------------------------------------------------- +# Tool call format (Chat Completions) +# --------------------------------------------------------------------------- + +def make_tool_call_chunk( + response_id: str, + model: str, + index: int, + call_id: str, + name: str, + arguments: str, + *, + is_first: bool = False, +) -> dict: + """A streaming delta chunk carrying a tool_calls item. + + On the first chunk for a given call index set *is_first=True* — this + emits the id/type/name fields. Subsequent chunks carry only the + arguments delta. + """ + if is_first: + tool_call_delta = { + "index": index, + "id": call_id, + "type": "function", + "function": {"name": name, "arguments": arguments}, + } + else: + tool_call_delta = { + "index": index, + "function": {"arguments": arguments}, + } + return { + "id": response_id, + "object": "chat.completion.chunk", + "created": int(time.time()), + "model": model, + "choices": [{ + "index": 0, + "delta": { + "role": "assistant", + "content": None, + "tool_calls": [tool_call_delta], + }, + }], + } + + +def make_tool_call_done_chunk( + response_id: str, + model: str, + *, + usage: dict | None = None, +) -> dict: + """Final streaming chunk with finish_reason='tool_calls'.""" + chunk: dict = { + "id": response_id, + "object": "chat.completion.chunk", + "created": int(time.time()), + "model": model, + "choices": [{ + "index": 0, + "delta": {}, + "finish_reason": "tool_calls", + }], + } + if usage is not None: + chunk["usage"] = usage + return chunk + + +def make_tool_call_response( + model: str, + tool_calls: list, + *, + prompt_content: Any | None = None, + response_id: str | None = None, + usage: dict | None = None, +) -> dict: + """Non-streaming chat completion response carrying tool_calls.""" + from app.dataplane.reverse.protocol.tool_parser import ParsedToolCall + rid = response_id or make_response_id() + tc_list = [ + { + "id": tc.call_id, + "type": "function", + "function": { + "name": tc.name, + "arguments": tc.arguments, + }, + } + for tc in tool_calls + if isinstance(tc, ParsedToolCall) + ] + ct = estimate_tool_call_tokens(tool_calls) + pt = estimate_prompt_tokens(prompt_content) + return { + "id": rid, + "object": "chat.completion", + "created": int(time.time()), + "model": model, + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": None, + "tool_calls": tc_list, + }, + "finish_reason": "tool_calls", + }], + "usage": usage or build_usage(pt, ct), + } + + +__all__ = [ + # chat completions + "make_response_id", "build_usage", + "make_stream_chunk", "make_thinking_chunk", "make_chat_response", + # tool calls + "make_tool_call_chunk", "make_tool_call_done_chunk", "make_tool_call_response", + # responses api + "make_resp_id", "build_resp_usage", "make_resp_object", "format_sse", +] diff --git a/app/products/openai/_tool_sieve.py b/app/products/openai/_tool_sieve.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad2e328997cc5f3b56a6221aeb2a8c6d0f5d64f --- /dev/null +++ b/app/products/openai/_tool_sieve.py @@ -0,0 +1,150 @@ +"""Tool Sieve — streaming tool-call detector and buffer. + +Sits between the raw SSE text stream and the response formatter. +Accumulates chunks, detects when the model starts emitting a +XML block, buffers the entire block, then parses it once complete. + +Usage pattern (streaming path in chat.py): + + sieve = ToolSieve(tool_names) + async for text_chunk in model_stream: + safe_text, tool_calls = sieve.feed(text_chunk) + if safe_text: + yield make_stream_chunk(safe_text) + if tool_calls: + yield make_tool_call_chunk(tool_calls) + break # nothing more to send + + # After the stream ends, flush any remaining buffer + tool_calls = sieve.flush() + if tool_calls: + yield make_tool_call_chunk(tool_calls) +""" + +from __future__ import annotations + +import re + +from app.dataplane.reverse.protocol.tool_parser import ParsedToolCall, parse_tool_calls + + +# --------------------------------------------------------------------------- +# Trigger detection +# --------------------------------------------------------------------------- + +# We start buffering as soon as we see the opening of a tag. +# Using a prefix match so we catch it even before the `>` arrives. +_OPEN_TAG_RE = re.compile(r"]?", re.IGNORECASE) +_CLOSE_TAG = "" +_CLOSE_TAG_RE = re.compile(r"", re.IGNORECASE) + + +# --------------------------------------------------------------------------- +# ToolSieve +# --------------------------------------------------------------------------- + +class ToolSieve: + """Stateful per-request sieve. + + Call :meth:`feed` for every text chunk from the model stream. + Call :meth:`flush` once the stream ends to handle any buffered remainder. + """ + + __slots__ = ("_tool_names", "_buf", "_capturing", "_done") + + def __init__(self, tool_names: list[str]) -> None: + self._tool_names = tool_names + self._buf: str = "" + self._capturing: bool = False + self._done: bool = False # already emitted tool calls once + + # ------------------------------------------------------------------ + # Public + # ------------------------------------------------------------------ + + def feed(self, chunk: str) -> tuple[str, list[ParsedToolCall] | None]: + """Process one text chunk. + + Returns: + (safe_text, tool_calls) + - safe_text: text safe to forward immediately to the client + - tool_calls: non-None (possibly empty list) once a complete + XML block has been parsed; None while still accumulating + """ + if self._done or not chunk: + return chunk if not self._capturing else "", None + + if self._capturing: + return self._feed_capturing(chunk) + else: + return self._feed_scanning(chunk) + + def flush(self) -> list[ParsedToolCall] | None: + """Call after the stream ends. Attempts to parse anything remaining + in the buffer. Returns None if no tool-call syntax was present.""" + if self._done or not self._buf: + return None + self._done = True + result = parse_tool_calls(self._buf, self._tool_names) + self._buf = "" + if result.saw_tool_syntax: + return result.calls + return None + + # ------------------------------------------------------------------ + # Internal + # ------------------------------------------------------------------ + + def _feed_scanning(self, chunk: str) -> tuple[str, list[ParsedToolCall] | None]: + """Not yet in capture mode — look for the opening tag.""" + combined = self._buf + chunk + self._buf = "" + + m = _OPEN_TAG_RE.search(combined) + if m is None: + # No opening tag; safe to forward. Keep the last few chars in + # the buffer in case the tag straddles a chunk boundary. + safe, leftover = _split_at_boundary(combined, " tuple[str, list[ParsedToolCall] | None]: + """In capture mode — accumulate until closing tag.""" + self._buf += chunk + + close_m = _CLOSE_TAG_RE.search(self._buf) + if close_m is None: + # Not complete yet — keep buffering, emit nothing + return "", None + + # Complete block found + xml_block = self._buf[: close_m.end()] + self._buf = "" + self._capturing = False + self._done = True + + result = parse_tool_calls(xml_block, self._tool_names) + return "", result.calls if result.saw_tool_syntax else None + + +# --------------------------------------------------------------------------- +# Helper +# --------------------------------------------------------------------------- + +def _split_at_boundary(text: str, prefix: str) -> tuple[str, str]: + """Split text so that any partial match of *prefix* at the end stays in + the leftover buffer (to be checked again on the next chunk).""" + # Check if any suffix of text could be the start of prefix + for i in range(min(len(prefix) - 1, len(text)), 0, -1): + if text.endswith(prefix[:i]): + return text[: -i], text[-i:] + return text, "" diff --git a/app/products/openai/chat.py b/app/products/openai/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..ce155a865f1b0ab2fa91fcd344a1495b2deb0123 --- /dev/null +++ b/app/products/openai/chat.py @@ -0,0 +1,903 @@ +"""Chat completion service — orchestrates account selection, reverse, streaming.""" + +import asyncio +import base64 +import re +from typing import Any, AsyncGenerator +from urllib.parse import urlparse + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError, ValidationError +from app.platform.runtime.clock import now_s +from app.platform.storage import save_local_image +from app.platform.tokens import ( + estimate_prompt_tokens, + estimate_tokens, + estimate_tool_call_tokens, +) +from app.control.account.runtime import get_refresh_service +from app.control.account.invalid_credentials import feedback_kind_for_error +from app.control.model.registry import resolve as resolve_model +from app.control.model.enums import ModeId +from app.control.account.enums import FeedbackKind +from app.dataplane.account.selector import current_strategy +from app.dataplane.proxy.adapters.headers import build_http_headers +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.session import ( + ResettableSession, + build_session_kwargs, +) +from app.dataplane.reverse.protocol.xai_chat import ( + build_chat_payload, + classify_line, + StreamAdapter, +) +from app.dataplane.reverse.protocol.xai_usage import is_invalid_credentials_error +from app.dataplane.reverse.runtime.endpoint_table import CHAT +from app.dataplane.reverse.transport.asset_upload import upload_from_input +from app.dataplane.reverse.protocol.tool_prompt import ( + build_tool_system_prompt, + extract_tool_names, + inject_into_message, + tool_calls_to_xml, +) +from app.dataplane.reverse.protocol.tool_parser import parse_tool_calls +from ._format import ( + make_response_id, + make_stream_chunk, + make_thinking_chunk, + make_chat_response, + make_tool_call_chunk, + make_tool_call_done_chunk, + make_tool_call_response, + build_usage, +) +from ._tool_sieve import ToolSieve +from app.products._account_selection import reserve_account, selection_max_retries + + +def _to_chat_annotations(anns: list[dict]) -> list[dict]: + """扁平 annotations → Chat Completions 嵌套格式(内层无 type)""" + return ( + [ + { + "type": "url_citation", + "url_citation": { + "url": a["url"], + "title": a["title"], + "start_index": a["start_index"], + "end_index": a["end_index"], + }, + } + for a in anns + ] + if anns + else [] + ) + + +def _log_task_exception(task: "asyncio.Task") -> None: + """Done-callback: log exceptions from fire-and-forget tasks.""" + exc = task.exception() if not task.cancelled() else None + if exc: + logger.warning("background task failed: task={} error={}", task.get_name(), exc) + + +def _upstream_body_excerpt(exc: UpstreamError, *, limit: int = 240) -> str: + details = getattr(exc, "details", {}) + if not isinstance(details, dict): + return "-" + body = str(details.get("body", "") or "").replace("\n", "\\n") + return body[:limit] or "-" + + +def _transport_upstream_error(exc: BaseException, *, context: str) -> UpstreamError: + if isinstance(exc, UpstreamError): + return exc + body = str(exc).replace("\n", "\\n")[:400] + return UpstreamError( + f"{context}: {exc}", + status=502, + body=body, + ) + + +async def _quota_sync(token: str, mode_id: int) -> None: + """Fire-and-forget: fetch real quota after a successful call.""" + try: + if current_strategy() != "quota": + return + svc = get_refresh_service() + if svc: + await svc.refresh_call_async(token, mode_id) + except Exception as exc: + logger.warning( + "chat quota sync failed: token={}... mode_id={} error={}", + token[:10], + mode_id, + exc, + ) + + +async def _fail_sync( + token: str, mode_id: int, exc: BaseException | None = None +) -> None: + """Fire-and-forget: persist failure metadata after a failed call. + + In random mode this helper must not trigger upstream quota probes. It still + records failures so 401 invalidation and local failure accounting continue + to work unchanged. + """ + try: + svc = get_refresh_service() + if svc: + await svc.record_failure_async(token, mode_id, exc) + if ( + current_strategy() == "quota" + and getattr(exc, "status", None) == 429 + ): + result = await svc.refresh_on_demand() + logger.info( + "account on-demand refresh triggered: token={}... mode_id={} refreshed={} failed={} rate_limited={}", + token[:10], + mode_id, + result.refreshed, + result.failed, + result.rate_limited, + ) + except Exception as e: + logger.warning( + "chat fail sync error: token={}... mode_id={} error={}", + token[:10], + mode_id, + e, + ) + + +def _parse_retry_codes(s: str) -> frozenset[int]: + """Parse retry status-code config from either a CSV string or a list.""" + result: set[int] = set() + parts: list[object] + if isinstance(s, str): + parts = [part.strip() for part in s.split(",")] + elif isinstance(s, (list, tuple, set)): + parts = list(s) + else: + return frozenset() + for part in parts: + text = str(part).strip() + if text.isdigit(): + result.add(int(text)) + return frozenset(result) + + +def _configured_retry_codes(cfg) -> frozenset[int]: + """Read retry codes from current config, including legacy array keys.""" + raw = cfg.get("retry.on_codes") + if raw is None: + raw = cfg.get("retry.retry_status_codes", "429,401,503") + return _parse_retry_codes(raw) + + +def _should_retry_upstream(exc: UpstreamError, retry_codes: frozenset[int]) -> bool: + """Return whether this upstream error should switch to another token.""" + return exc.status in retry_codes or is_invalid_credentials_error(exc) + + +def _feedback_kind(exc: BaseException) -> "FeedbackKind": + """Map an upstream exception to the appropriate FeedbackKind.""" + return feedback_kind_for_error(exc) + + +async def _download_image_bytes(token: str, url: str) -> tuple[bytes, str]: + """Download image bytes via the shared asset transport used by /v1/images.""" + from app.dataplane.reverse.protocol.xai_assets import infer_content_type + from app.dataplane.reverse.transport.assets import download_asset + + try: + stream, content_type = await download_asset(token, url) + chunks: list[bytes] = [] + async for chunk in stream: + chunks.append(chunk) + except UpstreamError: + raise + except Exception as exc: + raise UpstreamError(f"Image download failed: {exc}") from exc + return b"".join(chunks), (content_type or infer_content_type(url) or "image/jpeg") + + +def _save_image(raw: bytes, mime: str, image_id: str) -> str: + """Save raw bytes to ``${DATA_DIR}/files/images`` and return the file ID.""" + return save_local_image(raw, mime, image_id) + + +def _is_imagine_public_url(url: str) -> bool: + try: + host = urlparse(url or "").hostname or "" + except Exception: + return False + return host.startswith("imagine-public") + + +async def _resolve_image(token: str, url: str, image_id: str) -> str: + """Return the image embed text for the response body based on image_format config. + + Format values: + grok_url — raw CDN URL (no download) + local_url — download + serve locally, return accessible URL + grok_md — ![image](grok_cdn_url) markdown + local_md — ![image](local_url) markdown + base64 — ![image](data:...) markdown + """ + cfg = get_config() + fmt = _normalize_image_format(cfg.get_str("features.image_format", "grok_url")) + + proxy_imagine_public = ( + _is_imagine_public_url(url) + and cfg.get_bool("features.imagine_public_image_proxy", False) + ) + + # Formats that don't need downloading + if fmt == "grok_url" and not proxy_imagine_public: + return url + if fmt == "grok_md" and not proxy_imagine_public: + return f"![image]({url})" + + # Formats that require downloading + try: + raw, mime = await _download_image_bytes(token, url) + except Exception as exc: + logger.warning( + "chat image download failed: fallback_to=upstream_url error={}", exc + ) + return url + + if fmt == "base64": + b64 = base64.b64encode(raw).decode() + return f"![image](data:{mime};base64,{b64})" + + # local_url / local_md: save to disk and return local path + file_id = await asyncio.to_thread(_save_image, raw, mime, image_id) + app_url = cfg.get_str("app.app_url", "").rstrip("/") + local_url = ( + f"{app_url}/v1/files/image?id={file_id}" + if app_url + else f"/v1/files/image?id={file_id}" + ) + + if fmt in {"grok_url", "local_url"}: + return local_url + return f"![image]({local_url})" # grok_md / local_md + + +def _normalize_image_format(value: str | None) -> str: + fmt = (value or "grok_url").strip().lower() + if fmt not in {"grok_url", "local_url", "grok_md", "local_md", "base64"}: + raise ValidationError( + "image_format must be one of [grok_url, local_url, grok_md, local_md, base64]", + param="features.image_format", + ) + return fmt + + +# 精确匹配 grok2api 注入的 Sources 段落(含标记行),用于多轮对话剥离 +_SOURCES_STRIP_RE = re.compile( + r"(?:^|\r?\n\r?\n)## Sources\r?\n\[grok2api-sources\]: #\r?\n[\s\S]*$" +) + + +def _strip_generated_artifacts(text: str, *, strip_sources: bool = False) -> str: + """Remove generated assistant artifacts before reusing conversation history.""" + if not text or not isinstance(text, str): + return text + if strip_sources: + text = _SOURCES_STRIP_RE.sub("", text) + return text.strip() + + +def _extract_message(messages: list[dict]) -> tuple[str, list[str]]: + """Flatten OpenAI messages into a single prompt string + file attachments.""" + parts: list[str] = [] + files: list[str] = [] + + for msg in messages: + role = msg.get("role", "user") + content = msg.get("content") or "" + tool_calls = msg.get("tool_calls") + + # ── role=tool: tool execution result ───────────────────────────────── + if role == "tool": + tool_call_id = msg.get("tool_call_id", "") + label = ( + f"[tool result for {tool_call_id}]" if tool_call_id else "[tool result]" + ) + text = content.strip() if isinstance(content, str) else "" + if text: + parts.append(f"{label}:\n{text}") + continue + + # ── role=assistant with tool_calls: reconstruct as XML ──────────────── + if role == "assistant" and tool_calls: + xml = tool_calls_to_xml(tool_calls) + # Prepend any accompanying text content (rare but valid) + text = content.strip() if isinstance(content, str) else "" + if text: + parts.append(f"[assistant]: {text}\n{xml}") + else: + parts.append(f"[assistant]:\n{xml}") + continue + + # ── 剥离前轮 assistant 消息中 grok2api 注入的 Sources 段落 ──────────── + if role == "assistant" and isinstance(content, str): + content = _strip_generated_artifacts(content, strip_sources=True) + + # ── normal content handling ─────────────────────────────────────────── + if isinstance(content, str): + cleaned = _strip_generated_artifacts(content.strip()) + if cleaned: + parts.append(f"[{role}]: {cleaned}") + elif isinstance(content, list): + for block in content: + if not isinstance(block, dict): + continue + btype = block.get("type") + if btype == "text": + text = block.get("text") or "" + text = _strip_generated_artifacts( + text.strip(), + strip_sources=(role == "assistant"), + ) + if text: + parts.append(f"[{role}]: {text}") + elif btype == "image_url": + url = (block.get("image_url") or {}).get("url", "") + if url: + files.append(url) + elif btype in ("input_audio", "file"): + inner = block.get(btype) or {} + data = inner.get("data") or inner.get("file_data", "") + if data: + files.append(data) + + return "\n\n".join(parts), files + + +async def _prepare_file_attachments(token: str, file_inputs: list[str]) -> list[str]: + """Upload OpenAI-style multimodal inputs and return Grok chat attachment IDs.""" + attachments: list[str] = [] + for file_input in file_inputs: + if not file_input: + continue + file_id, _file_uri = await upload_from_input(token, file_input) + if file_id: + attachments.append(file_id) + return attachments + + +async def _stream_chat( + token: str, + mode_id: "ModeId", + message: str, + files: list[str], + *, + tool_overrides: dict | None = None, + model_config_override: dict | None = None, + request_overrides: dict | None = None, + timeout_s: float = 120.0, +) -> AsyncGenerator[str, None]: + """Yield raw SSE lines from the Grok app-chat endpoint.""" + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + attachments = await _prepare_file_attachments(token, files) + + payload = build_chat_payload( + message=message, + mode_id=mode_id, + file_attachments=attachments, + tool_overrides=tool_overrides, + model_config_override=model_config_override, + request_overrides=request_overrides, + ) + payload_bytes = orjson.dumps(payload) + + headers = build_http_headers( + token, + content_type="application/json", + origin="https://grok.com", + referer="https://grok.com/", + lease=lease, + ) + session_kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**session_kwargs) as session: + try: + response = await session.post( + CHAT, + headers=headers, + data=payload_bytes, + timeout=timeout_s, + stream=True, + ) + except Exception as exc: + raise _transport_upstream_error( + exc, context="Chat transport failed" + ) from exc + + if response.status_code != 200: + try: + body = response.content.decode("utf-8", "replace")[:400] + except Exception: + body = "" + raise UpstreamError( + f"Chat upstream returned {response.status_code}", + status=response.status_code, + body=body, + ) + + try: + async for line in response.aiter_lines(): + yield line + except Exception as exc: + raise _transport_upstream_error( + exc, context="Chat stream read failed" + ) from exc + + +async def completions( + *, + model: str, + messages: list[dict], + stream: bool | None = None, + emit_think: bool | None = None, + tools: list[dict] | None = None, + tool_choice: Any = None, + temperature: float = 0.8, + top_p: float = 0.95, + request_overrides: dict | None = None, +) -> dict | AsyncGenerator[str, None]: + """Entry point for /v1/chat/completions. + + Returns an async generator for streaming, or a dict for non-streaming. + Supports transparent retry with a different account on configured HTTP + status codes (chat.retry_on_codes) up to chat.max_retries times. + """ + cfg = get_config() + spec = resolve_model(model) + is_stream = stream if stream is not None else cfg.get_bool("features.stream", True) + if emit_think is None: + emit_think = cfg.get_bool("features.thinking", True) + + logger.info( + "chat request accepted: model={} stream={} message_count={}", + model, + is_stream, + len(messages), + ) + + # ── Console API 路由 (console.x.ai/v1/responses) ───────────────────────── + if spec.is_console_chat(): + from .console_chat import completions as console_completions + return await console_completions( + model=model, + messages=messages, + stream=is_stream, + emit_think=emit_think, + temperature=temperature, + top_p=top_p, + ) + # ───────────────────────────────────────────────────────────────────────── + + message, files = _extract_message(messages) + if not message.strip(): + raise UpstreamError("Empty message after extraction", status=400) + + from app.dataplane.account import _directory as _acct_dir + + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + directory = _acct_dir + + max_retries = selection_max_retries() + retry_codes = _configured_retry_codes(cfg) + response_id = make_response_id() + timeout_s = cfg.get_float("chat.timeout", 120.0) + + # ── Tool call setup ─────────────────────────────────────────────────────── + tool_names: list[str] = [] + if tools: + tool_names = extract_tool_names(tools) + tool_prompt = build_tool_system_prompt(tools, tool_choice) + message = inject_into_message(message, tool_prompt) + tool_overrides: dict | None = None + + # ── Streaming path ──────────────────────────────────────────────────────── + if is_stream: + + async def _run_stream() -> AsyncGenerator[str, None]: + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, + spec, + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() + collected_annotations: list[dict] = [] + + try: + try: + ended = False + sieve = ToolSieve(tool_names) + tool_calls_emitted = False + yield ": heartbeat\n\n" + async for line in _stream_chat( + token=token, + mode_id=ModeId(selected_mode_id), + message=message, + files=files, + tool_overrides=tool_overrides, + request_overrides=request_overrides, + timeout_s=timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + events = adapter.feed(data) + for ev in events: + if tool_calls_emitted: + break # already sent [DONE], drop remaining events + if ev.kind == "text": + if tool_names: + safe_text, parsed_calls = sieve.feed(ev.content) + if safe_text: + chunk = make_stream_chunk( + response_id, model, safe_text + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + if parsed_calls is not None: + for i, tc in enumerate(parsed_calls): + chunk = make_tool_call_chunk( + response_id, + model, + i, + tc.call_id, + tc.name, + tc.arguments, + is_first=True, + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + done_chunk = make_tool_call_done_chunk( + response_id, model + ) + yield f"data: {orjson.dumps(done_chunk).decode()}\n\n" + yield "data: [DONE]\n\n" + tool_calls_emitted = True + success = True + logger.info( + "chat stream tool_calls: attempt={}/{} model={} call_count={}", + attempt + 1, + max_retries + 1, + model, + len(parsed_calls), + ) + ended = True + break # stop processing remaining events in this batch + else: + chunk = make_stream_chunk( + response_id, model, ev.content + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + elif ev.kind == "thinking" and emit_think: + chunk = make_thinking_chunk( + response_id, model, ev.content + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + elif ev.kind == "annotation" and ev.annotation_data: + collected_annotations.append(ev.annotation_data) + elif ev.kind == "soft_stop": + ended = True + break + if ended: + break + + if not tool_calls_emitted and tool_names: + # Stream ended — flush sieve for any buffered XML + flushed_calls = sieve.flush() + if flushed_calls: + for i, tc in enumerate(flushed_calls): + chunk = make_tool_call_chunk( + response_id, + model, + i, + tc.call_id, + tc.name, + tc.arguments, + is_first=True, + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + done_chunk = make_tool_call_done_chunk( + response_id, model + ) + # 注入结构化搜索信源(tool_calls 场景) + sources = adapter.search_sources_list() + if sources: + done_chunk["search_sources"] = sources + yield f"data: {orjson.dumps(done_chunk).decode()}\n\n" + yield "data: [DONE]\n\n" + tool_calls_emitted = True + success = True + logger.info( + "chat stream tool_calls (flushed): model={} call_count={}", + model, + len(flushed_calls), + ) + + if not tool_calls_emitted: + for url, img_id in adapter.image_urls: + img_text = await _resolve_image(token, url, img_id) + chunk = make_stream_chunk( + response_id, model, img_text + "\n" + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + references = adapter.references_suffix() + if references: + chunk = make_stream_chunk( + response_id, model, references + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + chat_anns = _to_chat_annotations(collected_annotations) + final = make_stream_chunk( + response_id, + model, + "", + is_final=True, + annotations=chat_anns or None, + ) + # 注入结构化搜索信源到 chunk 根对象(避免 delta strict schema 拒绝) + sources = adapter.search_sources_list() + if sources: + final["search_sources"] = sources + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + success = True + logger.info( + "chat stream completed: attempt={}/{} model={} image_count={}", + attempt + 1, + max_retries + 1, + model, + len(adapter.image_urls), + ) + + except UpstreamError as exc: + fail_exc = exc + if ( + _should_retry_upstream(exc, retry_codes) + and attempt < max_retries + ): + _retry = True + logger.warning( + "chat stream retry scheduled: attempt={}/{} status={} token={}...", + attempt + 1, + max_retries, + exc.status, + token[:8], + ) + else: + logger.warning( + "chat stream upstream failed: attempt={}/{} model={} status={} body={}", + attempt + 1, + max_retries + 1, + model, + exc.status, + _upstream_body_excerpt(exc), + ) + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS + if success + else _feedback_kind(fail_exc) + if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback( + token, kind, selected_mode_id, now_s_val=now_s() + ) + if success: + asyncio.create_task( + _quota_sync(token, selected_mode_id) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, selected_mode_id, fail_exc) + ).add_done_callback(_log_task_exception) + + if success or not _retry: + return + excluded.append(token) + + return _run_stream() + + # ── Non-streaming path ──────────────────────────────────────────────────── + excluded: list[str] = [] + token = "" + adapter = StreamAdapter() + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, + spec, + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() # fresh adapter per attempt + + try: + try: + async for line in _stream_chat( + token=token, + mode_id=ModeId(selected_mode_id), + message=message, + files=files, + tool_overrides=tool_overrides, + request_overrides=request_overrides, + timeout_s=timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + ended = False + for ev in adapter.feed(data): + if ev.kind == "soft_stop": + ended = True + break + if ended: + break + success = True + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + _retry = True + logger.warning( + "chat retry scheduled: attempt={}/{} status={} token={}...", + attempt + 1, + max_retries, + exc.status, + token[:8], + ) + else: + logger.warning( + "chat upstream failed: attempt={}/{} model={} status={} body={}", + attempt + 1, + max_retries + 1, + model, + exc.status, + _upstream_body_excerpt(exc), + ) + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS + if success + else _feedback_kind(fail_exc) + if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task( + _quota_sync(token, selected_mode_id) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, selected_mode_id, fail_exc) + ).add_done_callback(_log_task_exception) + + if success or not _retry: + break + excluded.append(token) + + full_text = "".join(adapter.text_buf) + if adapter.image_urls: + img_texts = await asyncio.gather( + *[_resolve_image(token, url, img_id) for url, img_id in adapter.image_urls], + return_exceptions=True, + ) + for img_text in img_texts: + if isinstance(img_text, BaseException): + logger.warning("chat image resolve failed: error={}", img_text) + elif isinstance(img_text, str): + if full_text: + full_text += "\n\n" + full_text += img_text + + references = adapter.references_suffix() + if references: + full_text += references + + thinking_text = ("".join(adapter.thinking_buf) or None) if emit_think else None + + # ── Tool call detection (non-streaming) ────────────────────────────────── + if tool_names: + parse_result = parse_tool_calls(full_text, tool_names) + if parse_result.calls: + logger.info( + "chat request tool_calls: attempt={}/{} model={} call_count={}", + attempt + 1, + max_retries + 1, + model, + len(parse_result.calls), + ) + pt = estimate_prompt_tokens(message) + resp = make_tool_call_response( + model, + parse_result.calls, + prompt_content=message, + response_id=response_id, + usage=build_usage(pt, estimate_tool_call_tokens(parse_result.calls)), + ) + # 注入结构化搜索信源(tool_calls 场景) + sources = adapter.search_sources_list() + if sources: + resp["search_sources"] = sources + return resp + + logger.info( + "chat request completed: attempt={}/{} model={} text_len={} reasoning_len={} image_count={}", + attempt + 1, + max_retries + 1, + model, + len(full_text), + len(thinking_text or ""), + len(adapter.image_urls), + ) + + pt = estimate_prompt_tokens(message) + ct = estimate_tokens(full_text) + rt = estimate_tokens(thinking_text) if thinking_text else 0 + chat_anns = _to_chat_annotations(adapter.annotations_list()) + return make_chat_response( + model, + full_text, + prompt_content=message, + response_id=response_id, + reasoning_content=thinking_text, + search_sources=adapter.search_sources_list(), + annotations=chat_anns or None, + usage=build_usage(pt, ct + rt, reasoning_tokens=rt), + ) + + +__all__ = [ + "completions", + "_configured_retry_codes", + "_should_retry_upstream", +] diff --git a/app/products/openai/console_chat.py b/app/products/openai/console_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..37238cdc9e1d12a415e96f684b11772a7c52f982 --- /dev/null +++ b/app/products/openai/console_chat.py @@ -0,0 +1,310 @@ +"""Console chat completion service — routes to console.x.ai/v1/responses. + +通过 console.x.ai 端点访问 grok-4.3 / grok-4 等模型, +使用 grok.com SSO token 认证,免费账号可用。 + +与 chat.py 的区别: +- 不走 grok.com 的 app-chat SSE 端点 +- 不消耗 grok.com 配额窗口 +- 响应格式是标准 OpenAI Responses API SSE 事件流 +- thinking 内容以 encrypted_content 形式返回(不可读,不透传) +""" + +import asyncio +from typing import Any, AsyncGenerator + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError +from app.platform.runtime.clock import now_s +from app.platform.tokens import estimate_prompt_tokens, estimate_tokens +from app.control.account.enums import FeedbackKind +from app.control.account.invalid_credentials import feedback_kind_for_error +from app.control.account.runtime import get_refresh_service +from app.control.model.registry import resolve as resolve_model +from app.dataplane.account.selector import current_strategy +from app.dataplane.reverse.protocol.xai_console_chat import ( + build_console_payload, + ConsoleStreamAdapter, + stream_console_chat, +) +from app.products._account_selection import reserve_account, selection_max_retries +from app.products.openai.chat import _configured_retry_codes, _should_retry_upstream +from ._format import ( + make_response_id, + make_stream_chunk, + make_thinking_chunk, + make_chat_response, + build_usage, +) + + +def _log_task_exception(task: "asyncio.Task") -> None: + exc = task.exception() if not task.cancelled() else None + if exc: + logger.warning("background task failed: task={} error={}", task.get_name(), exc) + + +async def _quota_sync(token: str, mode_id: int) -> None: + """Fire-and-forget: 成功调用后持久化配额扣减和 usage_use_count。 + + Console 配额(mode_id=5)为本地管理,不依赖上游 API, + 无论 random/quota 策略都需要执行扣减和窗口重置。 + """ + try: + if current_strategy() != "quota" and mode_id != 5: + return + svc = get_refresh_service() + if svc: + await svc.refresh_call_async(token, mode_id) + except Exception as exc: + logger.warning( + "console quota sync failed: token={}... mode_id={} error={}", + token[:10], + mode_id, + exc, + ) + + +async def _fail_sync(token: str, mode_id: int, exc: BaseException | None = None) -> None: + """Fire-and-forget: 失败后持久化失败计数。""" + try: + svc = get_refresh_service() + if svc: + await svc.record_failure_async(token, mode_id, exc) + except Exception as e: + logger.warning( + "console fail sync error: token={}... mode_id={} error={}", + token[:10], + mode_id, + e, + ) + + +def _reasoning_effort_from_emit_think(emit_think: bool | None) -> str: + """将 emit_think 标志映射到 console API 的 reasoning effort。""" + if emit_think is False: + return "none" + return "low" # 默认 low,节省 token + + +async def completions( + *, + model: str, + messages: list[dict], + stream: bool = True, + emit_think: bool | None = None, + temperature: float = 0.7, + top_p: float = 0.95, +) -> dict | AsyncGenerator[str, None]: + """Entry point for console.x.ai chat completions. + + Returns an async generator for streaming, or a dict for non-streaming. + """ + cfg = get_config() + spec = resolve_model(model) + effort = _reasoning_effort_from_emit_think(emit_think) + timeout_s = cfg.get_float("chat.timeout", 120.0) + max_retries = selection_max_retries() + retry_codes = _configured_retry_codes(cfg) + response_id = make_response_id() + + logger.info( + "console chat request: model={} stream={} messages={}", + model, stream, len(messages), + ) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + directory = _acct_dir + + # ── Streaming path ──────────────────────────────────────────────────────── + if stream: + async def _run_stream() -> AsyncGenerator[str, None]: + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, + spec, + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + fail_exc: BaseException | None = None + _retry = False + adapter = ConsoleStreamAdapter() + + try: + payload = build_console_payload( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=effort, + stream=True, + ) + + try: + yield ": heartbeat\n\n" + async for event_type, data in stream_console_chat( + token, payload, timeout_s=timeout_s + ): + tokens = adapter.feed(event_type, data) + for tok in tokens: + chunk = make_stream_chunk(response_id, model, tok) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + # 流结束,发送 final chunk + usage_data = adapter.usage + prompt_tokens = ( + usage_data.get("input_tokens", 0) if usage_data else + estimate_prompt_tokens(messages) + ) + completion_tokens = ( + usage_data.get("output_tokens", 0) if usage_data else + estimate_tokens(adapter.full_text) + ) + usage = build_usage(prompt_tokens, completion_tokens) + final = make_stream_chunk( + response_id, model, "", is_final=True + ) + final["usage"] = usage + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + success = True + logger.info( + "console chat stream completed: attempt={}/{} model={} tokens={}", + attempt + 1, max_retries + 1, model, + (usage_data or {}).get("total_tokens", "?"), + ) + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + _retry = True + logger.warning( + "console chat retry: attempt={}/{} status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8], + ) + else: + logger.warning( + "console chat upstream failed: model={} status={} attempt={}/{}", + model, exc.status, attempt + 1, max_retries + 1, + ) + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS if success + else feedback_kind_for_error(fail_exc) if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task( + _quota_sync(token, selected_mode_id) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, selected_mode_id, fail_exc) + ).add_done_callback(_log_task_exception) + + if success or not _retry: + return + excluded.append(token) + + return _run_stream() + + # ── Non-streaming path ──────────────────────────────────────────────────── + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, + spec, + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + fail_exc: BaseException | None = None + adapter = ConsoleStreamAdapter() + + try: + payload = build_console_payload( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=effort, + stream=True, # 始终用流式,非流式在本地聚合 + ) + + try: + async for event_type, data in stream_console_chat( + token, payload, timeout_s=timeout_s + ): + adapter.feed(event_type, data) + + usage_data = adapter.usage + prompt_tokens = ( + usage_data.get("input_tokens", 0) if usage_data else + estimate_prompt_tokens(messages) + ) + completion_tokens = ( + usage_data.get("output_tokens", 0) if usage_data else + estimate_tokens(adapter.full_text) + ) + usage = build_usage(prompt_tokens, completion_tokens) + result = make_chat_response( + model, adapter.full_text, response_id=response_id, usage=usage + ) + success = True + logger.info( + "console chat non-stream completed: model={} tokens={}", + model, (usage_data or {}).get("total_tokens", "?"), + ) + return result + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + logger.warning( + "console chat non-stream retry: attempt={}/{} status={}", + attempt + 1, max_retries, exc.status, + ) + excluded.append(token) + continue + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS if success + else feedback_kind_for_error(fail_exc) if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task( + _quota_sync(token, selected_mode_id) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, selected_mode_id, fail_exc) + ).add_done_callback(_log_task_exception) + + raise RateLimitError("No available accounts after retries") + + +__all__ = ["completions"] diff --git a/app/products/openai/console_responses.py b/app/products/openai/console_responses.py new file mode 100644 index 0000000000000000000000000000000000000000..24e9d66622e1fb6bfb1816447eedaaa4c0fd5616 --- /dev/null +++ b/app/products/openai/console_responses.py @@ -0,0 +1,388 @@ +"""Console Responses API handler — /v1/responses for console.x.ai models. + +将 console.x.ai 上游的 Responses API SSE 事件流转换为 OpenAI Responses API 格式输出。 +由于上游本身就是 Responses API 格式,这里主要做: +1. 账号选择 + 重试 +2. 过滤/转换 SSE 事件(去掉 encrypted reasoning,保留文本 delta) +3. 包装成标准 Responses API 输出 +""" + +import asyncio +from typing import Any, AsyncGenerator + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError +from app.platform.runtime.clock import now_s +from app.platform.tokens import estimate_prompt_tokens, estimate_tokens +from app.control.account.enums import FeedbackKind +from app.control.account.invalid_credentials import feedback_kind_for_error +from app.control.account.runtime import get_refresh_service +from app.control.model.registry import resolve as resolve_model +from app.dataplane.account.selector import current_strategy +from app.dataplane.reverse.protocol.xai_console_chat import ( + build_console_payload, + ConsoleStreamAdapter, + stream_console_chat, +) +from app.products._account_selection import reserve_account, selection_max_retries +from app.products.openai.chat import _configured_retry_codes, _should_retry_upstream +from ._format import ( + make_resp_id, + make_resp_object, + build_resp_usage, + format_sse, +) + + +def _log_task_exception(task: "asyncio.Task") -> None: + exc = task.exception() if not task.cancelled() else None + if exc: + logger.warning("background task failed: task={} error={}", task.get_name(), exc) + + +async def _quota_sync(token: str, mode_id: int) -> None: + """Fire-and-forget: 成功调用后持久化配额扣减和 usage_use_count。 + + Console 配额(mode_id=5)为本地管理,不依赖上游 API, + 无论 random/quota 策略都需要执行扣减和窗口重置。 + """ + try: + if current_strategy() != "quota" and mode_id != 5: + return + svc = get_refresh_service() + if svc: + await svc.refresh_call_async(token, mode_id) + except Exception as exc: + logger.warning( + "console responses quota sync failed: token={}... mode_id={} error={}", + token[:10], + mode_id, + exc, + ) + + +async def _fail_sync(token: str, mode_id: int, exc: BaseException | None = None) -> None: + """Fire-and-forget: 失败后持久化失败计数。""" + try: + svc = get_refresh_service() + if svc: + await svc.record_failure_async(token, mode_id, exc) + except Exception as e: + logger.warning( + "console responses fail sync error: token={}... mode_id={} error={}", + token[:10], + mode_id, + e, + ) + + +async def create( + *, + model: str, + messages: list[dict], + stream: bool, + emit_think: bool, + temperature: float, + top_p: float, + response_id: str, + reasoning_id: str, + message_id: str, +) -> dict | AsyncGenerator[str, None]: + """Console models /v1/responses handler.""" + + cfg = get_config() + spec = resolve_model(model) + timeout_s = cfg.get_float("chat.timeout", 120.0) + max_retries = selection_max_retries() + retry_codes = _configured_retry_codes(cfg) + + # reasoning effort 映射 + effort = "low" if emit_think else "none" + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + directory = _acct_dir + + # ── Streaming ───────────────────────────────────────────────────────────── + if stream: + async def _run_stream() -> AsyncGenerator[str, None]: + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, spec, now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + fail_exc: BaseException | None = None + _retry = False + adapter = ConsoleStreamAdapter() + text_buf: list[str] = [] + + try: + payload = build_console_payload( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=effort, + stream=True, + ) + + try: + # response.created + yield format_sse("response.created", { + "type": "response.created", + "response": make_resp_object(response_id, model, "in_progress", []), + }) + + # response.in_progress + yield format_sse("response.in_progress", { + "type": "response.in_progress", + "response": make_resp_object(response_id, model, "in_progress", []), + }) + + # output_item.added (message) + yield format_sse("response.output_item.added", { + "type": "response.output_item.added", + "output_index": 0, + "item": { + "id": message_id, + "type": "message", + "role": "assistant", + "status": "in_progress", + "content": [], + }, + }) + + # content_part.added + yield format_sse("response.content_part.added", { + "type": "response.content_part.added", + "item_id": message_id, + "output_index": 0, + "content_index": 0, + "part": {"type": "output_text", "text": "", "annotations": []}, + }) + + event_count = 0 + yield ": heartbeat\n\n" + async for event_type, data in stream_console_chat( + token, payload, timeout_s=timeout_s + ): + event_count += 1 + tokens = adapter.feed(event_type, data) + for tok in tokens: + text_buf.append(tok) + yield format_sse("response.output_text.delta", { + "type": "response.output_text.delta", + "item_id": message_id, + "output_index": 0, + "content_index": 0, + "delta": tok, + }) + + logger.info( + "console responses stream raw: events={} text_tokens={} adapter_text_len={}", + event_count, len(text_buf), len(adapter.full_text), + ) + + # 流结束 + full_text = "".join(text_buf) + + # output_text.done + yield format_sse("response.output_text.done", { + "type": "response.output_text.done", + "item_id": message_id, + "output_index": 0, + "content_index": 0, + "text": full_text, + }) + + # content_part.done + yield format_sse("response.content_part.done", { + "type": "response.content_part.done", + "item_id": message_id, + "output_index": 0, + "content_index": 0, + "part": {"type": "output_text", "text": full_text, "annotations": []}, + }) + + # output_item.done + yield format_sse("response.output_item.done", { + "type": "response.output_item.done", + "output_index": 0, + "item": { + "id": message_id, + "type": "message", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": full_text}], + }, + }) + + # usage + usage_data = adapter.usage + input_tokens = ( + usage_data.get("input_tokens", 0) if usage_data + else estimate_prompt_tokens(messages) + ) + output_tokens = ( + usage_data.get("output_tokens", 0) if usage_data + else estimate_tokens(full_text) + ) + + # response.completed + output_items = [{ + "id": message_id, + "type": "message", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": full_text}], + }] + yield format_sse("response.completed", { + "type": "response.completed", + "response": make_resp_object( + response_id, model, "completed", output_items, + usage=build_resp_usage(input_tokens, output_tokens), + ), + }) + yield "data: [DONE]\n\n" + success = True + logger.info( + "console responses stream completed: model={} text_len={} attempt={}/{}", + model, len(full_text), attempt + 1, max_retries + 1, + ) + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + _retry = True + logger.warning( + "console responses retry: attempt={}/{} status={}", + attempt + 1, max_retries, exc.status, + ) + else: + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS if success + else feedback_kind_for_error(fail_exc) if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task( + _quota_sync(token, selected_mode_id) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, selected_mode_id, fail_exc) + ).add_done_callback(_log_task_exception) + + if success or not _retry: + return + excluded.append(token) + + return _run_stream() + + # ── Non-streaming ───────────────────────────────────────────────────────── + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, spec, now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + fail_exc: BaseException | None = None + adapter = ConsoleStreamAdapter() + + try: + payload = build_console_payload( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=effort, + stream=True, + ) + + try: + async for event_type, data in stream_console_chat( + token, payload, timeout_s=timeout_s + ): + adapter.feed(event_type, data) + + full_text = adapter.full_text + usage_data = adapter.usage + input_tokens = ( + usage_data.get("input_tokens", 0) if usage_data + else estimate_prompt_tokens(messages) + ) + output_tokens = ( + usage_data.get("output_tokens", 0) if usage_data + else estimate_tokens(full_text) + ) + + output_items = [{ + "id": message_id, + "type": "message", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": full_text}], + }] + result = make_resp_object( + response_id, model, "completed", output_items, + usage=build_resp_usage(input_tokens, output_tokens), + ) + success = True + logger.info( + "console responses non-stream completed: model={} text_len={}", + model, len(full_text), + ) + return result + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + logger.warning( + "console responses non-stream retry: attempt={}/{} status={}", + attempt + 1, max_retries, exc.status, + ) + excluded.append(token) + continue + raise + + finally: + await directory.release(acct) + kind = ( + FeedbackKind.SUCCESS if success + else feedback_kind_for_error(fail_exc) if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task( + _quota_sync(token, selected_mode_id) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, selected_mode_id, fail_exc) + ).add_done_callback(_log_task_exception) + + raise RateLimitError("No available accounts after retries") + + +__all__ = ["create"] diff --git a/app/products/openai/images.py b/app/products/openai/images.py new file mode 100644 index 0000000000000000000000000000000000000000..652767ff2e89ff4ef7a6628dfafe566e7cd356c7 --- /dev/null +++ b/app/products/openai/images.py @@ -0,0 +1,1294 @@ +"""Image services — generation (/v1/images/generations) and editing (/v1/images/edits).""" + +import asyncio +import base64 +import binascii +import hashlib +import re +import time +from dataclasses import dataclass +from typing import Any, AsyncGenerator, Awaitable, Callable +from urllib.parse import urlparse + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError, ValidationError +from app.platform.runtime.clock import now_s +from app.platform.storage import save_local_image +from app.control.model.registry import resolve as resolve_model +from app.control.model.enums import ModeId +from app.control.model.spec import ModelSpec +from app.control.account.enums import FeedbackKind +from app.dataplane.reverse.transport.imagine_ws import stream_images +from app.dataplane.reverse.protocol.xai_chat import ( + StreamAdapter, + build_chat_payload, + classify_line, + raise_for_stream_error, +) +from app.dataplane.reverse.protocol.xai_assets import infer_content_type, resolve_asset_reference, resolve_download_url +from app.dataplane.reverse.protocol.xai_image_edit import ( + IMAGE_POST_MEDIA_TYPE, + build_image_edit_payload, + extract_model_response_file_attachments, + extract_model_response_urls, + extract_streaming_response, +) +from app.dataplane.reverse.transport.assets import download_asset +from app.dataplane.reverse.transport.asset_upload import ( + resolve_uploaded_asset_reference, + upload_from_input, +) +from app.dataplane.reverse.transport.media import create_media_post +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.headers import build_http_headers, build_sso_cookie +from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs +from app.dataplane.reverse.runtime.endpoint_table import CHAT +from ._format import ( + make_chat_response, + make_response_id, + make_stream_chunk, + make_thinking_chunk, +) +from .chat import ( + _configured_retry_codes, + _fail_sync, + _feedback_kind, + _log_task_exception, + _quota_sync, + _should_retry_upstream, +) +from app.products._account_selection import selection_max_retries + +_X_USER_ID_RE = re.compile(r"(?:^|;\s*)x-userid=([^;]+)") + + +# --------------------------------------------------------------------------- +# Aspect-ratio helpers (generation) +# --------------------------------------------------------------------------- + +_RATIO_MAP: dict[str, str] = { + "1280x720": "16:9", "16:9": "16:9", + "720x1280": "9:16", "9:16": "9:16", + "1792x1024": "3:2", "3:2": "3:2", + "1024x1792": "2:3", "2:3": "2:3", + "1024x1024": "1:1", "1:1": "1:1", +} + + +def resolve_aspect_ratio(size: str) -> str: + return _RATIO_MAP.get(size, "2:3") + + +@dataclass(slots=True) +class _ImageOutput: + api_value: str + markdown_value: str + + +def _clamp_progress(value: int) -> int: + return max(0, min(100, int(value))) + + +def _compute_progress_percent(progress_map: dict[object, int], total: int) -> int: + if total <= 0: + return 100 + if not progress_map: + return 0 + values = sorted((_clamp_progress(value) for value in progress_map.values()), reverse=True)[:total] + return _clamp_progress(sum(values) // total) + + +def _progress_reason(label: str, progress: int, *, completed: int | None = None, total: int | None = None) -> str: + reason = f"{label}正在生成 {progress}%" + if completed is not None and total is not None and total > 0: + reason += f" ({completed}/{total})" + return reason + + +def _progress_reason_delta( + label: str, + progress: int, + *, + completed: int | None = None, + total: int | None = None, +) -> str: + return _progress_reason( + label, + progress, + completed=completed, + total=total, + ) + "\n" + + +def _append_reason_update( + updates: list[str], + label: str, + progress: int, + *, + completed: int | None = None, + total: int | None = None, +) -> None: + reason = _progress_reason(label, progress, completed=completed, total=total) + if not updates or updates[-1] != reason: + updates.append(reason) + + +def _completed_items(progress_map: dict[object, int]) -> int: + return sum(1 for value in progress_map.values() if _clamp_progress(value) >= 100) + + +async def _lite_progress_updates( + *, + idx: int, + progress: int, + total: int, + progress_map: dict[int, int], + updates: list[str], + enabled: bool, +) -> None: + progress_map[idx] = _clamp_progress(progress) + if enabled: + _append_reason_update( + updates, + "图片", + _compute_progress_percent(progress_map, total), + completed=_completed_items(progress_map), + total=total, + ) + + +def _normalize_response_format(response_format: str) -> str: + fmt = (response_format or "url").strip().lower() + if fmt not in {"url", "b64_json"}: + raise ValidationError( + "response_format must be one of ['url', 'b64_json']", + param="response_format", + ) + return fmt + + +def _app_url() -> str: + return get_config().get_str("app.app_url", "").rstrip("/") + + +def _local_image_url(file_id: str) -> str: + app_url = _app_url() + return f"{app_url}/v1/files/image?id={file_id}" + + +def _extract_image_file_id(url: str) -> str: + parts = [part for part in url.split("/") if part] + for part in reversed(parts): + stem = part.split(".", 1)[0] + if stem and stem not in {"image", "original", "thumbnail"}: + return stem + return hashlib.sha1(url.encode("utf-8")).hexdigest()[:32] + + +def _is_imagine_public_url(url: str) -> bool: + try: + host = urlparse(url or "").hostname or "" + except Exception: + return False + return host.startswith("imagine-public") + + +def _save_image(raw: bytes, mime: str, file_id: str) -> str: + return save_local_image(raw, mime, file_id) + + +async def _download_image_bytes(token: str, url: str) -> tuple[bytes, str]: + try: + stream, content_type = await download_asset(token, url) + chunks: list[bytes] = [] + async for chunk in stream: + chunks.append(chunk) + except UpstreamError: + raise + except Exception as exc: + raise UpstreamError(f"Image download failed: {exc}") from exc + return b"".join(chunks), (content_type or infer_content_type(url) or "image/jpeg") + + +async def _resolve_image_output( + *, + token: str, + url: str, + response_format: str, + blob_b64: str | None = None, +) -> _ImageOutput: + fmt = _normalize_response_format(response_format) + cfg = get_config() + if ( + fmt == "url" + and _is_imagine_public_url(url) + and not cfg.get_bool("features.imagine_public_image_proxy", False) + ): + return _ImageOutput(api_value=url, markdown_value=f"![image]({url})") + if fmt == "url" and not _app_url(): + return _ImageOutput(api_value=url, markdown_value=f"![image]({url})") + + mime = infer_content_type(url) or "image/jpeg" + if blob_b64 is not None: + try: + raw = base64.b64decode(blob_b64) + except (ValueError, TypeError, binascii.Error) as exc: + raise UpstreamError(f"Invalid upstream image blob: {exc}") from exc + else: + raw, mime = await _download_image_bytes(token, url) + + if fmt == "b64_json": + b64 = blob_b64 or base64.b64encode(raw).decode() + data_uri = f"data:{mime};base64,{b64}" + return _ImageOutput(api_value=b64, markdown_value=f"![image]({data_uri})") + + file_id = await asyncio.to_thread( + _save_image, + raw, + mime, + _extract_image_file_id(url), + ) + local_url = _local_image_url(file_id) + return _ImageOutput(api_value=local_url, markdown_value=f"![image]({local_url})") + + +def _output_content(image: _ImageOutput, *, chat_format: bool) -> str: + return image.markdown_value if chat_format else image.api_value + + +# --------------------------------------------------------------------------- +# Image generation +# --------------------------------------------------------------------------- + +# Models that use the chat endpoint for image generation (no WS, no params). +_LITE_IMAGE_MODELS = frozenset({"grok-imagine-image-lite"}) +# WS models that use quality mode (enable_pro=True). +_PRO_IMAGE_MODELS = frozenset({"grok-imagine-image-pro"}) + + +async def generate( + *, + model: str, + prompt: str, + n: int = 1, + size: str = "1024x1024", + response_format: str = "url", + stream: bool = False, + chat_format: bool = False, +) -> dict | AsyncGenerator[str, None]: + """Generate images. + + Routes to the appropriate backend based on model: + grok-imagine-image-lite → chat endpoint (fast quota, no aspect-ratio control) + grok-imagine-image → WebSocket speed mode (super+) + grok-imagine-image-pro → WebSocket quality mode (super+) + + Returns: + Non-streaming: OpenAI images.generations dict, or chat dict if chat_format=True. + Streaming: async generator of SSE strings. + """ + cfg = get_config() + spec = resolve_model(model) + aspect_ratio = resolve_aspect_ratio(size) + enable_nsfw = cfg.get_bool("features.enable_nsfw", True) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + # Lite model: chat-based generation (no WS, ignores aspect_ratio). + if model in _LITE_IMAGE_MODELS: + return await _generate_lite( + spec = spec, + prompt = prompt, + n = n, + response_format = response_format, + stream = stream, + chat_format = chat_format, + ) + + acct = await _acct_dir.reserve_any( + spec.pool_candidates(), + now_s_override=now_s(), + ) + if acct is None: + raise RateLimitError("No available accounts for image generation") + + token = acct.token + response_id = make_response_id() + enable_pro = model in _PRO_IMAGE_MODELS + _ws_mode_id = int(spec.mode_id) + + if stream: + async def _sse_stream() -> AsyncGenerator[str, None]: + success = False + fail_exc: BaseException | None = None + progress_map: dict[object, int] = {} + completed_ids: set[object] = set() + last_progress = -1 + try: + async for ev in stream_images( + token, prompt, + aspect_ratio = aspect_ratio, + n = n, + enable_nsfw = enable_nsfw, + enable_pro = enable_pro, + ): + ev_type = ev.get("type") + if ev_type == "error": + raise UpstreamError(f"Image error: {ev.get('error', '')}") + if ev_type == "moderated": + logger.warning("image generation slot moderated: image_id={}", ev.get("image_id", "")[:8]) + continue + if ev_type == "progress": + key = ev.get("image_id") or f"progress-{len(progress_map)}" + progress_map[key] = _clamp_progress(ev.get("progress") or 0) + aggregate = _compute_progress_percent(progress_map, n) + if chat_format and aggregate > last_progress: + last_progress = aggregate + reason = _progress_reason( + "图片", + aggregate, + completed=len(completed_ids), + total=n, + ) + chunk = make_thinking_chunk(response_id, model, reason + "\n") + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + continue + if not ev.get("is_final"): + continue + key = ev.get("image_id") or f"final-{len(completed_ids)}" + progress_map[key] = 100 + completed_ids.add(key) + aggregate = _compute_progress_percent(progress_map, n) + if chat_format and aggregate > last_progress: + last_progress = aggregate + reason = _progress_reason("图片", aggregate, completed=len(completed_ids), total=n) + chunk = make_thinking_chunk(response_id, model, reason + "\n") + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + image = await _resolve_image_output( + token=token, + url=ev.get("url", ""), + response_format=response_format, + blob_b64=ev.get("blob") or None, + ) + content = _output_content(image, chat_format=chat_format) + chunk = make_stream_chunk(response_id, model, content) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + final = make_stream_chunk(response_id, model, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + success = True + except BaseException as exc: + fail_exc = exc + raise + finally: + await _acct_dir.release(acct) + # WS image gen has its own upstream rate limiting — skip quota tracking. + # Still propagate auth failures so bad accounts get marked expired. + if not success and fail_exc is not None: + kind = _feedback_kind(fail_exc) + if kind in (FeedbackKind.UNAUTHORIZED, FeedbackKind.FORBIDDEN): + await _acct_dir.feedback(token, kind, _ws_mode_id) + + return _sse_stream() + + # Non-streaming: collect all final images. + finals: list[_ImageOutput] = [] + reasoning_updates: list[str] = [] + progress_map: dict[object, int] = {} + completed_ids: set[object] = set() + success = False + fail_exc: BaseException | None = None + try: + async for ev in stream_images( + token, prompt, + aspect_ratio = aspect_ratio, + n = n, + enable_nsfw = enable_nsfw, + enable_pro = enable_pro, + ): + ev_type = ev.get("type") + if ev_type == "error": + raise UpstreamError(f"Image generation failed: {ev.get('error', 'unknown')}") + if ev_type == "moderated": + logger.warning("image generation slot moderated: image_id={}", ev.get("image_id", "")[:8]) + continue + if ev_type == "progress": + key = ev.get("image_id") or f"progress-{len(progress_map)}" + progress_map[key] = _clamp_progress(ev.get("progress") or 0) + if chat_format: + _append_reason_update( + reasoning_updates, + "图片", + _compute_progress_percent(progress_map, n), + completed=len(completed_ids), + total=n, + ) + continue + if ev.get("is_final"): + key = ev.get("image_id") or f"final-{len(completed_ids)}" + progress_map[key] = 100 + completed_ids.add(key) + if chat_format: + _append_reason_update( + reasoning_updates, + "图片", + _compute_progress_percent(progress_map, n), + completed=len(completed_ids), + total=n, + ) + image = await _resolve_image_output( + token=token, + url=ev.get("url", ""), + response_format=response_format, + blob_b64=ev.get("blob") or None, + ) + finals.append(image) + success = True + except BaseException as exc: + fail_exc = exc + raise + finally: + await _acct_dir.release(acct) + # WS image gen has its own upstream rate limiting — skip quota tracking. + if not success and fail_exc is not None: + kind = _feedback_kind(fail_exc) + if kind in (FeedbackKind.UNAUTHORIZED, FeedbackKind.FORBIDDEN): + await _acct_dir.feedback(token, kind, _ws_mode_id) + + if chat_format: + content = "\n\n".join(image.markdown_value for image in finals) + reasoning = "\n".join(reasoning_updates) if reasoning_updates else None + return make_chat_response( + model, + content, + prompt_content=prompt, + response_id=response_id, + reasoning_content=reasoning, + ) + + data = [ + {"b64_json": image.api_value} + if _normalize_response_format(response_format) == "b64_json" + else {"url": image.api_value} + for image in finals + ] + return {"created": int(time.time()), "data": data} + + +# --------------------------------------------------------------------------- +# Lite image generation (chat-based, no WS, no aspect-ratio control) +# --------------------------------------------------------------------------- + +async def _generate_lite( + *, + spec: ModelSpec, + prompt: str, + n: int, + response_format: str, + stream: bool, + chat_format: bool, +) -> dict | AsyncGenerator[str, None]: + """Generate images via the chat endpoint (Aurora model path). + + Does not support aspect ratio or quality control. It uses fast quota. + """ + response_id = make_response_id() + cfg = get_config() + timeout_s = cfg.get_float("chat.timeout", 120.0) + logger.debug("lite image fan-out started: request_count={} mode={}", n, spec.mode_id.name.lower()) + + if stream: + async def _sse_stream() -> AsyncGenerator[str, None]: + progress_map: dict[int, int] = {} + last_progress = -1 + queue: asyncio.Queue[tuple[int, int]] = asyncio.Queue() + + async def _progress(idx: int, progress: int) -> None: + progress_map[idx] = _clamp_progress(progress) + await queue.put(( + _compute_progress_percent(progress_map, n), + _completed_items(progress_map), + )) + + task = asyncio.create_task( + _run_lite_batch( + spec=spec, + prompt=prompt, + n=n, + timeout_s=timeout_s, + response_format=response_format, + progress_cb=_progress, + ) + ) + + while not task.done() or not queue.empty(): + try: + aggregate, completed = await asyncio.wait_for(queue.get(), timeout=0.1) + except asyncio.TimeoutError: + continue + if chat_format and aggregate > last_progress: + last_progress = aggregate + chunk = make_thinking_chunk( + response_id, + spec.model_name, + _progress_reason_delta( + "图片", + aggregate, + completed=completed, + total=n, + ), + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + images = await task + for image in images: + chunk = make_stream_chunk( + response_id, + spec.model_name, + _output_content(image, chat_format=chat_format), + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + final = make_stream_chunk(response_id, spec.model_name, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + + return _sse_stream() + + reasoning_updates: list[str] = [] + progress_map: dict[int, int] = {} + images = await _run_lite_batch( + spec=spec, + prompt=prompt, + n=n, + timeout_s=timeout_s, + response_format=response_format, + progress_cb=lambda idx, progress: _lite_progress_updates( + idx=idx, + progress=progress, + total=n, + progress_map=progress_map, + updates=reasoning_updates, + enabled=chat_format, + ), + ) + if chat_format: + content = "\n\n".join(image.markdown_value for image in images) + reasoning = "\n".join(reasoning_updates) if reasoning_updates else None + return make_chat_response( + spec.model_name, + content, + prompt_content=prompt, + response_id=response_id, + reasoning_content=reasoning, + ) + + return { + "created": int(time.time()), + "data": [ + {"b64_json": image.api_value} + if _normalize_response_format(response_format) == "b64_json" + else {"url": image.api_value} + for image in images + ], + } + + +# --------------------------------------------------------------------------- +# Image editing +# --------------------------------------------------------------------------- + +_EDIT_MAX_REFERENCES = 7 +_EDIT_DEFAULT_SIZE = "1024x1024" +_EDIT_MAX_N = 2 +_EDIT_MAX_ATTEMPTS = 2 +_EDIT_IMAGE_PLACEHOLDER_RE = re.compile(r"@IMAGE(\d+)\b", re.IGNORECASE) + + +@dataclass(slots=True) +class _EditReference: + file_id: str + content_url: str + + +def _normalize_edit_inputs(image_inputs: list[str]) -> list[str]: + """Validate and normalize image-edit reference inputs.""" + cleaned = [item.strip() for item in image_inputs if isinstance(item, str) and item.strip()] + if not cleaned: + raise ValidationError("Image edit requires at least one image_url content block", param="messages") + return cleaned[-_EDIT_MAX_REFERENCES:] + + +def _normalize_edit_size(size: str) -> str: + """Validate the only upstream-backed image-edit size.""" + normalized = (size or _EDIT_DEFAULT_SIZE).strip().lower() + if normalized != _EDIT_DEFAULT_SIZE: + raise ValidationError( + f"image edit currently only supports size {_EDIT_DEFAULT_SIZE!r}", + param="size", + ) + return _EDIT_DEFAULT_SIZE + + +async def _prepare_edit_reference( + token: str, image_input: str, index: int +) -> _EditReference: + """Upload one edit reference and resolve it to the upstream content URL.""" + try: + file_id, file_uri = await upload_from_input(token, image_input) + return _EditReference( + file_id=file_id, + content_url=resolve_uploaded_asset_reference(token, file_id, file_uri), + ) + except ValidationError as exc: + raise ValidationError(exc.message, param=f"image.{index}") from exc + except UpstreamError as exc: + raise UpstreamError( + f"Image edit reference {index + 1} upload failed: {exc.message}", + status=exc.status, + body=exc.details.get("body", ""), + ) from exc + except Exception as exc: + raise UpstreamError(f"Image edit reference {index + 1} upload failed: {exc}") from exc + + +async def _prepare_edit_references( + token: str, image_inputs: list[str] +) -> list[_EditReference]: + """Upload edit references concurrently and preserve caller order.""" + results: list[_EditReference | None] = [None] * len(image_inputs) + + async def _runner(index: int, image_input: str) -> None: + results[index] = await _prepare_edit_reference(token, image_input, index) + + async with asyncio.TaskGroup() as tg: + for index, image_input in enumerate(image_inputs): + tg.create_task(_runner(index, image_input), name=f"image-edit-ref-{index}") + + return [result for result in results if result is not None] + + +def _replace_edit_image_placeholders( + prompt: str, references: list[_EditReference] +) -> str: + """Replace @IMAGE1-style placeholders with uploaded asset IDs.""" + + def _replace(match: re.Match[str]) -> str: + image_number = int(match.group(1)) + if image_number < 1 or image_number > len(references): + return match.group(0) + return f"@{references[image_number - 1].file_id}" + + return _EDIT_IMAGE_PLACEHOLDER_RE.sub(_replace, prompt) + + +def _extract_edit_prompt_and_inputs(messages: list[dict]) -> tuple[str, list[str]]: + """Extract the final prompt and ordered image references from messages.""" + prompt = "" + image_inputs: list[str] = [] + + for msg in messages: + content = msg.get("content", "") + if isinstance(content, str) and content.strip(): + prompt = content.strip() + continue + if not isinstance(content, list): + continue + for block in content: + if not isinstance(block, dict): + continue + btype = block.get("type") + if btype == "text": + text = (block.get("text") or "").strip() + if text: + prompt = text + elif btype == "image_url": + url = (block.get("image_url") or {}).get("url", "") + if url: + image_inputs.append(url) + + if not prompt: + raise ValidationError("Image edit requires a non-empty text prompt", param="messages") + return prompt, _normalize_edit_inputs(image_inputs) + + +def _absolutize_asset_url(url: str) -> str: + """Resolve an assets URL/path to an absolute URL.""" + full_url, _, _ = resolve_download_url(url) + return full_url + + +def _extract_user_id(token: str) -> str | None: + cookie = build_sso_cookie(token) + match = _X_USER_ID_RE.search(cookie) + if match: + return match.group(1) + return None + + +def _resolve_edit_final_url( + *, + raw_url: str | None, + asset_id: str | None, + user_id: str | None, +) -> str | None: + """Prefer stable asset content URLs over generated image paths for image-edit finals.""" + if asset_id and user_id: + resolved = resolve_asset_reference(asset_id, "", user_id=user_id) + if resolved: + return resolved + if raw_url: + return _absolutize_asset_url(raw_url) + return None + + +def _collect_edit_results( + *, + obj: dict[str, Any], + final_urls: dict[int, str], + user_id: str | None, +) -> None: + """Update final edit image URLs from one parsed SSE payload.""" + stream = extract_streaming_response(obj) + if stream: + try: + progress = int(stream.get("progress") or 0) + except (TypeError, ValueError): + progress = 0 + if progress >= 100 and not stream.get("moderated"): + raw_url = stream.get("imageUrl") + asset_id = stream.get("assetId") + resolved_url = _resolve_edit_final_url( + raw_url=raw_url if isinstance(raw_url, str) and raw_url else None, + asset_id=asset_id if isinstance(asset_id, str) and asset_id else None, + user_id=user_id, + ) + if resolved_url: + index = _parse_image_index(stream.get("imageIndex")) + if index is not None: + final_urls[index] = resolved_url + + for index, asset_id in enumerate(extract_model_response_file_attachments(obj)): + resolved_url = _resolve_edit_final_url(raw_url=None, asset_id=asset_id, user_id=user_id) + if resolved_url: + final_urls.setdefault(index, resolved_url) + + for index, url in enumerate(extract_model_response_urls(obj)): + final_urls.setdefault(index, _absolutize_asset_url(url)) + + +def _parse_image_index(value: Any) -> int | None: + """Return a non-negative image index from upstream metadata.""" + try: + index = int(value) + except (TypeError, ValueError): + return None + return index if index >= 0 else None + + +async def _collect_edit_final_urls( + *, + token: str, + prompt: str, + image_references: list[str], + parent_post_id: str, + timeout_s: float, + progress_cb: Callable[[int, int], Awaitable[None]] | None = None, +) -> dict[int, str]: + """Collect final image URLs from the dedicated image-edit SSE stream.""" + final_urls: dict[int, str] = {} + user_id = _extract_user_id(token) + async for line in _stream_image_edit( + token, + prompt, + image_references, + parent_post_id, + timeout_s=timeout_s, + ): + ev_type, data = classify_line(line) + if ev_type == "done": + break + if ev_type != "data" or not data: + continue + try: + obj = orjson.loads(data) + except Exception: + continue + raise_for_stream_error(obj) + stream = extract_streaming_response(obj) + if stream and progress_cb is not None: + index = _parse_image_index(stream.get("imageIndex")) + if index is not None: + try: + progress = _clamp_progress(int(stream.get("progress") or 0)) + except (TypeError, ValueError): + progress = 0 + await progress_cb(index, progress) + _collect_edit_results(obj=obj, final_urls=final_urls, user_id=user_id) + + if not final_urls: + raise UpstreamError("Image edit returned no images") + return final_urls + + +async def _collect_edit_images( + *, + token: str, + prompt: str, + image_references: list[str], + parent_post_id: str, + requested_n: int, + response_format: str, + timeout_s: float, + progress_cb: Callable[[int, int], Awaitable[None]] | None = None, +) -> list[_ImageOutput]: + """Collect up to *requested_n* edit results. + + Upstream image-edit requests are issued with a fixed batch size of 2. + If one batch returns fewer usable finals than requested, issue one more + attempt and merge unique results. + """ + images: list[_ImageOutput] = [] + seen_urls: set[str] = set() + + for _ in range(_EDIT_MAX_ATTEMPTS): + final_urls = await _collect_edit_final_urls( + token=token, + prompt=prompt, + image_references=image_references, + parent_post_id=parent_post_id, + timeout_s=timeout_s, + progress_cb=progress_cb, + ) + for _, url in sorted(final_urls.items()): + if url in seen_urls: + continue + seen_urls.add(url) + images.append( + await _resolve_image_output( + token=token, + url=url, + response_format=response_format, + ) + ) + if len(images) >= requested_n: + return images[:requested_n] + + if len(images) >= requested_n: + break + + if len(images) < requested_n: + logger.warning( + "image edit returned fewer images than requested: requested={} received={}", + requested_n, len(images), + ) + return images[:requested_n] + + +async def _stream_image_edit( + token: str, + prompt: str, + image_references: list[str], + parent_post_id: str, + *, + timeout_s: float = 120.0, +) -> AsyncGenerator[str, None]: + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + payload = build_image_edit_payload( + prompt=prompt, + image_references=image_references, + parent_post_id=parent_post_id, + ) + headers = build_http_headers( + token, + lease=lease, + origin="https://grok.com", + referer=f"https://grok.com/imagine/post/{parent_post_id}", + ) + kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**kwargs) as session: + response = await session.post( + CHAT, + headers=headers, + data=orjson.dumps(payload), + timeout=timeout_s, + stream=True, + ) + if response.status_code != 200: + body = response.content.decode("utf-8", "replace")[:300] + raise UpstreamError( + f"Image-edit upstream returned {response.status_code}", + status=response.status_code, + body=body, + ) + async for line in response.aiter_lines(): + yield line + + +async def _stream_lite_generate( + token: str, + message: str, + mode_id: ModeId, + *, + timeout_s: float = 120.0, +) -> AsyncGenerator[str, None]: + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + payload = build_chat_payload( + message = f"Drawing: {message}", + mode_id = mode_id, + file_attachments = [], + request_overrides = {"imageGenerationCount": 2}, + ) + headers = build_http_headers(token, lease=lease) + kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**kwargs) as session: + response = await session.post( + CHAT, + headers = headers, + data = orjson.dumps(payload), + timeout = timeout_s, + stream = True, + ) + if response.status_code != 200: + body = response.content.decode("utf-8", "replace")[:300] + raise UpstreamError( + f"Image-generation upstream returned {response.status_code}", + status = response.status_code, + body = body, + ) + async for line in response.aiter_lines(): + yield line + + +async def _run_lite_request( + *, + spec: ModelSpec, + prompt: str, + timeout_s: float, + response_format: str, + progress_cb: Callable[[int], Awaitable[None]] | None = None, +) -> _ImageOutput: + from app.dataplane.account import _directory as _acct_dir + + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + max_retries = selection_max_retries() + retry_codes = _configured_retry_codes(get_config()) + excluded: list[str] = [] + + for attempt in range(max_retries + 1): + acct = await _acct_dir.reserve( + pool_candidates=spec.pool_candidates(), + mode_id=int(spec.mode_id), + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for image generation") + + token = acct.token + adapter = StreamAdapter() + success = False + retry = False + fail_exc: BaseException | None = None + + try: + async for line in _stream_lite_generate( + token, + prompt, + spec.mode_id, + timeout_s=timeout_s, + ): + ev_type, data = classify_line(line) + if ev_type == "done": + break + if ev_type != "data" or not data: + continue + for ev in adapter.feed(data): + if ev.kind == "image_progress": + if progress_cb is not None: + try: + await progress_cb(_clamp_progress(int(ev.content or "0"))) + except ValueError: + pass + if ev.kind == "image" and ev.content: + if progress_cb is not None: + await progress_cb(100) + image = await _resolve_image_output( + token=token, + url=ev.content, + response_format=response_format, + ) + success = True + return image + raise UpstreamError("Image generation returned no images") + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + retry = True + logger.warning( + "lite image retry scheduled: attempt={}/{} status={} token={}...", + attempt + 1, + max_retries, + exc.status, + token[:8], + ) + else: + raise + except BaseException as exc: + fail_exc = exc + raise + finally: + await _acct_dir.release(acct) + kind = ( + FeedbackKind.SUCCESS + if success + else _feedback_kind(fail_exc) + if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task( + _quota_sync(token, int(spec.mode_id)) + ).add_done_callback(_log_task_exception) + else: + asyncio.create_task( + _fail_sync(token, int(spec.mode_id), fail_exc) + ).add_done_callback(_log_task_exception) + + if retry: + excluded.append(token) + continue + + raise RateLimitError("No available accounts for image generation") + + +async def _run_lite_batch( + *, + spec: ModelSpec, + prompt: str, + n: int, + timeout_s: float, + response_format: str, + progress_cb: Callable[[int, int], Awaitable[None]] | None = None, +) -> list[_ImageOutput]: + results: list[_ImageOutput | None] = [None] * n + + async def _runner(idx: int) -> None: + results[idx] = await _run_lite_request( + spec=spec, + prompt=prompt, + timeout_s=timeout_s, + response_format=response_format, + progress_cb=None if progress_cb is None else lambda progress: progress_cb(idx, progress), + ) + + async with asyncio.TaskGroup() as tg: + for idx in range(n): + tg.create_task(_runner(idx), name=f"lite-image-{idx}") + + return [result for result in results if result is not None] + + +async def edit( + *, + model: str, + messages: list[dict], + n: int = 1, + size: str = "1024x1024", + response_format: str = "url", + stream: bool = False, + chat_format: bool = False, +) -> dict | AsyncGenerator[str, None]: + """Edit images via media/post/create + imagine-image-edit chat payload.""" + cfg = get_config() + spec = resolve_model(model) + timeout_s = cfg.get_float("chat.timeout", 120.0) + if not (1 <= n <= _EDIT_MAX_N): + raise ValidationError("image edit n must be between 1 and 2", param="n") + _normalize_edit_size(size) + + prompt, image_inputs = _extract_edit_prompt_and_inputs(messages) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + acct = await _acct_dir.reserve( + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + now_s_override = now_s(), + ) + if acct is None: + raise RateLimitError("No available accounts for image edit") + + token = acct.token + response_id = make_response_id() + edit_prompt = prompt + + try: + edit_references = await _prepare_edit_references(token, image_inputs) + if not edit_references: + raise UpstreamError("All image uploads failed; cannot proceed with image edit") + edit_prompt = _replace_edit_image_placeholders(prompt, edit_references) + image_references = [ref.content_url for ref in edit_references] + + post = await create_media_post( + token, + media_type=IMAGE_POST_MEDIA_TYPE, + prompt=edit_prompt, + ) + post_data = post.get("post") + if not isinstance(post_data, dict): + raise UpstreamError("Image edit create-post returned no post payload") + parent_post_id = str(post_data.get("id") or "").strip() + if not parent_post_id: + raise UpstreamError("Image edit create-post returned no post id") + post_prompt = post_data.get("originalPrompt") or post_data.get("prompt") + if isinstance(post_prompt, str) and post_prompt.strip(): + edit_prompt = post_prompt.strip() + except Exception: + await _acct_dir.release(acct) + raise + + if stream: + async def _sse_stream() -> AsyncGenerator[str, None]: + success = False + fail_exc: BaseException | None = None + progress_map: dict[int, int] = {} + last_progress = -1 + queue: asyncio.Queue[tuple[int, int]] = asyncio.Queue() + try: + async def _progress(index: int, progress: int) -> None: + progress_map[index] = _clamp_progress(progress) + await queue.put(( + _compute_progress_percent(progress_map, n), + _completed_items(progress_map), + )) + + task = asyncio.create_task( + _collect_edit_images( + token=token, + prompt=edit_prompt, + image_references=image_references, + parent_post_id=parent_post_id, + requested_n=n, + response_format=response_format, + timeout_s=timeout_s, + progress_cb=_progress, + ) + ) + while not task.done() or not queue.empty(): + try: + aggregate, completed = await asyncio.wait_for(queue.get(), timeout=0.1) + except asyncio.TimeoutError: + continue + if chat_format and aggregate > last_progress: + last_progress = aggregate + chunk = make_thinking_chunk( + response_id, + model, + _progress_reason_delta( + "图片", + aggregate, + completed=completed, + total=n, + ), + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + images = await task + for image in images: + content = _output_content(image, chat_format=chat_format) + chunk = make_stream_chunk(response_id, model, content) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + final = make_stream_chunk(response_id, model, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + success = True + except BaseException as exc: + fail_exc = exc + raise + finally: + await _acct_dir.release(acct) + kind = FeedbackKind.SUCCESS if success else _feedback_kind(fail_exc) if fail_exc else FeedbackKind.SERVER_ERROR + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id), fail_exc)) + + return _sse_stream() + + success = False + fail_exc: BaseException | None = None + reasoning_updates: list[str] = [] + progress_map: dict[int, int] = {} + try: + async def _progress(index: int, progress: int) -> None: + progress_map[index] = _clamp_progress(progress) + if chat_format: + _append_reason_update( + reasoning_updates, + "图片", + _compute_progress_percent(progress_map, n), + completed=_completed_items(progress_map), + total=n, + ) + + images = await _collect_edit_images( + token=token, + prompt=edit_prompt, + image_references=image_references, + parent_post_id=parent_post_id, + requested_n=n, + response_format=response_format, + timeout_s=timeout_s, + progress_cb=_progress, + ) + success = True + except BaseException as exc: + fail_exc = exc + raise + finally: + await _acct_dir.release(acct) + kind = FeedbackKind.SUCCESS if success else _feedback_kind(fail_exc) if fail_exc else FeedbackKind.SERVER_ERROR + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id), fail_exc)) + + if chat_format: + content = "\n\n".join(image.markdown_value for image in images) + reasoning = "\n".join(reasoning_updates) if reasoning_updates else None + return make_chat_response( + model, + content, + prompt_content=prompt, + response_id=response_id, + reasoning_content=reasoning, + ) + + data_list = [ + {"b64_json": image.api_value} + if _normalize_response_format(response_format) == "b64_json" + else {"url": image.api_value} + for image in images + ] + return {"created": int(time.time()), "data": data_list} + + +__all__ = ["generate", "edit", "resolve_aspect_ratio"] diff --git a/app/products/openai/responses.py b/app/products/openai/responses.py new file mode 100644 index 0000000000000000000000000000000000000000..98008ab451fa634d5bc9068794c53b6babc4dcc0 --- /dev/null +++ b/app/products/openai/responses.py @@ -0,0 +1,770 @@ +"""OpenAI Responses API handler (/v1/responses). + +Unsupported request fields are silently discarded. +Streaming emits standard Responses API SSE events. +""" + +import asyncio +from typing import Any, AsyncGenerator + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError +from app.platform.runtime.clock import now_s +from app.platform.tokens import estimate_prompt_tokens, estimate_tokens, estimate_tool_call_tokens +from app.control.model.enums import ModeId +from app.control.model.registry import resolve as resolve_model +from app.control.account.enums import FeedbackKind +from app.dataplane.reverse.protocol.xai_chat import classify_line, StreamAdapter +from app.products._account_selection import reserve_account, selection_max_retries + +from .chat import _stream_chat, _extract_message, _resolve_image, _quota_sync, _fail_sync, _parse_retry_codes, _feedback_kind, _log_task_exception, _upstream_body_excerpt +from .chat import _configured_retry_codes, _should_retry_upstream +from ._format import ( + make_resp_id, build_resp_usage, make_resp_object, format_sse, +) +from app.dataplane.reverse.protocol.tool_prompt import ( + build_tool_system_prompt, extract_tool_names, inject_into_message, tool_calls_to_xml, +) +from app.dataplane.reverse.protocol.tool_parser import parse_tool_calls +from ._tool_sieve import ToolSieve + + +# --------------------------------------------------------------------------- +# Tool format normalisation +# --------------------------------------------------------------------------- + +def _to_chat_tools(tools: list[dict]) -> list[dict]: + """Normalise Responses API tool format → Chat Completions format. + + Responses API: {type, name, description, parameters} (flat) + Chat Completions: {type, function: {name, description, parameters}} + + Already-wrapped tools are passed through unchanged so this is safe to + call regardless of which format the caller used. + """ + normalised = [] + for tool in tools: + if tool.get("type") == "function" and "function" not in tool and "name" in tool: + normalised.append({ + "type": "function", + "function": { + "name": tool.get("name", ""), + "description": tool.get("description", ""), + "parameters": tool.get("parameters"), + }, + }) + else: + normalised.append(tool) + return normalised + + +# --------------------------------------------------------------------------- +# Tool call helpers (Responses API format) +# --------------------------------------------------------------------------- + +def _build_fc_items(calls: list) -> list[dict]: + """Allocate stable IDs and build function_call output items for response.completed.""" + return [ + { + "id": make_resp_id("fc"), + "type": "function_call", + "call_id": tc.call_id, + "name": tc.name, + "arguments": tc.arguments, + "status": "completed", + } + for tc in calls + ] + + +async def _emit_fc_events(items: list[dict], base_idx: int): + """Async generator — yields SSE events for pre-built function_call items. + + Using pre-built items ensures the IDs in the streaming events match those + in the final response.completed payload. + """ + for i, item in enumerate(items): + out_idx = base_idx + i + fc_item_id = item["id"] + yield format_sse("response.output_item.added", { + "type": "response.output_item.added", + "output_index": out_idx, + "item": { + "id": fc_item_id, + "type": "function_call", + "call_id": item["call_id"], + "name": item["name"], + "arguments": "", + "status": "in_progress", + }, + }) + yield format_sse("response.function_call_arguments.delta", { + "type": "response.function_call_arguments.delta", + "item_id": fc_item_id, + "output_index": out_idx, + "delta": item["arguments"], + }) + yield format_sse("response.function_call_arguments.done", { + "type": "response.function_call_arguments.done", + "item_id": fc_item_id, + "output_index": out_idx, + "arguments": item["arguments"], + }) + yield format_sse("response.output_item.done", { + "type": "response.output_item.done", + "output_index": out_idx, + "item": item, + }) + + +# --------------------------------------------------------------------------- +# Input normalisation +# --------------------------------------------------------------------------- + +def _parse_input(input_val: str | list) -> list[dict]: + """Convert Responses API input to our internal messages list. + + Handles message, function_call, and function_call_output item types. + function_call → assistant message with tool_calls + function_call_output → tool result message + """ + if isinstance(input_val, str): + return [{"role": "user", "content": input_val}] + + messages: list[dict] = [] + for item in input_val: + if not isinstance(item, dict): + continue + item_type = item.get("type", "message" if "role" in item else None) + + if item_type == "function_call": + # Reconstruct as assistant message with tool_calls (Chat Completions format) + call_id = item.get("call_id", "") + name = item.get("name", "") + args = item.get("arguments", "{}") + messages.append({ + "role": "assistant", + "content": None, + "tool_calls": [{ + "id": call_id, + "type": "function", + "function": {"name": name, "arguments": args}, + }], + }) + continue + + if item_type == "function_call_output": + # Reconstruct as tool result message + call_id = item.get("call_id", "") + output = item.get("output", "") + messages.append({ + "role": "tool", + "tool_call_id": call_id, + "content": output, + }) + continue + + if item_type != "message": + continue # skip reasoning items, etc. + + role = item.get("role", "user") + content = item.get("content", "") + + if isinstance(content, list): + normalized: list[dict] = [] + for part in content: + if not isinstance(part, dict): + continue + ptype = part.get("type", "") + if ptype in ("input_text", "output_text"): + normalized.append({"type": "text", "text": part.get("text", "")}) + elif ptype == "image": + src = part.get("image_url") or part.get("source") or {} + url = src.get("url", "") + if url: + normalized.append({"type": "image_url", "image_url": {"url": url}}) + elif ptype == "input_image": + src = part.get("image_url") or part.get("source") or {} + if isinstance(src, dict): + url = src.get("url", "") + else: + url = str(src or "") + if url: + normalized.append({"type": "image_url", "image_url": {"url": url}}) + else: + normalized.append(part) + content = normalized + + messages.append({"role": role, "content": content}) + return messages + + +# --------------------------------------------------------------------------- +# Main handler +# --------------------------------------------------------------------------- + +async def create( + *, + model: str, + input_val: str | list, + instructions: str | None, + stream: bool, + emit_think: bool, + temperature: float, + top_p: float, + tools: list[dict] | None = None, + tool_choice: Any = None, +) -> dict | AsyncGenerator[str, None]: + + cfg = get_config() + spec = resolve_model(model) + mode_id = int(spec.mode_id) # cast once, reuse everywhere + + messages: list[dict] = [] + if instructions: + messages.append({"role": "system", "content": instructions}) + messages.extend(_parse_input(input_val)) + + message, files = _extract_message(messages) + if not message.strip(): + raise UpstreamError("Empty message after extraction", status=400) + + # Tool prompt injection — only modify the message text, never the Grok payload + # Normalise to Chat Completions format first (Responses API uses a flat structure) + tool_names: list[str] = [] + if tools: + chat_tools = _to_chat_tools(tools) + tool_names = extract_tool_names(chat_tools) + tool_prompt = build_tool_system_prompt(chat_tools, tool_choice) + message = inject_into_message(message, tool_prompt) + logger.info("responses tool injection: tool_names={} choice={}", tool_names, tool_choice) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + directory = _acct_dir + + max_retries = selection_max_retries() + retry_codes = _configured_retry_codes(cfg) + response_id = make_resp_id("resp") + reasoning_id = make_resp_id("rs") + message_id = make_resp_id("msg") + timeout_s = cfg.get_float("chat.timeout", 120.0) + + # ------------------------------------------------------------------------- + # Console 模型路由 — 走 console.x.ai/v1/responses,输出转为 Responses API 格式 + # ------------------------------------------------------------------------- + if spec.is_console_chat(): + from .console_responses import create as console_responses_create + return await console_responses_create( + model=model, + messages=messages, + stream=stream, + emit_think=emit_think, + temperature=temperature, + top_p=top_p, + response_id=response_id, + reasoning_id=reasoning_id, + message_id=message_id, + ) + + # ------------------------------------------------------------------------- + # Streaming (grok.com path) + # ------------------------------------------------------------------------- + async def _run_stream() -> AsyncGenerator[str, None]: + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, + spec, + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() + think_buf: list[str] = [] + text_buf: list[str] = [] + reasoning_started = False + reasoning_closed = False + message_started = False + sieve = ToolSieve(tool_names) if tool_names else None + tool_calls_emitted = False + detected_fc_items: list[dict] = [] + collected_annotations: list[dict] = [] + + try: + try: + yield format_sse("response.created", { + "type": "response.created", + "response": make_resp_object(response_id, model, "in_progress", []), + }) + + ended = False + yield ": heartbeat\n\n" + async for line in _stream_chat( + token = token, + mode_id = ModeId(selected_mode_id), + message = message, + files = files, + timeout_s = timeout_s, + ): + if tool_calls_emitted: + break + + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + + for ev in adapter.feed(data): + + if ev.kind == "thinking" and emit_think and not reasoning_closed: + if not reasoning_started: + reasoning_started = True + yield format_sse("response.output_item.added", { + "type": "response.output_item.added", + "output_index": 0, + "item": { + "id": reasoning_id, "type": "reasoning", + "summary": [], "status": "in_progress", + }, + }) + yield format_sse("response.reasoning_summary_part.added", { + "type": "response.reasoning_summary_part.added", + "item_id": reasoning_id, + "output_index": 0, + "summary_index": 0, + "part": {"type": "summary_text", "text": ""}, + }) + think_buf.append(ev.content) + yield format_sse("response.reasoning_summary_text.delta", { + "type": "response.reasoning_summary_text.delta", + "item_id": reasoning_id, + "output_index": 0, + "summary_index": 0, + "delta": ev.content, + }) + + elif ev.kind == "text": + if reasoning_started and not reasoning_closed: + reasoning_closed = True + full_think = "".join(think_buf) + yield format_sse("response.reasoning_summary_text.done", { + "type": "response.reasoning_summary_text.done", + "item_id": reasoning_id, + "output_index": 0, + "summary_index": 0, + "text": full_think, + }) + yield format_sse("response.reasoning_summary_part.done", { + "type": "response.reasoning_summary_part.done", + "item_id": reasoning_id, + "output_index": 0, + "summary_index": 0, + "part": {"type": "summary_text", "text": full_think}, + }) + yield format_sse("response.output_item.done", { + "type": "response.output_item.done", + "output_index": 0, + "item": { + "id": reasoning_id, + "type": "reasoning", + "summary": [{"type": "summary_text", "text": full_think}], + "status": "completed", + }, + }) + + # Feed through ToolSieve if tools are active + if sieve is not None: + safe_text, calls = sieve.feed(ev.content) + if calls is not None: + fc_items = _build_fc_items(calls) + detected_fc_items = fc_items + base_idx = 1 if reasoning_started else 0 + async for evt in _emit_fc_events(fc_items, base_idx): + yield evt + tool_calls_emitted = True + ended = True + break + text_chunk = safe_text + else: + text_chunk = ev.content + + if text_chunk: + msg_idx = 1 if reasoning_started else 0 + if not message_started: + message_started = True + yield format_sse("response.output_item.added", { + "type": "response.output_item.added", + "output_index": msg_idx, + "item": { + "id": message_id, "type": "message", + "role": "assistant", "content": [], "status": "in_progress", + }, + }) + yield format_sse("response.content_part.added", { + "type": "response.content_part.added", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "part": {"type": "output_text", "text": "", "annotations": []}, + }) + + text_buf.append(text_chunk) + yield format_sse("response.output_text.delta", { + "type": "response.output_text.delta", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "delta": text_chunk, + }) + + elif ev.kind == "annotation" and ev.annotation_data: + if message_started: + collected_annotations.append(ev.annotation_data) + msg_idx = 1 if reasoning_started else 0 + yield format_sse("response.output_text.annotation.added", { + "type": "response.output_text.annotation.added", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "annotation_index": len(collected_annotations) - 1, + "annotation": ev.annotation_data, + }) + + elif ev.kind == "soft_stop": + ended = True + break + + if ended: + break + + # Flush sieve after stream ends (incomplete XML at end of stream) + if sieve is not None and not tool_calls_emitted: + calls = sieve.flush() + if calls: + fc_items = _build_fc_items(calls) + detected_fc_items = fc_items + base_idx = 1 if reasoning_started else 0 + async for evt in _emit_fc_events(fc_items, base_idx): + yield evt + tool_calls_emitted = True + + if tool_calls_emitted: + # Build output with function_call items only + full_think = "".join(think_buf) + output: list[dict] = [] + if reasoning_started and full_think: + output.append({ + "id": reasoning_id, + "type": "reasoning", + "summary": [{"type": "summary_text", "text": full_think}], + "status": "completed", + }) + output.extend(detected_fc_items) + pt = estimate_prompt_tokens(message) + ct = estimate_tool_call_tokens(detected_fc_items) + rt = estimate_tokens(full_think) if full_think else 0 + yield format_sse("response.completed", { + "type": "response.completed", + "response": make_resp_object( + response_id, model, "completed", output, + build_resp_usage(pt, ct + rt, rt), + ), + }) + yield "data: [DONE]\n\n" + success = True + logger.info("responses stream tool_calls: attempt={}/{} model={}", + attempt + 1, max_retries + 1, model) + else: + # Normal text path + msg_idx = 1 if reasoning_started else 0 + for url, img_id in adapter.image_urls: + img_text = await _resolve_image(token, url, img_id) + img_md = img_text + "\n" + text_buf.append(img_md) + if message_started: + yield format_sse("response.output_text.delta", { + "type": "response.output_text.delta", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "delta": img_md, + }) + + references = adapter.references_suffix() + if references: + text_buf.append(references) + if message_started: + yield format_sse("response.output_text.delta", { + "type": "response.output_text.delta", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "delta": references, + }) + + full_text = "".join(text_buf) + if message_started: + yield format_sse("response.output_text.done", { + "type": "response.output_text.done", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "text": full_text, + }) + yield format_sse("response.content_part.done", { + "type": "response.content_part.done", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "part": {"type": "output_text", "text": full_text, "annotations": collected_annotations}, + }) + # 构建 message item(流式 output_item.done + response.completed 共用) + sources = adapter.search_sources_list() + msg_item: dict = { + "id": message_id, + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": full_text, "annotations": collected_annotations}], + "status": "completed", + } + if sources: + msg_item["search_sources"] = sources + yield format_sse("response.output_item.done", { + "type": "response.output_item.done", + "output_index": msg_idx, + "item": msg_item, + }) + + full_think = "".join(think_buf) + output = [] + if reasoning_started and full_think: + output.append({ + "id": reasoning_id, + "type": "reasoning", + "summary": [{"type": "summary_text", "text": full_think}], + "status": "completed", + }) + # 复用 msg_item(message_started 时已构建);未启动时重新构建 + if not message_started: + msg_item = { + "id": message_id, + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": full_text, "annotations": adapter.annotations_list()}], + "status": "completed", + } + sources = adapter.search_sources_list() + if sources: + msg_item["search_sources"] = sources + output.append(msg_item) + + pt = estimate_prompt_tokens(message) + ct = estimate_tokens(full_text) + rt = estimate_tokens(full_think) if full_think else 0 + yield format_sse("response.completed", { + "type": "response.completed", + "response": make_resp_object( + response_id, model, "completed", output, + build_resp_usage(pt, ct + rt, rt), + ), + }) + yield "data: [DONE]\n\n" + success = True + logger.info("responses stream completed: attempt={}/{} model={} text_len={} reasoning_len={} image_count={}", + attempt + 1, max_retries + 1, model, + len(full_text), len(full_think), len(adapter.image_urls)) + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + _retry = True + logger.warning("responses stream retry scheduled: attempt={}/{} status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8]) + else: + logger.warning( + "responses stream upstream failed: attempt={}/{} model={} status={} body={}", + attempt + 1, + max_retries + 1, + model, + exc.status, + _upstream_body_excerpt(exc), + ) + raise + + finally: + await directory.release(acct) + kind = FeedbackKind.SUCCESS if success else _feedback_kind(fail_exc) if fail_exc else FeedbackKind.SERVER_ERROR + await directory.feedback(token, kind, selected_mode_id, now_s_val=now_s()) + if success: + asyncio.create_task(_quota_sync(token, selected_mode_id)).add_done_callback(_log_task_exception) + else: + asyncio.create_task(_fail_sync(token, selected_mode_id, fail_exc)).add_done_callback(_log_task_exception) + + if success or not _retry: + return + excluded.append(token) + + if stream: + return _run_stream() + + # ------------------------------------------------------------------------- + # Non-streaming + # ------------------------------------------------------------------------- + excluded: list[str] = [] + token = "" + adapter = StreamAdapter() + for attempt in range(max_retries + 1): + acct, selected_mode_id = await reserve_account( + directory, + spec, + now_s_override=now_s(), + exclude_tokens=excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() # fresh adapter per attempt + + try: + try: + async for line in _stream_chat( + token = token, + mode_id = ModeId(selected_mode_id), + message = message, + files = files, + timeout_s = timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + ended = False + for ev in adapter.feed(data): + if ev.kind == "soft_stop": + ended = True + break + if ended: + break + success = True + + except UpstreamError as exc: + fail_exc = exc + if _should_retry_upstream(exc, retry_codes) and attempt < max_retries: + _retry = True + logger.warning("responses retry scheduled: attempt={}/{} status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8]) + else: + logger.warning( + "responses upstream failed: attempt={}/{} model={} status={} body={}", + attempt + 1, + max_retries + 1, + model, + exc.status, + _upstream_body_excerpt(exc), + ) + raise + + finally: + await directory.release(acct) + kind = FeedbackKind.SUCCESS if success else _feedback_kind(fail_exc) if fail_exc else FeedbackKind.SERVER_ERROR + await directory.feedback(token, kind, selected_mode_id) + if success: + asyncio.create_task(_quota_sync(token, selected_mode_id)).add_done_callback(_log_task_exception) + else: + asyncio.create_task(_fail_sync(token, selected_mode_id, fail_exc)).add_done_callback(_log_task_exception) + + if success or not _retry: + break + excluded.append(token) + + full_text = "".join(adapter.text_buf) + if adapter.image_urls: + img_texts = await asyncio.gather( + *[_resolve_image(token, url, img_id) for url, img_id in adapter.image_urls], + return_exceptions=True, + ) + for img_text in img_texts: + if isinstance(img_text, BaseException): + logger.warning("responses image resolve failed: error={}", img_text) + elif isinstance(img_text, str): + if full_text: + full_text += "\n\n" + full_text += img_text + references = adapter.references_suffix() + if references: + full_text += references + + full_think = ("".join(adapter.thinking_buf) or "") if emit_think else "" + + # Check for tool calls in the accumulated text + if tool_names: + tc_result = parse_tool_calls(full_text, tool_names) + if tc_result.calls: + output: list[dict] = [] + if full_think: + output.append({ + "id": reasoning_id, + "type": "reasoning", + "summary": [{"type": "summary_text", "text": full_think}], + "status": "completed", + }) + output.extend(_build_fc_items(tc_result.calls)) + pt = estimate_prompt_tokens(message) + ct = estimate_tool_call_tokens(tc_result.calls) + rt = estimate_tokens(full_think) if full_think else 0 + logger.info("responses tool_calls: model={} calls={}", model, len(tc_result.calls)) + return make_resp_object( + response_id, model, "completed", output, + build_resp_usage(pt, ct + rt, rt), + ) + + logger.info("responses request completed: model={} text_len={} reasoning_len={} image_count={}", + model, len(full_text), len(full_think), len(adapter.image_urls)) + + output = [] + if full_think: + output.append({ + "id": reasoning_id, + "type": "reasoning", + "summary": [{"type": "summary_text", "text": full_think}], + "status": "completed", + }) + msg_item: dict = { + "id": message_id, + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": full_text, "annotations": adapter.annotations_list()}], + "status": "completed", + } + sources = adapter.search_sources_list() + if sources: + msg_item["search_sources"] = sources + output.append(msg_item) + + pt = estimate_prompt_tokens(message) + ct = estimate_tokens(full_text) + rt = estimate_tokens(full_think) if full_think else 0 + return make_resp_object( + response_id, model, "completed", output, + build_resp_usage(pt, ct + rt, rt), + ) + + +__all__ = ["create"] diff --git a/app/products/openai/router.py b/app/products/openai/router.py new file mode 100644 index 0000000000000000000000000000000000000000..01a27504af5469280c7fbd5c426004ce095957ed --- /dev/null +++ b/app/products/openai/router.py @@ -0,0 +1,610 @@ +"""OpenAI-compatible API router (/v1/*).""" + +import base64 +import binascii +import mimetypes +from typing import Annotated, AsyncGenerator, AsyncIterable, Literal + +import orjson +from fastapi import APIRouter, Depends, File, Form, Query, Request, UploadFile +from fastapi.responses import JSONResponse, StreamingResponse, FileResponse + +from app.control.account.state_machine import is_manageable +from app.platform.auth.middleware import verify_api_key +from app.platform.errors import AppError, ValidationError +from app.platform.logging.logger import logger +from app.platform.storage import image_files_dir, video_files_dir +from app.control.model import registry as model_registry +from app.control.model.spec import ModelSpec +from app.control.account.quota_defaults import supports_mode +from .schemas import ( + ChatCompletionRequest, + ImageGenerationRequest, + VideoConfig, + ImageConfig, + ResponsesCreateRequest, +) +from .chat import completions as chat_completions + +router = APIRouter(prefix="/v1") +_POOL_ID_TO_NAME = {0: "basic", 1: "super", 2: "heavy"} +_TAG_MODELS = "OpenAI - Models" +_TAG_CHAT = "OpenAI - Chat" +_TAG_RESPONSES = "OpenAI - Responses" +_TAG_IMAGES = "OpenAI - Images" +_TAG_VIDEOS = "OpenAI - Videos" +_TAG_FILES = "OpenAI - Files" + + +async def _available_pools(request: Request) -> frozenset[str]: + repo = getattr(request.app.state, "repository", None) + if repo is None: + return frozenset() + + snapshot = await repo.runtime_snapshot() + pools = {record.pool for record in snapshot.items if is_manageable(record)} + return frozenset(pools) + + +def _model_available_for_pools(spec: ModelSpec, pools: frozenset[str]) -> bool: + if not spec.enabled: + return False + for pool_id in spec.pool_candidates(): + pool = _POOL_ID_TO_NAME[pool_id] + if pool in pools and supports_mode(pool, int(spec.mode_id)): + return True + return False + + +# --------------------------------------------------------------------------- +# /v1/models +# --------------------------------------------------------------------------- + + +@router.get("/models", tags=[_TAG_MODELS], dependencies=[Depends(verify_api_key)]) +async def list_models(request: Request): + import time + + pools = await _available_pools(request) + models = [ + { + "id": m.model_name, + "object": "model", + "created": int(time.time()), + "owned_by": "xai", + "name": m.public_name, + } + for m in model_registry.list_enabled() + if _model_available_for_pools(m, pools) + ] + return JSONResponse({"object": "list", "data": models}) + + +@router.get( + "/models/{model_id}", tags=[_TAG_MODELS], dependencies=[Depends(verify_api_key)] +) +async def get_model_endpoint(model_id: str, request: Request): + import time + + spec = model_registry.get(model_id) + pools = await _available_pools(request) + if spec is None or not _model_available_for_pools(spec, pools): + return JSONResponse( + { + "error": { + "message": f"Model {model_id!r} not found", + "type": "invalid_request_error", + } + }, + status_code=404, + ) + return JSONResponse( + { + "id": spec.model_name, + "object": "model", + "created": int(time.time()), + "owned_by": "xai", + "name": spec.public_name, + } + ) + + +# --------------------------------------------------------------------------- +# SSE streaming helpers +# --------------------------------------------------------------------------- + + +async def _safe_sse(stream: AsyncIterable[str]) -> AsyncGenerator[str, None]: + """Wrap an SSE stream, converting exceptions to in-band error events.""" + try: + async for chunk in stream: + yield chunk + except AppError as exc: + payload = orjson.dumps({"error": exc.to_dict()["error"]}).decode() + yield f"event: error\ndata: {payload}\n\n" + yield "data: [DONE]\n\n" + except Exception as exc: + payload = orjson.dumps( + {"error": {"message": str(exc), "type": "server_error"}} + ).decode() + yield f"event: error\ndata: {payload}\n\n" + yield "data: [DONE]\n\n" + + +_SSE_HEADERS = {"Cache-Control": "no-cache", "Connection": "keep-alive"} + + +# --------------------------------------------------------------------------- +# /v1/chat/completions +# --------------------------------------------------------------------------- + +_VALID_ROLES = {"developer", "system", "user", "assistant", "tool"} +_USER_BLOCK_TYPES = {"text", "image_url", "input_audio", "file"} +_ALLOWED_SIZES = {"1280x720", "720x1280", "1792x1024", "1024x1792", "1024x1024"} +_EFFORT_VALUES = {"none", "minimal", "low", "medium", "high", "xhigh"} +_LITE_IMAGE_MODELS = {"grok-imagine-image-lite"} + + +def _validate_chat(req: ChatCompletionRequest) -> None: + from app.platform.errors import ValidationError + + spec = model_registry.get(req.model) + if spec is None or not spec.enabled: + raise ValidationError( + f"Model {req.model!r} does not exist or you do not have access to it.", + param="model", + code="model_not_found", + ) + if not req.messages: + raise ValidationError("messages cannot be empty", param="messages") + for i, msg in enumerate(req.messages): + if msg.role not in _VALID_ROLES: + raise ValidationError( + f"role must be one of {sorted(_VALID_ROLES)}", + param=f"messages.{i}.role", + ) + if req.temperature is not None and not (0 <= req.temperature <= 2): + raise ValidationError( + "temperature must be between 0 and 2", param="temperature" + ) + if req.top_p is not None and not (0 <= req.top_p <= 1): + raise ValidationError("top_p must be between 0 and 1", param="top_p") + if req.reasoning_effort is not None and req.reasoning_effort not in _EFFORT_VALUES: + raise ValidationError( + f"reasoning_effort must be one of {sorted(_EFFORT_VALUES)}", + param="reasoning_effort", + ) + + +def _validate_image_n(model_name: str, n: int, *, param: str) -> None: + max_n = 4 if model_name in _LITE_IMAGE_MODELS else 10 + if not (1 <= n <= max_n): + raise ValidationError( + f"n must be between 1 and {max_n} for model {model_name!r}", + param=param, + ) + + +def _validate_image_edit_n(n: int, *, param: str) -> None: + if not (1 <= n <= 2): + raise ValidationError("n must be between 1 and 2 for image edit", param=param) + + +async def _upload_to_data_uri(upload: UploadFile, *, param: str) -> str: + raw = await upload.read() + if not raw: + raise ValidationError("Uploaded image cannot be empty", param=param) + + mime = ( + (upload.content_type or "").strip().lower() + or mimetypes.guess_type(upload.filename or "")[0] + or "application/octet-stream" + ) + if not mime.startswith("image/"): + raise ValidationError("Uploaded file must be an image", param=param) + + try: + blob_b64 = base64.b64encode(raw).decode("ascii") + except (ValueError, TypeError, binascii.Error) as exc: + raise ValidationError("Failed to encode uploaded image", param=param) from exc + return f"data:{mime};base64,{blob_b64}" + + +@router.post( + "/chat/completions", tags=[_TAG_CHAT], dependencies=[Depends(verify_api_key)] +) +async def chat_completions_endpoint(req: ChatCompletionRequest): + _validate_chat(req) + from app.platform.config.snapshot import get_config + + cfg = get_config() + is_stream = ( + req.stream if req.stream is not None else cfg.get_bool("features.stream", True) + ) + + spec = model_registry.get(req.model) + if spec is None: + raise ValidationError( + f"Model {req.model!r} does not exist or you do not have access to it.", + param="model", + code="model_not_found", + ) + messages = [m.model_dump(exclude_none=True) for m in req.messages] + + try: + # Dispatch by model capability. + if spec.is_image_edit(): + from .images import edit as img_edit + + cfg = req.image_config or ImageConfig() + _validate_image_edit_n(cfg.n or 1, param="image_config.n") + result = await img_edit( + model=req.model, + messages=messages, + n=cfg.n or 1, + size=cfg.size or "1024x1024", + response_format=cfg.response_format or "url", + stream=is_stream, + chat_format=True, + ) + + elif spec.is_image(): + from .images import generate as img_gen + + cfg = req.image_config or ImageConfig() + size = cfg.size or "1024x1024" + fmt = cfg.response_format or "url" + n = cfg.n or 1 + _validate_image_n(req.model, n, param="image_config.n") + # Extract prompt from last user message. + prompt = next( + ( + m.content + for m in reversed(req.messages) + if m.role == "user" + and isinstance(m.content, str) + and m.content.strip() + ), + "", + ) + result = await img_gen( + model=req.model, + prompt=prompt or "", + n=n, + size=size, + response_format=fmt, + stream=is_stream, + chat_format=True, + ) + + elif spec.is_video(): + from .video import completions as vid_comp + + vcfg = req.video_config or VideoConfig() + from .video import validate_video_length as _validate_video_length + + _validate_video_length(vcfg.seconds or 6) + result = await vid_comp( + model=req.model, + messages=messages, + stream=is_stream, + seconds=vcfg.seconds or 6, + size=vcfg.size or "720x1280", + resolution_name=vcfg.resolution_name, + preset=vcfg.preset, + ) + + else: + # reasoning_effort=None → config default; "none" → off; otherwise → on. + if req.reasoning_effort is None: + emit_think: bool | None = None + else: + emit_think = req.reasoning_effort != "none" + result = await chat_completions( + model=req.model, + messages=messages, + stream=is_stream, + emit_think=emit_think, + tools=req.tools, + tool_choice=req.tool_choice, + temperature=req.temperature or 0.8, + top_p=req.top_p or 0.95, + ) + + except AppError: + raise + except Exception as exc: + logger.exception( + "chat completions endpoint failed: model={} stream={} error={}", + req.model, + is_stream, + exc, + ) + if is_stream: + _err_msg = str( + exc + ) # capture before Python clears the except-scope variable + + async def _err_stream(): + payload = orjson.dumps( + {"error": {"message": _err_msg, "type": "server_error"}} + ).decode() + yield f"event: error\ndata: {payload}\n\n" + yield "data: [DONE]\n\n" + + return StreamingResponse( + _err_stream(), media_type="text/event-stream", headers=_SSE_HEADERS + ) + raise + + if isinstance(result, dict): + return JSONResponse(result) + return StreamingResponse( + _safe_sse(result), media_type="text/event-stream", headers=_SSE_HEADERS + ) + + +# --------------------------------------------------------------------------- +# /v1/responses (OpenAI Responses API) +# --------------------------------------------------------------------------- + + +async def _safe_sse_responses(stream) -> AsyncGenerator[str, None]: + """SSE wrapper that converts errors to Responses API error events.""" + try: + async for chunk in stream: + yield chunk + except Exception as exc: + from app.platform.errors import AppError + + if isinstance(exc, AppError): + err = exc.to_dict()["error"] + else: + err = { + "message": str(exc), + "type": "server_error", + "code": None, + "param": None, + } + payload = orjson.dumps({"type": "error", **err}).decode() + yield f"event: error\ndata: {payload}\n\n" + yield "data: [DONE]\n\n" + + +@router.post( + "/responses", tags=[_TAG_RESPONSES], dependencies=[Depends(verify_api_key)] +) +async def responses_endpoint(req: ResponsesCreateRequest): + from app.platform.config.snapshot import get_config + from app.platform.errors import ValidationError as _ValidationError + + spec = model_registry.get(req.model) + if spec is None or not spec.enabled: + raise _ValidationError( + f"Model {req.model!r} does not exist or you do not have access to it.", + param="model", + code="model_not_found", + ) + if not req.input: + raise _ValidationError("input cannot be empty", param="input") + + cfg = get_config() + is_stream = ( + req.stream if req.stream is not None else cfg.get_bool("features.stream", True) + ) + + # Map reasoning param → emit_think flag. + # reasoning=None → use config; reasoning.effort="none" → off; otherwise on. + if req.reasoning is None: + emit_think = cfg.get_bool("features.thinking", True) + elif isinstance(req.reasoning, dict) and req.reasoning.get("effort") == "none": + emit_think = False + else: + emit_think = True + + from .responses import create as responses_create + + result = await responses_create( + model=req.model, + input_val=req.input, + instructions=req.instructions, + stream=is_stream, + emit_think=emit_think, + temperature=req.temperature or 0.8, + top_p=req.top_p or 0.95, + tools=req.tools or None, + tool_choice=req.tool_choice, + ) + + if isinstance(result, dict): + return JSONResponse(result) + return StreamingResponse( + _safe_sse_responses(result), + media_type = "text/event-stream", + headers = _SSE_HEADERS, + ) + + +# --------------------------------------------------------------------------- +# /v1/images/generations (standalone image endpoint) +# --------------------------------------------------------------------------- + + +@router.post( + "/images/generations", tags=[_TAG_IMAGES], dependencies=[Depends(verify_api_key)] +) +async def image_generations(req: ImageGenerationRequest): + spec = model_registry.get(req.model) + if spec is None or not spec.enabled or not spec.is_image(): + raise ValidationError( + f"Model {req.model!r} is not an image model", param="model" + ) + _validate_image_n(req.model, req.n or 1, param="n") + + from .images import generate as img_gen + + result = await img_gen( + model=req.model, + prompt=req.prompt, + n=req.n or 1, + size=req.size or "1024x1024", + response_format=req.response_format or "url", + stream=False, + chat_format=False, + ) + return JSONResponse(result) + + +# --------------------------------------------------------------------------- +# /v1/videos (OpenAI videos.create surface) +# --------------------------------------------------------------------------- + + +@router.post("/videos", tags=[_TAG_VIDEOS], dependencies=[Depends(verify_api_key)]) +async def videos_create( + model: Annotated[str, Form(...)], + prompt: Annotated[str, Form(...)], + seconds: Annotated[int, Form()] = 6, + size: Annotated[ + Literal["720x1280", "1280x720", "1024x1024", "1024x1792", "1792x1024"], Form() + ] = "720x1280", + resolution_name: Annotated[Literal["480p", "720p"] | None, Form()] = None, + preset: Annotated[ + Literal["fun", "normal", "spicy", "custom"] | None, Form() + ] = None, + input_reference: Annotated[ + list[UploadFile] | None, File(alias="input_reference[]") + ] = None, +): + from .video import create_video + + references_payload = None + if input_reference: + references_payload = [ + {"image_url": await _upload_to_data_uri(f, param="input_reference")} + for f in input_reference[:7] + ] + + result = await create_video( + model=model or "grok-video", + prompt=prompt, + seconds=seconds, + size=size or "720x1280", + resolution_name=resolution_name, + preset=preset, + input_references=references_payload, + ) + return JSONResponse(result) + + +@router.get( + "/videos/{video_id}", tags=[_TAG_VIDEOS], dependencies=[Depends(verify_api_key)] +) +async def videos_retrieve(video_id: str): + from .video import retrieve + + return JSONResponse(await retrieve(video_id)) + + +@router.get( + "/videos/{video_id}/content", + tags=[_TAG_VIDEOS], + dependencies=[Depends(verify_api_key)], +) +async def videos_content(video_id: str): + from .video import content_path + + path = await content_path(video_id) + return FileResponse(path, media_type="video/mp4", filename=f"{video_id}.mp4") + + +# --------------------------------------------------------------------------- +# /v1/images/edits (standalone image-edit endpoint) +# --------------------------------------------------------------------------- + + +@router.post( + "/images/edits", tags=[_TAG_IMAGES], dependencies=[Depends(verify_api_key)] +) +async def image_edits( + model: Annotated[str, Form(...)], + prompt: Annotated[str, Form(...)], + image: Annotated[list[UploadFile], File(..., alias="image[]")], + mask: Annotated[UploadFile | None, File()] = None, + n: Annotated[int, Form()] = 1, + size: Annotated[str, Form()] = "1024x1024", + response_format: Annotated[str, Form()] = "url", +): + spec = model_registry.get(model) + if spec is None or not spec.enabled or not spec.is_image_edit(): + raise ValidationError( + f"Model {model!r} is not an image-edit model", param="model" + ) + if mask is not None: + raise ValidationError("mask is not supported yet", param="mask") + _validate_image_edit_n(n, param="n") + + from .images import edit as img_edit + + image_inputs = [ + await _upload_to_data_uri(item, param=f"image.{index}") + for index, item in enumerate(image) + ] + # Wrap input into a single-message conversation. + content = [{"type": "text", "text": prompt}] + content.extend( + {"type": "image_url", "image_url": {"url": image_input}} + for image_input in image_inputs + ) + messages = [{"role": "user", "content": content}] + result = await img_edit( + model=model, + messages=messages, + n=n, + size=size, + response_format=response_format, + stream=False, + chat_format=False, + ) + return JSONResponse(result) + + +# --------------------------------------------------------------------------- +# /v1/files/image — serve locally saved images +# --------------------------------------------------------------------------- + + +@router.get("/files/video", tags=[_TAG_FILES]) +async def serve_video(id: str = Query(..., description="Video file ID")): + """Serve a locally cached video by file ID.""" + import re + + if not re.fullmatch(r"[0-9a-f\-]{16,36}", id): + raise ValidationError("Invalid file ID", param="id") + + path = video_files_dir() / f"{id}.mp4" + if path.exists(): + return FileResponse(path, media_type="video/mp4") + + raise ValidationError(f"Video {id!r} not found", param="id") + + +@router.get("/files/image", tags=[_TAG_FILES]) +async def serve_image(id: str = Query(..., description="Image file ID")): + """Serve a locally cached image by file ID.""" + import re + + if not re.fullmatch(r"[0-9a-f\-]{16,36}", id): + raise ValidationError("Invalid file ID", param="id") + + img_dir = image_files_dir() + for ext in (".jpg", ".png"): + path = img_dir / f"{id}{ext}" + if path.exists(): + mime = "image/png" if ext == ".png" else "image/jpeg" + return FileResponse(path, media_type=mime) + + raise ValidationError(f"Image {id!r} not found", param="id") + + +__all__ = ["router"] diff --git a/app/products/openai/schemas.py b/app/products/openai/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..f4caa0fee1a343ade7385ce6a9a64357c7db483d --- /dev/null +++ b/app/products/openai/schemas.py @@ -0,0 +1,95 @@ +"""OpenAI-compatible request schemas (Pydantic models).""" + +from typing import Any, Literal + +from pydantic import BaseModel, Field + + +class MessageItem(BaseModel): + role: str + content: str | list[dict[str, Any]] | None = None + tool_calls: list[dict[str, Any]] | None = None + tool_call_id: str | None = None + name: str | None = None + + +class ImageConfig(BaseModel): + n: int | None = Field(1, ge=1, le=10) + size: str | None = "1024x1024" + response_format: str | None = None + + +class VideoConfig(BaseModel): + seconds: int | None = 6 + size: Literal["720x1280", "1280x720", "1024x1024", "1024x1792", "1792x1024"] | None = "720x1280" + resolution_name: Literal["480p", "720p"] | None = None + preset: Literal["fun", "normal", "spicy", "custom"] | None = None + + +class ChatCompletionRequest(BaseModel): + model: str + messages: list[MessageItem] + stream: bool | None = None + reasoning_effort: str | None = None + temperature: float | None = 0.8 + top_p: float | None = 0.95 + image_config: ImageConfig | None = None + video_config: VideoConfig | None = None + tools: list[dict[str, Any]] | None = None + tool_choice: str | dict[str, Any] | None = None + parallel_tool_calls: bool | None = True + max_tokens: int | None = None + + +class ImageGenerationRequest(BaseModel): + model: str + prompt: str + n: int | None = Field(1, ge=1, le=10) + size: str | None = "1024x1024" + response_format: str | None = "url" + + +class ImageEditRequest(BaseModel): + model: str + prompt: str + image: str | list[str] + mask: str | None = None + n: int | None = Field(1, ge=1, le=2) + size: str | None = "1024x1024" + response_format: str | None = "url" + + +class ResponsesCreateRequest(BaseModel): + """OpenAI Responses API — /v1/responses. + + Only model/input/instructions/stream/reasoning/temperature/top_p are acted on. + All other fields are accepted and silently discarded. + """ + model: str + input: str | list[Any] + instructions: str | None = None + stream: bool | None = None + reasoning: dict[str, Any] | None = None + temperature: float | None = None + top_p: float | None = None + # silently ignored + max_output_tokens: int | None = None + tools: list[Any] | None = None + tool_choice: Any | None = None + previous_response_id: str | None = None + store: bool | None = None + metadata: dict[str, Any] | None = None + truncation: str | None = None + parallel_tool_calls: bool | None = None + include: list[str] | None = None + background: bool | None = None + + class Config: + extra = "ignore" + + +__all__ = [ + "MessageItem", "ImageConfig", "VideoConfig", + "ChatCompletionRequest", "ImageGenerationRequest", "ImageEditRequest", + "ResponsesCreateRequest", +] diff --git a/app/products/openai/video.py b/app/products/openai/video.py new file mode 100644 index 0000000000000000000000000000000000000000..f4e75baca3222d2046cfdde6b8204eb894921ddb --- /dev/null +++ b/app/products/openai/video.py @@ -0,0 +1,1146 @@ +"""Video generation service. + +Supports: + - OpenAI-style async ``/v1/videos`` jobs + - ``/v1/chat/completions`` video output via the same core pipeline +""" + +import asyncio +import hashlib +import html +import time +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Any, AsyncGenerator, Awaitable, Callable +from urllib.parse import urlparse + +import orjson + +from app.platform.config.snapshot import get_config +from app.platform.errors import ( + AppError, + ErrorKind, + RateLimitError, + UpstreamError, + ValidationError, +) +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_s +from app.platform.storage import save_local_video +from app.control.account.enums import FeedbackKind +from app.control.model import registry as model_registry +from app.control.model.registry import resolve as resolve_model +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.headers import build_http_headers +from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs +from app.dataplane.reverse.protocol.xai_assets import ( + resolve_asset_reference, + resolve_download_url, +) +from app.dataplane.reverse.protocol.xai_chat import classify_line, raise_for_stream_error +from app.dataplane.reverse.runtime.endpoint_table import CHAT +from app.dataplane.reverse.transport.asset_upload import ( + resolve_uploaded_asset_reference, + upload_from_input, +) +from app.dataplane.reverse.transport.assets import download_asset +from app.dataplane.reverse.transport.media import create_media_post +from ._format import ( + make_chat_response, + make_response_id, + make_stream_chunk, + make_thinking_chunk, +) +from .chat import _fail_sync, _quota_sync, _feedback_kind + +_IMAGE_MEDIA_TYPE = "MEDIA_POST_TYPE_IMAGE" +_VIDEO_MEDIA_TYPE = "MEDIA_POST_TYPE_VIDEO" +_VIDEO_MODEL_NAME = "imagine-video-gen" +_VIDEO_QUALITY = "standard" +_VIDEO_OBJECT = "video" +_VIDEO_JOB_TTL_S = 3600 +_VIDEO_EXTENSION_REF_TYPE = "ORIGINAL_REF_TYPE_VIDEO_EXTENSION" +_SUPPORTED_VIDEO_LENGTHS = frozenset({6, 10, 12, 16, 20}) +_VIDEO_SIZE_MAP: dict[str, tuple[str, str]] = { + "720x1280": ("9:16", "720p"), + "1280x720": ("16:9", "720p"), + "1024x1024": ("1:1", "720p"), + "1024x1792": ("9:16", "720p"), + "1792x1024": ("16:9", "720p"), +} +_PRESET_FLAGS = { + "fun": "--mode=extremely-crazy", + "normal": "--mode=normal", + "spicy": "--mode=extremely-spicy-or-crazy", + "custom": "--mode=custom", +} + + +@dataclass(slots=True) +class _VideoArtifact: + video_url: str + video_post_id: str + asset_id: str + thumbnail_url: str + remixed_from_video_id: str | None = None + + +@dataclass(slots=True) +class _VideoReference: + content_url: str + post_id: str + + +@dataclass(slots=True) +class _VideoJob: + id: str + model: str + prompt: str + seconds: str + size: str + quality: str + created_at: int + status: str = "queued" + progress: int = 0 + completed_at: int | None = None + error: dict[str, Any] | None = None + remixed_from_video_id: str | None = None + video_url: str = "" + content_path: str = "" + + def to_dict(self) -> dict[str, Any]: + payload: dict[str, Any] = { + "id": self.id, + "object": _VIDEO_OBJECT, + "created_at": self.created_at, + "status": self.status, + "model": self.model, + "progress": self.progress, + "prompt": self.prompt, + "seconds": self.seconds, + "size": self.size, + "quality": self.quality, + } + if self.completed_at is not None: + payload["completed_at"] = self.completed_at + if self.error is not None: + payload["error"] = self.error + if self.remixed_from_video_id: + payload["remixed_from_video_id"] = self.remixed_from_video_id + return payload + + +_VIDEO_JOBS: dict[str, _VideoJob] = {} +_VIDEO_JOBS_LOCK = asyncio.Lock() + + +def _build_message(prompt: str, preset: str) -> str: + return f"{prompt} {_PRESET_FLAGS.get(preset, '--mode=custom')}".strip() + + +def _progress_reason(progress: int) -> str: + return f"视频正在生成 {max(0, min(100, int(progress)))}%" + + +def _progress_reason_delta(progress: int) -> str: + return _progress_reason(progress) + "\n" + + +def _coerce_seconds(value: str | int | None) -> int: + if value is None: + return 6 + if isinstance(value, int): + return value + text = str(value).strip() + if not text: + return 6 + try: + return int(text) + except ValueError as exc: + raise ValidationError( + "seconds must be an integer string", param="seconds" + ) from exc + + +def validate_video_length(seconds: int) -> None: + if seconds not in _SUPPORTED_VIDEO_LENGTHS: + allowed = ", ".join(str(item) for item in sorted(_SUPPORTED_VIDEO_LENGTHS)) + raise ValidationError(f"seconds must be one of [{allowed}]", param="seconds") + + +def _resolve_video_size(size: str) -> tuple[str, str]: + normalized = (size or "720x1280").strip() + config = _VIDEO_SIZE_MAP.get(normalized) + if config is None: + allowed = ", ".join(_VIDEO_SIZE_MAP) + raise ValidationError(f"size must be one of [{allowed}]", param="size") + return config + + +def _resolve_video_resolution_name(value: str | None, *, default: str = "720p") -> str: + normalized = (value or default).strip().lower() + if normalized not in {"480p", "720p"}: + raise ValidationError( + "resolution_name must be one of [480p, 720p]", param="resolution_name" + ) + return normalized + + +def _resolve_video_preset(value: str | None, *, default: str = "custom") -> str: + normalized = (value or default).strip().lower() + if normalized not in _PRESET_FLAGS: + allowed = ", ".join(sorted(_PRESET_FLAGS)) + raise ValidationError(f"preset must be one of [{allowed}]", param="preset") + return normalized + + +def _build_segment_lengths(seconds: int) -> list[int]: + if seconds == 6: + return [6] + if seconds == 10: + return [10] + if seconds == 12: + return [6, 6] + if seconds == 16: + return [10, 6] + if seconds == 20: + return [10, 10] + validate_video_length(seconds) + raise AssertionError("unreachable") + + +def _video_create_payload( + *, + prompt: str, + parent_post_id: str, + aspect_ratio: str, + resolution_name: str, + video_length: int, + preset: str, + image_references: list[str] | None = None, +) -> dict[str, Any]: + video_gen_config: dict[str, Any] = { + "parentPostId": parent_post_id, + "aspectRatio": aspect_ratio, + "videoLength": video_length, + "resolutionName": resolution_name, + } + if image_references: + video_gen_config["isVideoEdit"] = False + video_gen_config["isReferenceToVideo"] = True + video_gen_config["imageReferences"] = image_references + return { + "temporary": True, + "modelName": _VIDEO_MODEL_NAME, + "message": _build_message(prompt, preset), + "enableSideBySide": True, + "responseMetadata": { + "experiments": [], + "modelConfigOverride": { + "modelMap": { + "videoGenModelConfig": video_gen_config, + } + }, + }, + } + + +def _video_extend_start_time(seconds: int) -> float: + return round(seconds + (1.0 / 24.0), 6) + + +def _video_extend_payload( + *, + prompt: str, + parent_post_id: str, + extend_post_id: str, + aspect_ratio: str, + resolution_name: str, + video_length: int, + preset: str, + start_time_s: float, +) -> dict[str, Any]: + return { + "temporary": True, + "modelName": _VIDEO_MODEL_NAME, + "message": _build_message(prompt, preset), + "enableSideBySide": True, + "responseMetadata": { + "experiments": [], + "modelConfigOverride": { + "modelMap": { + "videoGenModelConfig": { + "isVideoExtension": True, + "videoExtensionStartTime": start_time_s, + "extendPostId": extend_post_id, + "stitchWithExtendPostId": True, + "originalPrompt": prompt, + "originalPostId": parent_post_id, + "originalRefType": _VIDEO_EXTENSION_REF_TYPE, + "mode": preset, + "aspectRatio": aspect_ratio, + "videoLength": video_length, + "resolutionName": resolution_name, + "parentPostId": parent_post_id, + "isVideoEdit": False, + } + } + }, + }, + } + + +def _extract_streaming_video_response(data: dict[str, Any]) -> dict[str, Any] | None: + result = data.get("result") + if not isinstance(result, dict): + return None + response = result.get("response") + if not isinstance(response, dict): + return None + stream = response.get("streamingVideoGenerationResponse") + return stream if isinstance(stream, dict) else None + + +def _extract_model_response_file_attachments(data: dict[str, Any]) -> list[str]: + result = data.get("result") + if not isinstance(result, dict): + return [] + response = result.get("response") + if not isinstance(response, dict): + return [] + model_response = response.get("modelResponse") + if not isinstance(model_response, dict): + return [] + attachments = model_response.get("fileAttachments") + if not isinstance(attachments, list): + return [] + return [item for item in attachments if isinstance(item, str) and item] + + +async def _stream_video_request( + token: str, + payload: dict[str, Any], + *, + referer: str, + timeout_s: float, +) -> AsyncGenerator[str, None]: + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + headers = build_http_headers( + token, + content_type="application/json", + origin="https://grok.com", + referer=referer, + lease=lease, + ) + kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**kwargs) as session: + response = await session.post( + CHAT, + headers=headers, + data=orjson.dumps(payload), + timeout=timeout_s, + stream=True, + ) + if response.status_code != 200: + body = response.content.decode("utf-8", "replace")[:300] + raise UpstreamError( + f"Video upstream returned {response.status_code}", + status=response.status_code, + body=body, + ) + async for line in response.aiter_lines(): + yield line + + +def _absolutize_video_url(url: str) -> str: + full_url, _, _ = resolve_download_url(url) + return full_url + + +def _is_upstream_asset_content_url(value: str) -> bool: + parsed = urlparse(value) + return ( + parsed.scheme == "https" + and parsed.netloc == "assets.grok.com" + and parsed.path.endswith("/content") + ) + + +async def _prepare_video_reference( + token: str, input_reference: dict[str, Any] +) -> _VideoReference: + file_id = str(input_reference.get("file_id") or "").strip() + image_input = str(input_reference.get("image_url") or "").strip() + + if file_id and image_input: + raise ValidationError( + "input_reference accepts only one of file_id or image_url", + param="input_reference", + ) + if file_id: + raise ValidationError( + "input_reference.file_id is not supported yet", + param="input_reference.file_id", + ) + if not image_input: + raise ValidationError( + "input_reference.image_url is required", param="input_reference.image_url" + ) + + if _is_upstream_asset_content_url(image_input): + content_url = image_input + else: + try: + uploaded_file_id, uploaded_file_uri = await upload_from_input( + token, image_input + ) + content_url = resolve_uploaded_asset_reference( + token, uploaded_file_id, uploaded_file_uri + ) + except ValidationError as exc: + raise ValidationError( + exc.message, param="input_reference.image_url" + ) from exc + except UpstreamError as exc: + raise UpstreamError( + f"Video input reference upload failed: {exc.message}", + status=exc.status, + body=exc.details.get("body", ""), + ) from exc + except Exception as exc: + raise UpstreamError(f"Video input reference upload failed: {exc}") from exc + + post = await create_media_post( + token, + media_type=_IMAGE_MEDIA_TYPE, + media_url=content_url, + prompt="", + referer="https://grok.com/imagine", + ) + post_data = post.get("post") + if not isinstance(post_data, dict): + raise UpstreamError( + "Video image reference create-post returned no post payload" + ) + post_id = str(post_data.get("id") or "").strip() + if not post_id: + raise UpstreamError("Video image reference create-post returned no post id") + return _VideoReference(content_url=content_url, post_id=post_id) + + +async def _prepare_video_references( + token: str, + input_references: list[dict[str, Any]], +) -> list[_VideoReference]: + """Upload multiple video references concurrently and preserve order.""" + tasks = [ + _prepare_video_reference(token, ref) + for ref in input_references + ] + results = await asyncio.gather(*tasks, return_exceptions=True) + failures: list[tuple[int, BaseException]] = [ + (index, result) + for index, result in enumerate(results) + if isinstance(result, BaseException) + ] + if failures: + index, exc = failures[0] + message = f"Video input reference {index + 1} failed: {_exception_message(exc)}" + if len(failures) > 1: + message += f" ({len(failures)} references failed)" + if isinstance(exc, ValidationError): + raise ValidationError(message, param=exc.param) from exc + if isinstance(exc, UpstreamError): + raise UpstreamError( + message, + status=exc.status, + body=exc.details.get("body", ""), + ) from exc + raise UpstreamError(message) from exc + + return [r for r in results if isinstance(r, _VideoReference)] + + +def _exception_message(exc: BaseException) -> str: + if isinstance(exc, BaseExceptionGroup): + messages = [ + _exception_message(child) + for child in exc.exceptions + if not isinstance(child, asyncio.CancelledError) + ] + return "; ".join(message for message in messages if message) or str(exc) + if isinstance(exc, AppError): + return exc.message + return str(exc) + + +async def _collect_video_segment( + *, + token: str, + payload: dict[str, Any], + referer: str, + timeout_s: float, + progress_cb: Callable[[int], Awaitable[None]] | None = None, +) -> _VideoArtifact: + final_url = "" + final_asset_id = "" + final_thumbnail = "" + video_post_id = "" + stream_data_items: list[str] = [] + + async for line in _stream_video_request( + token, + payload, + referer=referer, + timeout_s=timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + stream_data_items.append(data) + try: + obj = orjson.loads(data) + except Exception: + continue + raise_for_stream_error(obj) + + stream = _extract_streaming_video_response(obj) + if stream: + try: + progress = int(stream.get("progress") or 0) + except (TypeError, ValueError): + progress = 0 + if progress_cb is not None: + await progress_cb(progress) + + video_post_id = str( + stream.get("videoPostId") + or stream.get("videoId") + or video_post_id + or "" + ).strip() + + if progress >= 100 and not stream.get("moderated"): + raw_url = stream.get("videoUrl") + asset_id = stream.get("assetId") + thumbnail = stream.get("thumbnailImageUrl") + if isinstance(raw_url, str) and raw_url: + final_url = _absolutize_video_url(raw_url) + if isinstance(asset_id, str) and asset_id: + final_asset_id = asset_id + if isinstance(thumbnail, str) and thumbnail: + final_thumbnail = _absolutize_video_url(thumbnail) + + attachments = _extract_model_response_file_attachments(obj) + if attachments and not final_asset_id: + final_asset_id = attachments[0] + + if not final_url and final_asset_id: + final_url = resolve_asset_reference(final_asset_id, "", user_id=None) or "" + + if not final_url and final_asset_id: + raise UpstreamError( + "Video segment returned only assetId without a resolvable URL", + body="\n".join(stream_data_items), + ) + if not final_url: + raise UpstreamError( + "Video generation returned no final video URL", + body="\n".join(stream_data_items), + ) + + return _VideoArtifact( + video_url=final_url, + video_post_id=video_post_id or final_asset_id, + asset_id=final_asset_id, + thumbnail_url=final_thumbnail, + ) + + +async def _download_video_bytes(token: str, url: str) -> tuple[bytes, str]: + try: + stream, content_type = await download_asset(token, url) + chunks: list[bytes] = [] + async for chunk in stream: + chunks.append(chunk) + except UpstreamError: + raise + except Exception as exc: + raise UpstreamError(f"Video download failed: {exc}") from exc + raw = b"".join(chunks) + if not raw: + raise UpstreamError("Video download returned empty content", status=502) + if raw.lstrip()[:1] in {b"<", b"{"}: + raise UpstreamError("Video download returned non-video content", status=502) + return raw, (content_type or "video/mp4") + + +def _save_video_bytes(raw: bytes, file_id: str) -> Path: + return save_local_video(raw, file_id) + + +def _local_video_url(file_id: str) -> str: + app_url = get_config().get_str("app.app_url", "").rstrip("/") + return ( + f"{app_url}/v1/files/video?id={file_id}" + if app_url + else f"/v1/files/video?id={file_id}" + ) + + +def _normalize_video_format(value: str | None) -> str: + fmt = (value or "grok_url").strip().lower() + if fmt not in {"grok_url", "local_url", "grok_html", "local_html"}: + raise ValidationError( + "video_format must be one of [grok_url, local_url, grok_html, local_html]", + param="features.video_format", + ) + return fmt + + +def _render_video_html(url: str) -> str: + safe_url = html.escape(url, quote=True) + return f'' + + +async def _resolve_video_output(*, token: str, url: str, file_id: str) -> str: + fmt = _normalize_video_format( + get_config().get_str("features.video_format", "grok_url") + ) + if fmt == "grok_url": + return url + if fmt == "grok_html": + return _render_video_html(url) + + try: + raw, _mime = await _download_video_bytes(token, url) + await asyncio.to_thread(_save_video_bytes, raw, file_id) + except Exception as exc: + logger.debug("video download fallback_to=upstream_url error={}", exc) + return url if fmt == "local_url" else _render_video_html(url) + + local_url = _local_video_url(file_id) + return local_url if fmt == "local_url" else _render_video_html(local_url) + + +async def _generate_video_with_token( + *, + token: str, + prompt: str, + aspect_ratio: str, + resolution_name: str, + seconds: int, + preset: str, + timeout_s: float, + input_references: list[dict[str, Any]] | None = None, + progress_cb: Callable[[int], Awaitable[None]] | None = None, +) -> _VideoArtifact: + references: list[_VideoReference] = [] + if input_references: + references = await _prepare_video_references(token, input_references) + parent_post_id = references[0].post_id + else: + post = await create_media_post( + token, + media_type=_VIDEO_MEDIA_TYPE, + prompt=prompt, + referer="https://grok.com/imagine", + ) + post_data = post.get("post") + if not isinstance(post_data, dict): + raise UpstreamError("Video create-post returned no post payload") + parent_post_id = str(post_data.get("id") or "").strip() + if not parent_post_id: + raise UpstreamError("Video create-post returned no post id") + + segments = _build_segment_lengths(seconds) + total_segments = len(segments) + artifact: _VideoArtifact | None = None + extend_post_id = parent_post_id + elapsed_seconds = 0 + + for index, segment_length in enumerate(segments): + if index == 0: + payload = _video_create_payload( + prompt=prompt, + parent_post_id=parent_post_id, + aspect_ratio=aspect_ratio, + resolution_name=resolution_name, + video_length=segment_length, + preset=preset, + image_references=[r.content_url for r in references] + if references + else None, + ) + referer = "https://grok.com/imagine" + else: + payload = _video_extend_payload( + prompt=prompt, + parent_post_id=parent_post_id, + extend_post_id=extend_post_id, + aspect_ratio=aspect_ratio, + resolution_name=resolution_name, + video_length=segment_length, + preset=preset, + start_time_s=_video_extend_start_time(elapsed_seconds), + ) + referer = f"https://grok.com/imagine/post/{parent_post_id}" + + async def _segment_progress(progress: int) -> None: + if progress_cb is None: + return + scaled = int( + ((index + (max(0, min(100, progress)) / 100.0)) / total_segments) * 100 + ) + await progress_cb(scaled) + + artifact = await _collect_video_segment( + token=token, + payload=payload, + referer=referer, + timeout_s=timeout_s, + progress_cb=_segment_progress if progress_cb is not None else None, + ) + if index == 0 and total_segments > 1: + artifact.remixed_from_video_id = artifact.video_post_id or parent_post_id + extend_post_id = artifact.video_post_id or artifact.asset_id or parent_post_id + elapsed_seconds += segment_length + + if artifact is None: + raise UpstreamError("Video generation returned no artifact") + return artifact + + +async def _run_video_generation( + *, + model: str, + prompt: str, + aspect_ratio: str, + resolution_name: str, + seconds: int, + preset: str = "custom", + input_references: list[dict[str, Any]] | None = None, + progress_cb: Callable[[int], Awaitable[None]] | None = None, +) -> _VideoArtifact: + async def _runner(token: str, timeout_s: float) -> _VideoArtifact: + return await _generate_video_with_token( + token=token, + prompt=prompt, + aspect_ratio=aspect_ratio, + resolution_name=resolution_name, + seconds=seconds, + preset=preset, + timeout_s=timeout_s, + input_references=input_references, + progress_cb=progress_cb, + ) + + return await _run_video_with_account(model=model, runner=_runner) + + +async def _run_video_with_account( + *, + model: str, + runner: Callable[[str, float], Awaitable[Any]], +) -> Any: + cfg = get_config() + timeout_s = cfg.get_float("video.timeout", 180.0) + spec = resolve_model(model) + if not spec.is_video(): + raise ValidationError(f"Model {model!r} is not a video model", param="model") + + from app.dataplane.account import _directory as _acct_dir + + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + acct = await _acct_dir.reserve( + pool_candidates=spec.pool_candidates(), + mode_id=int(spec.mode_id), + now_s_override=now_s(), + ) + if acct is None: + raise RateLimitError("No available accounts for video generation") + + token = acct.token + success = False + fail_exc: BaseException | None = None + try: + artifact = await runner(token, timeout_s) + success = True + return artifact + except BaseException as exc: + fail_exc = exc + raise + finally: + await _acct_dir.release(acct) + kind = ( + FeedbackKind.SUCCESS + if success + else _feedback_kind(fail_exc) + if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id), fail_exc)) + + +async def _put_video_job(job: _VideoJob) -> None: + async with _VIDEO_JOBS_LOCK: + _VIDEO_JOBS[job.id] = job + + +async def get_video_job(video_id: str) -> _VideoJob | None: + async with _VIDEO_JOBS_LOCK: + return _VIDEO_JOBS.get(video_id) + + +async def _expire_video_job(video_id: str, ttl_s: int = _VIDEO_JOB_TTL_S) -> None: + await asyncio.sleep(ttl_s) + async with _VIDEO_JOBS_LOCK: + _VIDEO_JOBS.pop(video_id, None) + + +async def _set_job_status( + job: _VideoJob, *, status: str, progress: int | None = None +) -> None: + async with _VIDEO_JOBS_LOCK: + job.status = status + if progress is not None: + job.progress = max(0, min(100, progress)) + + +def _job_error_payload(message: str) -> dict[str, Any]: + return {"code": "video_generation_failed", "message": message} + + +async def _run_video_job( + job: _VideoJob, + *, + size: str, + resolution_name: str | None, + prompt: str, + seconds: int, + preset: str | None, + input_references: list[dict[str, Any]] | None = None, +) -> None: + try: + await _set_job_status(job, status="in_progress", progress=1) + aspect_ratio, default_resolution_name = _resolve_video_size(size) + resolved_resolution_name = _resolve_video_resolution_name( + resolution_name, + default=default_resolution_name, + ) + resolved_preset = _resolve_video_preset(preset) + spec = resolve_model(job.model) + + from app.dataplane.account import _directory as _acct_dir + + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + acct = await _acct_dir.reserve( + pool_candidates=spec.pool_candidates(), + mode_id=int(spec.mode_id), + now_s_override=now_s(), + ) + if acct is None: + raise RateLimitError("No available accounts for video generation") + + token = acct.token + success = False + fail_exc: BaseException | None = None + try: + cfg = get_config() + timeout_s = cfg.get_float("video.timeout", 180.0) + + async def _progress(progress: int) -> None: + await _set_job_status( + job, status="in_progress", progress=max(1, progress) + ) + + artifact = await _generate_video_with_token( + token=token, + prompt=prompt, + aspect_ratio=aspect_ratio, + resolution_name=resolved_resolution_name, + seconds=seconds, + preset=resolved_preset, + timeout_s=timeout_s, + input_references=input_references, + progress_cb=_progress, + ) + raw, _mime = await _download_video_bytes(token, artifact.video_url) + success = True + except BaseException as exc: + fail_exc = exc + raise + finally: + await _acct_dir.release(acct) + kind = ( + FeedbackKind.SUCCESS + if success + else _feedback_kind(fail_exc) + if fail_exc + else FeedbackKind.SERVER_ERROR + ) + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id), fail_exc)) + + path = _save_video_bytes(raw, job.id) + async with _VIDEO_JOBS_LOCK: + job.status = "completed" + job.progress = 100 + job.completed_at = int(time.time()) + job.video_url = artifact.video_url + job.content_path = str(path) + job.remixed_from_video_id = artifact.remixed_from_video_id + except Exception as exc: + logger.exception("video job failed: job_id={} error={}", job.id, exc) + async with _VIDEO_JOBS_LOCK: + job.status = "failed" + job.error = _job_error_payload(_exception_message(exc)) + + +async def create_video( + *, + model: str, + prompt: str, + seconds: str | int | None = None, + size: str | None = None, + resolution_name: str | None = None, + preset: str | None = None, + input_references: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + spec = model_registry.get(model) + if spec is None or not spec.enabled or not spec.is_video(): + raise ValidationError(f"Model {model!r} is not a video model", param="model") + + cleaned_prompt = (prompt or "").strip() + if not cleaned_prompt: + raise ValidationError("prompt cannot be empty", param="prompt") + + normalized_seconds = _coerce_seconds(seconds) + validate_video_length(normalized_seconds) + normalized_size = (size or "720x1280").strip() + _aspect_ratio, default_resolution_name = _resolve_video_size(normalized_size) + _resolve_video_resolution_name(resolution_name, default=default_resolution_name) + _resolve_video_preset(preset) + + job = _VideoJob( + id=f"video_{uuid.uuid4().hex}", + model=model, + prompt=cleaned_prompt, + seconds=str(normalized_seconds), + size=normalized_size, + quality=_VIDEO_QUALITY, + created_at=int(time.time()), + ) + await _put_video_job(job) + asyncio.create_task( + _run_video_job( + job, + size=normalized_size, + resolution_name=resolution_name, + prompt=cleaned_prompt, + seconds=normalized_seconds, + preset=preset, + input_references=input_references, + ) + ) + asyncio.create_task(_expire_video_job(job.id)) + return job.to_dict() + + +async def retrieve(video_id: str) -> dict[str, Any]: + job = await get_video_job(video_id) + if job is None: + raise ValidationError(f"Video {video_id!r} not found", param="video_id") + return job.to_dict() + + +async def content_path(video_id: str) -> Path: + job = await get_video_job(video_id) + if job is None: + raise ValidationError(f"Video {video_id!r} not found", param="video_id") + if job.status != "completed" or not job.content_path: + raise AppError( + "Video content is not ready yet", + kind=ErrorKind.VALIDATION, + code="video_not_ready", + status=409, + ) + path = Path(job.content_path) + if not path.exists(): + raise ValidationError( + f"Video content for {video_id!r} not found", param="video_id" + ) + return path + + +def _extract_video_prompt_and_reference( + messages: list[dict], +) -> tuple[str, list[dict[str, Any]] | None]: + prompt = "" + reference_urls: list[str] = [] + + for msg in reversed(messages): + content = msg.get("content", "") + if isinstance(content, str) and content.strip(): + prompt = content.strip() + if prompt: + break + continue + if not isinstance(content, list): + continue + + text_parts: list[str] = [] + block_references: list[str] = [] + for item in content: + if not isinstance(item, dict): + continue + item_type = item.get("type") + if item_type == "text": + text = str(item.get("text") or "").strip() + if text: + text_parts.append(text) + elif item_type == "image_url": + image_url = item.get("image_url") + if isinstance(image_url, dict): + url = str(image_url.get("url") or "").strip() + if url: + block_references.append(url) + elif isinstance(image_url, str) and image_url.strip(): + block_references.append(image_url.strip()) + + if text_parts: + prompt = " ".join(text_parts) + if block_references and not reference_urls: + reference_urls = block_references + if prompt: + break + + if not prompt: + raise ValidationError("Video prompt cannot be empty", param="messages") + + input_references: list[dict[str, Any]] | None = None + if reference_urls: + input_references = [{"image_url": url} for url in reference_urls[:7]] + return prompt, input_references + + +async def completions( + *, + model: str, + messages: list[dict], + stream: bool | None = None, + seconds: int = 6, + size: str = "720x1280", + resolution_name: str | None = None, + preset: str | None = None, +) -> dict | AsyncGenerator[str, None]: + """Chat-completions video support on top of the same core flow.""" + validate_video_length(seconds) + aspect_ratio, default_resolution_name = _resolve_video_size(size) + resolved_resolution_name = _resolve_video_resolution_name( + resolution_name, + default=default_resolution_name, + ) + resolved_preset = _resolve_video_preset(preset) + prompt, input_references = _extract_video_prompt_and_reference(messages) + + cfg = get_config() + is_stream = stream if stream is not None else cfg.get_bool("features.stream", False) + response_id = make_response_id() + + async def _run(progress_cb: Callable[[int], Awaitable[None]] | None = None) -> str: + async def _runner(token: str, timeout_s: float) -> str: + artifact = await _generate_video_with_token( + token=token, + prompt=prompt, + aspect_ratio=aspect_ratio, + resolution_name=resolved_resolution_name, + seconds=seconds, + preset=resolved_preset, + timeout_s=timeout_s, + input_references=input_references, + progress_cb=progress_cb, + ) + file_id = hashlib.sha1(artifact.video_url.encode("utf-8")).hexdigest()[:32] + return await _resolve_video_output( + token=token, + url=artifact.video_url, + file_id=file_id, + ) + + return await _run_video_with_account(model=model, runner=_runner) + + if is_stream: + + async def _sse() -> AsyncGenerator[str, None]: + queue: asyncio.Queue[int] = asyncio.Queue() + last_progress = -1 + + async def _progress(progress: int) -> None: + await queue.put(max(0, min(100, progress))) + + task = asyncio.create_task(_run(progress_cb=_progress)) + while not task.done() or not queue.empty(): + try: + progress = await asyncio.wait_for(queue.get(), timeout=0.1) + except asyncio.TimeoutError: + continue + if progress > last_progress: + last_progress = progress + chunk = make_thinking_chunk( + response_id, model, _progress_reason_delta(progress) + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + content = await task + chunk = make_stream_chunk(response_id, model, content) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + final = make_stream_chunk(response_id, model, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + + return _sse() + + progress_updates: list[str] = [] + + async def _progress(progress: int) -> None: + reason = _progress_reason(progress) + if not progress_updates or progress_updates[-1] != reason: + progress_updates.append(reason) + + content = await _run(progress_cb=_progress) + reasoning = "\n".join(progress_updates) if progress_updates else None + return make_chat_response( + model, + content, + prompt_content=prompt, + response_id=response_id, + reasoning_content=reasoning, + ) + + +__all__ = [ + "create_video", + "retrieve", + "content_path", + "validate_video_length", + "completions", + "_build_segment_lengths", + "_resolve_video_size", +] diff --git a/app/products/web/__init__.py b/app/products/web/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f84059f3e308dcbb63063470c330864c4526ab8 --- /dev/null +++ b/app/products/web/__init__.py @@ -0,0 +1,5 @@ +"""Web product — unified frontend (admin + webui pages & API).""" + +from .router import router + +__all__ = ["router"] diff --git a/app/products/web/admin/__init__.py b/app/products/web/admin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88093af783f0ae363dd3dec6a34e32b7736d9773 --- /dev/null +++ b/app/products/web/admin/__init__.py @@ -0,0 +1,268 @@ +"""Admin API — router aggregator, shared DI, lightweight endpoints. + +All admin endpoints live under ``/admin/api`` with ``verify_admin_key`` guard. +Heavy handlers are split into ``tokens`` and ``batch`` sub-modules. +""" + +import re +from typing import TYPE_CHECKING, Any + +import orjson +from fastapi import APIRouter, Depends, Request +from fastapi.responses import Response +from pydantic import RootModel + +from app.control.account.backends.factory import get_repository_backend +from app.platform.auth.middleware import verify_admin_key +from app.platform.config.snapshot import config +from app.platform.errors import AppError, ErrorKind, ValidationError +from app.platform.logging.logger import logger, reload_file_logging +from app.platform.storage import reconcile_local_media_cache_async + +if TYPE_CHECKING: + from app.control.account.refresh import AccountRefreshService + from app.control.account.repository import AccountRepository + +# --------------------------------------------------------------------------- +# Shared DI dependencies — inject via Depends, no try/except per call +# --------------------------------------------------------------------------- + +_CFG_CHAR_REPLACEMENTS = str.maketrans( + { + "\u2010": "-", + "\u2011": "-", + "\u2012": "-", + "\u2013": "-", + "\u2014": "-", + "\u2212": "-", + "\u2018": "'", + "\u2019": "'", + "\u201c": '"', + "\u201d": '"', + "\u00a0": " ", + "\u2007": " ", + "\u202f": " ", + "\u200b": "", + "\u200c": "", + "\u200d": "", + "\ufeff": "", + } +) + +_STARTUP_ONLY_CONFIG_PREFIXES = ( + "account.storage", + "account.local", + "account.redis", + "account.mysql", + "account.postgresql", +) + + +class ConfigPatchRequest(RootModel[dict[str, Any]]): + """Loose config patch payload with explicit root typing.""" + + +def _sanitize_text(value: Any, *, remove_all_spaces: bool = False) -> str: + text = "" if value is None else str(value) + text = text.translate(_CFG_CHAR_REPLACEMENTS) + if remove_all_spaces: + text = re.sub(r"\s+", "", text) + else: + text = text.strip() + return text.encode("latin-1", errors="ignore").decode("latin-1") + + +def _sanitize_proxy_config(payload: dict[str, Any]) -> dict[str, Any]: + proxy = payload.get("proxy") + if not isinstance(proxy, dict): + return dict(payload) + + sanitized = dict(proxy) + changed = False + + def _sanitize_fields(target: dict[str, Any]) -> tuple[dict[str, Any], bool]: + normalized = dict(target) + local_changed = False + for key, strip_spaces in [ + ("user_agent", False), + ("cf_cookies", False), + ("cf_clearance", True), + ]: + if key not in normalized: + continue + raw = normalized[key] + val = _sanitize_text(raw, remove_all_spaces=strip_spaces) + if val != raw: + normalized[key] = val + local_changed = True + return normalized, local_changed + + sanitized, changed = _sanitize_fields(sanitized) + + clearance = sanitized.get("clearance") + if isinstance(clearance, dict): + sanitized_clearance, clearance_changed = _sanitize_fields(clearance) + if clearance_changed: + sanitized["clearance"] = sanitized_clearance + changed = True + + if not changed: + return dict(payload) + + logger.warning("admin config payload sanitized before save: section=proxy") + result = dict(payload) + result["proxy"] = sanitized + return result + + +def _iter_patch_paths(value: Any, prefix: str = ""): + if isinstance(value, dict): + for key, child in value.items(): + path = f"{prefix}.{key}" if prefix else str(key) + if isinstance(child, dict): + yield from _iter_patch_paths(child, path) + else: + yield path + + +def _ensure_runtime_patch_allowed(payload: dict[str, Any]) -> None: + for path in _iter_patch_paths(payload): + for blocked in _STARTUP_ONLY_CONFIG_PREFIXES: + if path == blocked or path.startswith(f"{blocked}."): + raise ValidationError( + "Storage config is startup-only and must be set via env", + param=path, + code="startup_only_config", + ) + + +def _patch_touches_prefix(payload: dict[str, Any], prefix: str) -> bool: + return any( + path == prefix or path.startswith(f"{prefix}.") + for path in _iter_patch_paths(payload) + ) + + +def get_repo(request: Request) -> "AccountRepository": + """Resolve the singleton AccountRepository from app state.""" + return request.app.state.repository + + +def get_refresh_svc(request: Request) -> "AccountRefreshService": + """Resolve the singleton AccountRefreshService from app state.""" + return request.app.state.refresh_service + + +# --------------------------------------------------------------------------- +# Router +# --------------------------------------------------------------------------- + +router = APIRouter(prefix="/admin/api", dependencies=[Depends(verify_admin_key)]) +_TAG_ADMIN_SYSTEM = "Admin - System" + +# Mount sub-modules +from .tokens import router as _tokens_router # noqa: E402 +from .batch import router as _batch_router # noqa: E402 +from .assets import router as _assets_router # noqa: E402 +from .cache import router as _cache_router # noqa: E402 + +router.include_router(_tokens_router) +router.include_router(_batch_router) +router.include_router(_assets_router) +router.include_router(_cache_router) + + +# --------------------------------------------------------------------------- +# Lightweight inline endpoints (no separate file needed) +# --------------------------------------------------------------------------- + + +@router.get("/verify", tags=[_TAG_ADMIN_SYSTEM]) +async def admin_verify(): + return {"status": "success"} + + +@router.get("/config", tags=[_TAG_ADMIN_SYSTEM]) +async def get_config_endpoint(): + return Response( + content=orjson.dumps(config.raw()), + media_type="application/json", + ) + + +@router.post("/config", tags=[_TAG_ADMIN_SYSTEM]) +async def update_config(req: ConfigPatchRequest): + from app.control.account.runtime import reconcile_refresh_runtime + + patch = _sanitize_proxy_config(req.root) + _ensure_runtime_patch_allowed(patch) + cache_local_changed = _patch_touches_prefix(patch, "cache.local") + await config.update(patch) + # config.update() only writes to the backend and invalidates the in-memory + # snapshot (_version = None); it does not refresh the data. load() is + # required here so that get_str/get_int calls below return the new values. + await config.load() + reload_file_logging( + file_level=config.get_str("logging.file_level", "") or None, + max_files=config.get_int("logging.max_files", 7), + ) + if cache_local_changed: + await reconcile_local_media_cache_async() + strategy_name = reconcile_refresh_runtime() + return { + "status": "success", + "message": "配置已更新", + "selection_strategy": strategy_name, + } + + +@router.get("/storage", tags=[_TAG_ADMIN_SYSTEM]) +async def get_storage_mode(): + return {"type": get_repository_backend()} + + +@router.get("/status", tags=[_TAG_ADMIN_SYSTEM]) +async def runtime_status(): + from app.control.account.runtime import reconcile_refresh_runtime + from app.dataplane.account import _directory + + if _directory is None: + raise AppError( + "Account directory not initialised", + kind=ErrorKind.SERVER, + code="directory_not_initialised", + status=503, + ) + strategy_name = reconcile_refresh_runtime() + return Response( + content=orjson.dumps( + { + "status": "ok", + "size": _directory.size, + "revision": _directory.revision, + "selection_strategy": strategy_name, + } + ), + media_type="application/json", + ) + + +@router.post("/sync", tags=[_TAG_ADMIN_SYSTEM]) +async def force_sync(): + from app.dataplane.account import _directory + + if _directory is None: + raise AppError( + "Account directory not initialised", + kind=ErrorKind.SERVER, + code="directory_not_initialised", + status=503, + ) + changed = await _directory.sync_if_changed() + return Response( + content=orjson.dumps({"changed": changed, "revision": _directory.revision}), + media_type="application/json", + ) + + +__all__ = ["router", "get_repo", "get_refresh_svc"] diff --git a/app/products/web/admin/assets.py b/app/products/web/admin/assets.py new file mode 100644 index 0000000000000000000000000000000000000000..77c99ee3feed9e3d1883e82fc2fff86cdd5f81c6 --- /dev/null +++ b/app/products/web/admin/assets.py @@ -0,0 +1,140 @@ +"""Admin online-asset management — list, delete, clear per token.""" + +import asyncio +from typing import TYPE_CHECKING + +import orjson +from fastapi import APIRouter, Depends +from fastapi.responses import Response +from pydantic import BaseModel + +from app.control.account.commands import ListAccountsQuery +from app.control.account.invalid_credentials import mark_account_invalid_credentials +from app.control.account.state_machine import is_manageable +from app.platform.errors import UpstreamError + +if TYPE_CHECKING: + from app.control.account.repository import AccountRepository + +from . import get_repo + +router = APIRouter(prefix="/assets", tags=["Admin - Assets"]) + + +def _mask(token: str) -> str: + return f"{token[:8]}...{token[-8:]}" if len(token) > 20 else token + + +def _asset_row(token: str, items: list[dict], *, error: str | None = None) -> dict: + return { + "token": token, + "masked": _mask(token), + "count": len(items), + "assets": [ + { + "id": item.get("id") or item.get("assetId") or "", + "name": item.get("fileName") or item.get("name") or "", + "file_path": item.get("filePath") or item.get("file_path") or "", + "content_type": item.get("contentType") or item.get("content_type") or "", + "size": item.get("fileSize") or item.get("size") or 0, + "created_at": item.get("createdAt") or item.get("created_at") or "", + } + for item in items + ], + "error": error, + } + + +async def _list_all_tokens(repo: "AccountRepository") -> list[str]: + page_num, tokens = 1, [] + while True: + page = await repo.list_accounts(ListAccountsQuery(page=page_num, page_size=2000)) + tokens.extend(r.token for r in page.items if is_manageable(r)) + if page_num * 2000 >= page.total: + break + page_num += 1 + return tokens + + +class DeleteItemRequest(BaseModel): + token: str + asset_id: str + + +class ClearTokenRequest(BaseModel): + token: str + + +@router.get("") +async def list_all_assets(repo: "AccountRepository" = Depends(get_repo)): + """Fetch asset lists for all tokens concurrently.""" + from app.dataplane.reverse.transport.assets import list_assets + + tokens = await _list_all_tokens(repo) + if not tokens: + return Response( + content=orjson.dumps({"tokens": [], "total_assets": 0}), + media_type="application/json", + ) + + async def _fetch_row(token: str) -> dict: + try: + resp = await list_assets(token) + except Exception as exc: + await mark_account_invalid_credentials(repo, token, exc, source="asset list") + return _asset_row(token, [], error=str(exc)) + + items = resp.get("assets", resp.get("items", [])) + return _asset_row(token, items) + + results = await asyncio.gather(*[_fetch_row(t) for t in tokens]) + total = sum(r["count"] for r in results) + return Response( + content=orjson.dumps({"tokens": list(results), "total_assets": total}), + media_type="application/json", + ) + + +@router.post("/delete-item") +async def delete_item(req: DeleteItemRequest, repo: "AccountRepository" = Depends(get_repo)): + """Delete a single asset by token + asset_id.""" + from app.dataplane.reverse.transport.assets import delete_asset + + try: + await delete_asset(req.token, req.asset_id) + return {"status": "success"} + except Exception as exc: + await mark_account_invalid_credentials(repo, req.token, exc, source="asset delete") + raise UpstreamError(str(exc)) from exc + + +@router.post("/clear-token") +async def clear_token_assets(req: ClearTokenRequest, repo: "AccountRepository" = Depends(get_repo)): + """Delete all assets for one token concurrently.""" + from app.dataplane.reverse.transport.assets import delete_asset, list_assets + + try: + resp = await list_assets(req.token) + items = resp.get("assets", resp.get("items", [])) + + async def _delete_one(item: dict) -> int: + asset_id = item.get("id") or item.get("assetId") + if not asset_id: + return 0 + await delete_asset(req.token, asset_id) + return 1 + + results = await asyncio.gather(*[_delete_one(item) for item in items], return_exceptions=True) + for result in results: + if not isinstance(result, Exception): + continue + if await mark_account_invalid_credentials(repo, req.token, result, source="asset clear"): + raise result + deleted = sum(result for result in results if isinstance(result, int)) + return {"status": "success", "deleted": deleted} + except Exception as exc: + await mark_account_invalid_credentials(repo, req.token, exc, source="asset clear") + raise UpstreamError(str(exc)) from exc + + +__all__ = ["router"] diff --git a/app/products/web/admin/batch.py b/app/products/web/admin/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..9f852745f70b3697e58a1364748d71fc15816171 --- /dev/null +++ b/app/products/web/admin/batch.py @@ -0,0 +1,391 @@ +"""Admin batch operations + SSE progress streaming. + +Performance notes: + - Uses ``run_batch`` for bounded-concurrency parallel execution + (replaces old sequential for-loop) + - Async mode: background task with SSE fan-out via AsyncTask + - Sync mode: concurrent execution, single JSON response +""" + +import asyncio +from typing import TYPE_CHECKING, Any, Callable, Awaitable + +import orjson +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import Response, StreamingResponse +from pydantic import BaseModel + +from app.platform.config.snapshot import get_config +from app.platform.errors import AppError, ErrorKind, UpstreamError, ValidationError +from app.platform.logging.logger import logger +from app.platform.runtime.batch import run_batch +from app.platform.runtime.task import create_task, expire_task, get_task +from app.control.account.commands import AccountPatch, ListAccountsQuery +from app.control.account.state_machine import is_manageable + +if TYPE_CHECKING: + from app.control.account.refresh import AccountRefreshService + from app.control.account.repository import AccountRepository + +from . import get_refresh_svc, get_repo + +router = APIRouter(prefix="/batch", tags=["Admin - Batch"]) +_MAX_BATCH_CONCURRENCY = 80 + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _concurrency(override: int | None, config_key: str, fallback: int = 50) -> int: + """Resolve effective concurrency: query-param → config → fallback.""" + if override is not None: + return min(max(1, override), _MAX_BATCH_CONCURRENCY) + v = get_config(config_key, fallback) + try: + resolved = int(v) + except (TypeError, ValueError): + resolved = fallback + return min(max(1, resolved), _MAX_BATCH_CONCURRENCY) + + +def _mask(token: str) -> str: + return f"{token[:8]}...{token[-8:]}" if len(token) > 20 else token + + +async def _list_all_tokens(repo: "AccountRepository") -> list[str]: + page_num, tokens = 1, [] + while True: + page = await repo.list_accounts(ListAccountsQuery(page=page_num, page_size=2000)) + tokens.extend(r.token for r in page.items if is_manageable(r)) + if page_num >= page.total_pages or not page.items: + break + page_num += 1 + return tokens + + +async def _filter_manageable_tokens(repo: "AccountRepository", tokens: list[str]) -> list[str]: + unique_tokens = list(dict.fromkeys(tokens)) + records = await repo.get_accounts(unique_tokens) + by_token = {r.token: r for r in records} + return [token for token in unique_tokens if (record := by_token.get(token)) and is_manageable(record)] + + +def _json(data: Any, status_code: int = 200) -> Response: + return Response(content=orjson.dumps(data), media_type="application/json", status_code=status_code) + + +class BatchRequest(BaseModel): + tokens: list[str] = [] + + +# --------------------------------------------------------------------------- +# Dispatch engine — sync (run_batch) or async (background task + SSE) +# --------------------------------------------------------------------------- + +async def _dispatch( + tokens: list[str], + handler: Callable[[str], Awaitable[dict]], + *, + use_async: bool, + concurrency: int = 10, + repo: "AccountRepository | None" = None, +) -> Response: + if use_async: + return await _dispatch_async(tokens, handler, concurrency) + return await _dispatch_sync(tokens, handler, concurrency, repo) + + +async def _dispatch_sync( + tokens: list[str], + handler: Callable[[str], Awaitable[dict]], + concurrency: int, + repo: "AccountRepository | None" = None, +) -> Response: + """Concurrent execution, collect all results, return at once.""" + results: dict[str, Any] = {} + ok_c = fail_c = 0 + failed_tokens: list[str] = [] + + async def _wrapped(token: str) -> tuple[str, dict | None, str | None]: + try: + data = await handler(token) + return token, data, None + except Exception as exc: + return token, None, str(exc) + + raw = await run_batch(tokens, _wrapped, concurrency=concurrency) + for token, data, err in raw: + key = _mask(token) + if err is None: + ok_c += 1 + results[key] = data + else: + fail_c += 1 + failed_tokens.append(token) + results[key] = {"error": err} + + # 批量查询失败 token 的状态,统计凭证失效数量 + expired_c = 0 + if repo and failed_tokens: + from app.control.account.enums import AccountStatus + records = await repo.get_accounts(failed_tokens) + expired_c = sum(1 for r in records if r.status == AccountStatus.EXPIRED) + + return _json({ + "status": "success", + "summary": { + "total": len(tokens), + "ok": ok_c, + "fail": fail_c, + "expired": expired_c, + "transient": fail_c - expired_c, + }, + "results": results, + }) + + +async def _dispatch_async( + tokens: list[str], + handler: Callable[[str], Awaitable[dict]], + concurrency: int, +) -> Response: + """Background task with per-item progress via AsyncTask SSE.""" + task = create_task(len(tokens)) + + async def _run() -> None: + try: + results: dict[str, Any] = {} + ok_c = fail_c = 0 + + async def _one(token: str) -> None: + nonlocal ok_c, fail_c + if task.cancelled: + return + masked = _mask(token) + try: + if task.cancelled: + return + data = await handler(token) + ok_c += 1 + results[masked] = data + task.record(True, item=masked, detail=data) + except Exception as exc: + fail_c += 1 + results[masked] = {"error": str(exc)} + task.record(False, item=masked, error=str(exc)) + + await run_batch(tokens, _one, concurrency=concurrency) + + if task.cancelled: + task.finish_cancelled() + else: + task.finish({ + "status": "success", + "summary": {"total": len(tokens), "ok": ok_c, "fail": fail_c}, + "results": results, + }) + except Exception as exc: + task.fail_task(str(exc)) + finally: + asyncio.create_task(expire_task(task.id, 300)) + + asyncio.create_task(_run()) + return _json({"status": "success", "task_id": task.id, "total": len(tokens)}) + + +# --------------------------------------------------------------------------- +# Per-token handlers +# --------------------------------------------------------------------------- + +async def _nsfw_one(repo: "AccountRepository", token: str, enabled: bool) -> dict: + from app.dataplane.reverse.protocol.xai_auth import nsfw_sequence, set_nsfw + if enabled: + await nsfw_sequence(token) + else: + await set_nsfw(token, enabled) + patch = AccountPatch(token=token, add_tags=["nsfw"]) if enabled else AccountPatch(token=token, remove_tags=["nsfw"]) + await repo.patch_accounts([patch]) + return {"success": True, "tagged": enabled} + + +async def _cache_clear_one(repo: "AccountRepository", token: str) -> dict: + from app.control.account.invalid_credentials import mark_account_invalid_credentials + from app.dataplane.reverse.transport.assets import list_assets, delete_asset + try: + resp = await list_assets(token) + items = resp.get("assets", resp.get("items", [])) + + async def _delete_one(item: dict) -> int: + asset_id = item.get("id") or item.get("assetId") + if not asset_id: + return 0 + await delete_asset(token, asset_id) + return 1 + + results = await asyncio.gather(*[_delete_one(item) for item in items], return_exceptions=True) + for result in results: + if not isinstance(result, Exception): + continue + if await mark_account_invalid_credentials(repo, token, result, source="asset batch clear"): + raise result + return {"deleted": sum(r for r in results if isinstance(r, int))} + except Exception as exc: + await mark_account_invalid_credentials(repo, token, exc, source="asset batch clear") + raise + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + +@router.post("/nsfw") +async def batch_nsfw( + req: BatchRequest, + async_mode: bool = Query(False, alias="async"), + all_manageable: bool = Query(False), + concurrency: int | None = Query(None, ge=1), + enabled: bool = Query(True), + repo: "AccountRepository" = Depends(get_repo), +): + tokens = [t.strip() for t in req.tokens if t.strip()] + if all_manageable and tokens: + raise ValidationError("tokens must be empty when all_manageable=true", param="tokens") + if all_manageable: + tokens = await _list_all_tokens(repo) + else: + if not tokens: + raise ValidationError("No tokens provided", param="tokens") + # Explicit refresh follows NSFW maintenance: only manageable accounts are operator-maintainable. + requested_count = len(tokens) + tokens = await _filter_manageable_tokens(repo, tokens) + skipped_count = requested_count - len(tokens) + if skipped_count: + logger.info("admin batch nsfw skipped non-manageable tokens: skipped_count={}", skipped_count) + if not tokens: + raise ValidationError("No manageable tokens available", param="tokens") + + async def _nsfw_and_tag(token: str) -> dict: + return await _nsfw_one(repo, token, enabled) + + c = _concurrency(concurrency, "batch.nsfw_concurrency") + if all_manageable: + logger.info("admin batch nsfw all manageable: token_count={} concurrency={}", len(tokens), c) + return await _dispatch(tokens, _nsfw_and_tag, use_async=async_mode, concurrency=c) + + +@router.post("/refresh") +async def batch_refresh( + req: BatchRequest, + async_mode: bool = Query(False, alias="async"), + all_manageable: bool = Query(False), + concurrency: int | None = Query(None, ge=1), + repo: "AccountRepository" = Depends(get_repo), + refresh_svc: "AccountRefreshService" = Depends(get_refresh_svc), +): + tokens = [t.strip() for t in req.tokens if t.strip()] + if all_manageable and tokens: + raise ValidationError("tokens must be empty when all_manageable=true", param="tokens") + if all_manageable: + tokens = await _list_all_tokens(repo) + else: + if not tokens: + raise ValidationError("No tokens provided", param="tokens") + requested_count = len(tokens) + tokens = await _filter_manageable_tokens(repo, tokens) + skipped_count = requested_count - len(tokens) + if skipped_count: + logger.info("admin batch refresh skipped non-manageable tokens: skipped_count={}", skipped_count) + if not tokens: + raise ValidationError("No manageable tokens available", param="tokens") + + async def _refresh_one(token: str) -> dict: + result = await refresh_svc.refresh_tokens([token]) + if not result.refreshed: + raise UpstreamError("未获取到真实配额数据") + return {"refreshed": result.refreshed} + + c = _concurrency(concurrency, "batch.refresh_concurrency") + if all_manageable: + logger.info("admin batch refresh all manageable: token_count={} concurrency={}", len(tokens), c) + return await _dispatch(tokens, _refresh_one, use_async=async_mode, concurrency=c, repo=repo) + + +@router.post("/cache-clear") +async def batch_cache_clear( + req: BatchRequest, + async_mode: bool = Query(False, alias="async"), + concurrency: int | None = Query(None, ge=1), + repo: "AccountRepository" = Depends(get_repo), +): + tokens = [t.strip() for t in req.tokens if t.strip()] + if not tokens: + tokens = await _list_all_tokens(repo) + if not tokens: + raise ValidationError("No tokens available", param="tokens") + + async def _clear_one(token: str) -> dict: + return await _cache_clear_one(repo, token) + + c = _concurrency(concurrency, "batch.asset_delete_concurrency") + return await _dispatch(tokens, _clear_one, use_async=async_mode, concurrency=c) + + +# --------------------------------------------------------------------------- +# SSE stream + cancel +# --------------------------------------------------------------------------- + +@router.get("/{task_id}/stream") +async def batch_stream(task_id: str, request: Request): + # Auth is handled by the parent router's verify_admin_key dependency, + # which accepts both Bearer header and ?app_key= query param (for EventSource). + task = get_task(task_id) + if not task: + raise AppError( + "Task not found", + kind=ErrorKind.VALIDATION, + code="task_not_found", + status=404, + ) + + async def _stream(): + queue = task.attach() + try: + yield f"data: {orjson.dumps({'type': 'snapshot', **task.snapshot()}).decode()}\n\n" + + final = task.final_event() + if final: + yield f"data: {orjson.dumps(final).decode()}\n\n" + return + + while True: + try: + event = await asyncio.wait_for(queue.get(), timeout=15) + except asyncio.TimeoutError: + yield ": ping\n\n" + final = task.final_event() + if final: + yield f"data: {orjson.dumps(final).decode()}\n\n" + return + continue + + yield f"data: {orjson.dumps(event).decode()}\n\n" + if event.get("type") in ("done", "error", "cancelled"): + return + finally: + task.detach(queue) + + return StreamingResponse(_stream(), media_type="text/event-stream") + + +@router.post("/{task_id}/cancel") +async def batch_cancel(task_id: str): + task = get_task(task_id) + if not task: + raise AppError( + "Task not found", + kind=ErrorKind.VALIDATION, + code="task_not_found", + status=404, + ) + task.cancel() + return {"status": "success"} diff --git a/app/products/web/admin/cache.py b/app/products/web/admin/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..fc49ab597a2827706eedacd6bc3c23f1b3fa97a0 --- /dev/null +++ b/app/products/web/admin/cache.py @@ -0,0 +1,191 @@ +"""Local media cache management — stats, list, clear, delete.""" + +import asyncio +from pathlib import Path +from typing import Any, Literal + +from fastapi import APIRouter, Query +from pydantic import BaseModel + +from app.platform.config.snapshot import get_config +from app.platform.errors import AppError, ErrorKind +from app.platform.storage import ( + clear_local_media_files, + delete_local_media_file, + image_files_dir, + video_files_dir, +) + +router = APIRouter(prefix="/cache", tags=["Admin - Cache"]) + +# --------------------------------------------------------------------------- +# Lightweight local media cache service. +# --------------------------------------------------------------------------- +_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"} +_VIDEO_EXTS = {".mp4", ".mov", ".m4v", ".webm", ".avi", ".mkv"} + + +class ClearCacheRequest(BaseModel): + type: Literal["image", "video"] = "image" + + +class DeleteCacheItemRequest(BaseModel): + type: Literal["image", "video"] = "image" + name: str + + +class DeleteCacheItemsRequest(BaseModel): + type: Literal["image", "video"] = "image" + names: list[str] + + +def _dir(media_type: str) -> Path: + return image_files_dir() if media_type == "image" else video_files_dir() + + +def _exts(media_type: str): + return _IMAGE_EXTS if media_type == "image" else _VIDEO_EXTS + + +def _limit_mb(media_type: str) -> int: + cfg = get_config() + return max(0, int(cfg.get_int(f"cache.local.{media_type}_max_mb", 0))) + + +def _stats(media_type: str) -> dict[str, Any]: + d = _dir(media_type) + files = [] + if d.exists(): + allowed = _exts(media_type) + files = [f for f in d.glob("*") if f.is_file() and f.suffix.lower() in allowed] + + total_size = sum(f.stat().st_size for f in files) + limit_mb = _limit_mb(media_type) + limit_bytes = limit_mb * 1024 * 1024 + usage_ratio = (total_size / limit_bytes) if limit_bytes > 0 else None + usage_percent = round(usage_ratio * 100, 1) if usage_ratio is not None else None + return { + "count": len(files), + "size_mb": round(total_size / 1024 / 1024, 2), + "size_bytes": total_size, + "limit_mb": limit_mb, + "limit_bytes": limit_bytes, + "limited": limit_bytes > 0, + "usage_ratio": round(usage_ratio, 4) if usage_ratio is not None else None, + "usage_percent": usage_percent, + } + + +def _list_files(media_type: str, page: int, page_size: int) -> dict[str, Any]: + d = _dir(media_type) + if not d.exists(): + return {"total": 0, "page": page, "page_size": page_size, "items": []} + allowed = _exts(media_type) + files = sorted( + (f for f in d.glob("*") if f.is_file() and f.suffix.lower() in allowed), + key=lambda f: f.stat().st_mtime, + reverse=True, + ) + total = len(files) + start = (page - 1) * page_size + chunk = files[start : start + page_size] + items = [] + for f in chunk: + st = f.stat() + items.append({ + "name": f.name, + "size_bytes": st.st_size, + "modified_at": st.st_mtime, + }) + return {"total": total, "page": page, "page_size": page_size, "items": items} + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + +@router.get("") +async def cache_stats(): + return { + "local_image": _stats("image"), + "local_video": _stats("video"), + } + + +@router.get("/list") +async def list_local( + cache_type: Literal["image", "video"] = "image", + type_: Literal["image", "video"] | None = Query(default=None, alias="type"), + page: int = 1, + page_size: int = 1000, +): + media_type = type_ or cache_type + return {"status": "success", **_list_files(media_type, page, page_size)} + + +@router.post("/clear") +async def clear_local(req: ClearCacheRequest): + removed = await asyncio.to_thread(clear_local_media_files, req.type) + return {"status": "success", "result": {"removed": removed}} + + +@router.post("/item/delete") +async def delete_local_item(req: DeleteCacheItemRequest): + if not req.name: + raise AppError( + "Missing file name", + kind=ErrorKind.VALIDATION, + code="missing_file_name", + status=400, + ) + try: + deleted = await asyncio.to_thread(delete_local_media_file, req.type, req.name) + except ValueError as exc: + raise AppError( + str(exc), + kind=ErrorKind.VALIDATION, + code="invalid_file_name", + status=400, + ) from exc + if not deleted: + raise AppError( + "File not found", + kind=ErrorKind.VALIDATION, + code="file_not_found", + status=404, + ) + return {"status": "success", "result": {"deleted": req.name}} + + +@router.post("/items/delete") +async def delete_local_items(req: DeleteCacheItemsRequest): + names = [name.strip() for name in req.names if name and name.strip()] + if not names: + raise AppError( + "Missing file names", + kind=ErrorKind.VALIDATION, + code="missing_file_names", + status=400, + ) + + deleted = 0 + missing = 0 + + for name in names: + try: + removed = await asyncio.to_thread(delete_local_media_file, req.type, name) + except ValueError: + missing += 1 + continue + if removed: + deleted += 1 + else: + missing += 1 + + return { + "status": "success", + "result": { + "deleted": deleted, + "missing": missing, + }, + } diff --git a/app/products/web/admin/tokens.py b/app/products/web/admin/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..8e40ae4947dee700f18d2672ca9756de2deae741 --- /dev/null +++ b/app/products/web/admin/tokens.py @@ -0,0 +1,564 @@ +"""Admin token CRUD — list, import, delete, replace pool. + +Performance notes: + - DI-injected repo (no try/except per call) + - orjson direct output (bypasses stdlib json) + - Quota dict: zero deserialization — reads r.quota directly + - Import refresh: reuses app.state.refresh_service singleton +""" + +import asyncio +import re +from typing import TYPE_CHECKING + +import orjson +from fastapi import APIRouter, Body, Depends, Query +from fastapi.responses import Response +from pydantic import BaseModel, RootModel + +from app.platform.errors import AppError, ErrorKind, ValidationError +from app.platform.config.snapshot import get_config +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_ms +from app.control.account.commands import ( + AccountPatch, + AccountUpsert, + BulkReplacePoolCommand, + ListAccountsQuery, +) +from app.control.account.enums import AccountStatus +from app.control.account.state_machine import is_manageable + +if TYPE_CHECKING: + from app.control.account.refresh import AccountRefreshService + from app.control.account.repository import AccountRepository + +from . import get_refresh_svc, get_repo + +router = APIRouter(tags=["Admin - Tokens"]) +_background_tasks: set[asyncio.Task] = set() + +# --------------------------------------------------------------------------- +# Token sanitisation +# --------------------------------------------------------------------------- + +_TOKEN_TRANS = str.maketrans({ + "\u2010": "-", "\u2011": "-", "\u2012": "-", + "\u2013": "-", "\u2014": "-", "\u2212": "-", + "\u00a0": " ", "\u2007": " ", "\u202f": " ", + "\u200b": "", "\u200c": "", "\u200d": "", "\ufeff": "", +}) +_STRIP_RE = re.compile(r"\s+") + + +def _sanitize(value: str) -> str: + tok = str(value or "").translate(_TOKEN_TRANS) + tok = _STRIP_RE.sub("", tok) + if tok.startswith("sso="): + tok = tok[4:] + return tok.encode("ascii", errors="ignore").decode("ascii") + + +def _mask(token: str) -> str: + return f"{token[:8]}...{token[-8:]}" if len(token) > 20 else token + + +# --------------------------------------------------------------------------- +# Request models +# --------------------------------------------------------------------------- + +class ReplacePoolRequest(BaseModel): + pool: str + tokens: list[str] + tags: list[str] = [] + + +class AddTokensRequest(BaseModel): + tokens: list[str] + pool: str = "basic" + tags: list[str] = [] + + +class EditTokenRequest(BaseModel): + old_token: str + token: str + pool: str = "basic" + + +class ToggleTokenDisabledRequest(BaseModel): + token: str + disabled: bool + + +class ToggleTokensDisabledRequest(BaseModel): + tokens: list[str] + disabled: bool + + +class TokenImportItem(BaseModel): + token: str + tags: list[str] = [] + + +class SaveTokensRequest(RootModel[dict[str, list[str | TokenImportItem]]]): + """Bulk-save payload keyed by pool name.""" + + +# --------------------------------------------------------------------------- +# Serialisation — zero-copy quota extraction +# --------------------------------------------------------------------------- + +def _quota_brief(q: dict) -> dict: + """Extract {auto, fast, expert, heavy, console} with only remaining/total from stored quota dict.""" + out = {} + for mode in ("auto", "fast", "expert", "heavy", "console"): + v = q.get(mode) + if isinstance(v, dict): + out[mode] = { + "remaining": int(v.get("remaining", 0) or 0), + "total": int(v.get("total", 0) or 0), + } + return out + + +def _serialize_record(r) -> dict: + return { + "token": r.token, + "pool": r.pool or "basic", + "status": r.status, + "quota": _quota_brief(r.quota) if isinstance(r.quota, dict) else {}, + "use_count": r.usage_use_count or 0, + "last_used_at": r.last_use_at, + "tags": r.tags or [], + } + + +def _json(data) -> Response: + """orjson fast-path response.""" + return Response(content=orjson.dumps(data), media_type="application/json") + + +def _fire_and_forget(coro) -> asyncio.Task: + # Keep a strong reference so import maintenance tasks cannot disappear before completion. + task = asyncio.create_task(coro) + _background_tasks.add(task) + + def _cleanup(done: asyncio.Task) -> None: + _background_tasks.discard(done) + if done.cancelled(): + return + if exc := done.exception(): + logger.warning("admin background task failed: error_type={}", type(exc).__name__) + + task.add_done_callback(_cleanup) + return task + + +def _schedule_auto_nsfw( + repo: "AccountRepository", + tokens: list[str], + *, + enabled: bool, +) -> None: + if not tokens or not enabled: + return + unique_tokens = list(dict.fromkeys(tokens)) + _fire_and_forget(_enable_nsfw_imported(repo, unique_tokens)) + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + +@router.get("/tokens") +async def list_tokens(repo: "AccountRepository" = Depends(get_repo)): + """Return flat token list.""" + all_items: list = [] + page_num = 1 + while True: + page = await repo.list_accounts(ListAccountsQuery(page=page_num, page_size=2000)) + all_items.extend(page.items) + if page_num * 2000 >= page.total: + break + page_num += 1 + + return _json({"tokens": [_serialize_record(r) for r in all_items]}) + + +@router.post("/tokens") +async def save_tokens( + req: SaveTokensRequest, + auto_nsfw: bool = Query(False), + repo: "AccountRepository" = Depends(get_repo), + refresh_svc: "AccountRefreshService" = Depends(get_refresh_svc), +): + """Full pool replace — accepts {pool_name: [token_objects]} dict.""" + total_upserted = 0 + all_tokens: list[str] = [] + + for pool_name, items in req.root.items(): + upserts = [] + for item in items: + td = {"token": item} if isinstance(item, str) else item.model_dump() + token_val = _sanitize(td.get("token", "")) + if not token_val: + continue + upserts.append(AccountUpsert(token=token_val, pool=pool_name, tags=td.get("tags") or [])) + if upserts: + await repo.replace_pool(BulkReplacePoolCommand(pool=pool_name, upserts=upserts)) + all_tokens.extend(u.token for u in upserts) + total_upserted += len(upserts) + + logger.info("admin tokens saved across pools: saved_count={}", total_upserted) + if all_tokens: + _fire_and_forget(_refresh_then_auto_nsfw( + refresh_svc, + repo, + all_tokens, + auto_nsfw_enabled=auto_nsfw, + )) + return _json({"status": "success", "count": total_upserted}) + + +@router.post("/tokens/add") +async def add_tokens( + req: AddTokensRequest, + auto_nsfw: bool = Query(False), + repo: "AccountRepository" = Depends(get_repo), + refresh_svc: "AccountRefreshService" = Depends(get_refresh_svc), +): + requested_pool = (req.pool or "basic").strip().lower() + + # Deduplicate and sanitize input + cleaned: list[str] = [] + seen: set[str] = set() + for token in req.tokens: + tok = _sanitize(token) + if tok and tok not in seen: + seen.add(tok) + cleaned.append(tok) + if not cleaned: + raise ValidationError("No valid tokens provided", param="tokens") + + # Only upsert tokens that are not already active — avoids overwriting quota/status. + # Soft-deleted tokens are treated as non-existing so they can be restored. + existing = {r.token for r in await repo.get_accounts(cleaned) if not r.is_deleted()} + new_tokens = [t for t in cleaned if t not in existing] + + if not new_tokens: + return _json({"status": "success", "count": 0, "skipped": len(cleaned)}) + + upserts = [AccountUpsert(token=t, pool=requested_pool, tags=req.tags) for t in new_tokens] + result = await repo.upsert_accounts(upserts) + logger.info( + "admin tokens added: pool={} added_count={} skipped_count={}", + requested_pool, + len(new_tokens), + len(existing), + ) + + _fire_and_forget(_refresh_then_auto_nsfw( + refresh_svc, + repo, + new_tokens, + auto_nsfw_enabled=auto_nsfw, + )) + + return _json({ + "status": "success", + "count": result.upserted or len(new_tokens), + "skipped": len(existing), + }) + + +@router.delete("/tokens") +async def delete_tokens( + tokens: list[str] = Body(...), + repo: "AccountRepository" = Depends(get_repo), +): + cleaned = [t for t in (_sanitize(t) for t in tokens) if t] + if not cleaned: + raise ValidationError("No valid tokens provided", param="tokens") + await repo.delete_accounts(cleaned) + logger.info("admin tokens deleted: deleted_count={}", len(cleaned)) + return _json({"deleted": len(cleaned)}) + + +@router.delete("/tokens/invalid") +async def delete_invalid_tokens(repo: "AccountRepository" = Depends(get_repo)): + tokens: list[str] = [] + page_num = 1 + while True: + page = await repo.list_accounts(ListAccountsQuery(page=page_num, page_size=2000)) + tokens.extend( + r.token + for r in page.items + if r.status not in ( + AccountStatus.ACTIVE, + AccountStatus.COOLING, + AccountStatus.DISABLED, + ) + ) + if page_num >= page.total_pages or not page.items: + break + page_num += 1 + + if not tokens: + return _json({"deleted": 0}) + + await repo.delete_accounts(tokens) + logger.info("admin invalid tokens deleted: deleted_count={}", len(tokens)) + return _json({"deleted": len(tokens)}) + + +@router.put("/tokens/edit") +async def edit_token( + req: EditTokenRequest, + repo: "AccountRepository" = Depends(get_repo), +): + old_token = _sanitize(req.old_token) + new_token = _sanitize(req.token) + pool = (req.pool or "basic").strip().lower() + + if not old_token or not new_token: + raise ValidationError("Token is required", param="token") + + records = await repo.get_accounts([old_token]) + if not records: + raise AppError( + "Account not found", + kind=ErrorKind.VALIDATION, + code="account_not_found", + status=404, + ) + record = records[0] + + if old_token != new_token: + existing = await repo.get_accounts([new_token]) + if existing: + raise AppError( + "Target token already exists", + kind=ErrorKind.VALIDATION, + code="token_conflict", + status=409, + ) + + await repo.upsert_accounts([AccountUpsert( + token=new_token, + pool=pool, + tags=record.tags, + ext=record.ext, + )]) + + if old_token == new_token: + logger.info("admin token updated: token={} pool={}", _mask(new_token), pool) + return _json({"status": "success", "token": new_token, "pool": pool}) + + qs = record.quota_set() + await repo.patch_accounts([AccountPatch( + token=new_token, + status=record.status, + tags=record.tags, + quota_auto=qs.auto.to_dict(), + quota_fast=qs.fast.to_dict(), + quota_expert=qs.expert.to_dict(), + usage_use_delta=record.usage_use_count, + usage_fail_delta=record.usage_fail_count, + usage_sync_delta=record.usage_sync_count, + last_use_at=record.last_use_at, + last_fail_at=record.last_fail_at, + last_fail_reason=record.last_fail_reason, + last_sync_at=record.last_sync_at, + last_clear_at=record.last_clear_at, + state_reason=record.state_reason, + ext_merge=record.ext, + )]) + await repo.delete_accounts([old_token]) + + logger.info("admin token replaced: previous_token={} current_token={} pool={}", _mask(old_token), _mask(new_token), pool) + return _json({"status": "success", "token": new_token, "pool": pool}) + + +@router.post("/tokens/disabled") +async def toggle_token_disabled( + req: ToggleTokenDisabledRequest, + repo: "AccountRepository" = Depends(get_repo), +): + token = _sanitize(req.token) + if not token: + raise ValidationError("Token is required", param="token") + + records = await repo.get_accounts([token]) + if not records: + raise AppError( + "Account not found", + kind=ErrorKind.VALIDATION, + code="account_not_found", + status=404, + ) + record = records[0] + + if req.disabled: + await repo.patch_accounts([AccountPatch( + token=token, + status=AccountStatus.DISABLED, + state_reason="operator_disabled", + ext_merge={ + **record.ext, + "disabled_at": now_ms(), + "disabled_reason": "operator_disabled", + }, + )]) + logger.info("admin token disabled: token={}", _mask(token)) + return _json({"status": "success", "token": token, "disabled": True}) + + await repo.patch_accounts([AccountPatch( + token=token, + status=AccountStatus.ACTIVE, + clear_failures=True, + )]) + logger.info("admin token restored: token={}", _mask(token)) + return _json({"status": "success", "token": token, "disabled": False}) + + +@router.post("/tokens/disabled/batch") +async def toggle_tokens_disabled( + req: ToggleTokensDisabledRequest, + repo: "AccountRepository" = Depends(get_repo), +): + cleaned: list[str] = [] + seen: set[str] = set() + for raw in req.tokens: + token = _sanitize(raw) + if token and token not in seen: + seen.add(token) + cleaned.append(token) + if not cleaned: + raise ValidationError("No valid tokens provided", param="tokens") + + records = await repo.get_accounts(cleaned) + if not records: + raise AppError( + "No matching accounts found", + kind=ErrorKind.VALIDATION, + code="account_not_found", + status=404, + ) + + ts = now_ms() + patches: list[AccountPatch] = [] + for record in records: + if req.disabled: + patches.append(AccountPatch( + token=record.token, + status=AccountStatus.DISABLED, + state_reason="operator_disabled", + ext_merge={ + **record.ext, + "disabled_at": ts, + "disabled_reason": "operator_disabled", + }, + )) + else: + patches.append(AccountPatch( + token=record.token, + status=AccountStatus.ACTIVE, + clear_failures=True, + )) + + result = await repo.patch_accounts(patches) + logger.info( + "admin tokens disabled batch updated: disabled={} requested_count={} patched_count={}", + req.disabled, + len(cleaned), + result.patched, + ) + return _json({ + "status": "success", + "disabled": req.disabled, + "summary": { + "total": len(cleaned), + "ok": result.patched, + "fail": max(0, len(cleaned) - result.patched), + }, + }) + + +@router.put("/tokens/pool") +async def replace_pool( + req: ReplacePoolRequest, + auto_nsfw: bool = Query(False), + repo: "AccountRepository" = Depends(get_repo), + refresh_svc: "AccountRefreshService" = Depends(get_refresh_svc), +): + cleaned = [t for t in (_sanitize(t) for t in req.tokens) if t] + upserts = [AccountUpsert(token=t, pool=req.pool, tags=req.tags) for t in cleaned] + await repo.replace_pool(BulkReplacePoolCommand(pool=req.pool, upserts=upserts)) + logger.info("admin pool replaced: pool={} token_count={}", req.pool, len(cleaned)) + if cleaned: + _fire_and_forget(_refresh_then_auto_nsfw( + refresh_svc, + repo, + cleaned, + auto_nsfw_enabled=auto_nsfw, + )) + return _json({"pool": req.pool, "count": len(cleaned)}) + + +# --------------------------------------------------------------------------- +# Fire-and-forget import refresh +# --------------------------------------------------------------------------- + +async def _refresh_imported(svc: "AccountRefreshService", tokens: list[str]) -> bool: + try: + await svc.refresh_on_import(tokens) + logger.info("admin import quota sync completed: token_count={}", len(tokens)) + return True + except Exception as exc: + logger.warning("admin import quota sync failed: token_count={} error={}", len(tokens), exc) + return False + + +async def _refresh_then_auto_nsfw( + svc: "AccountRefreshService", + repo: "AccountRepository", + tokens: list[str], + *, + auto_nsfw_enabled: bool, +) -> None: + unique_tokens = list(dict.fromkeys(tokens)) + if await _refresh_imported(svc, unique_tokens): + _schedule_auto_nsfw(repo, unique_tokens, enabled=auto_nsfw_enabled) + + +async def _enable_nsfw_imported(repo: "AccountRepository", tokens: list[str]) -> None: + from app.products.web.admin.batch import _concurrency, _nsfw_one + from app.platform.runtime.batch import run_batch + + records = await repo.get_accounts(tokens) + by_token = {r.token: r for r in records} + manageable_tokens = [token for token in tokens if (record := by_token.get(token)) and is_manageable(record)] + skipped_c = len(tokens) - len(manageable_tokens) + if not manageable_tokens: + logger.info("admin import auto nsfw skipped: token_count={} skipped_non_manageable={}", len(tokens), skipped_c) + return + + ok_c = fail_c = 0 + + async def _one(token: str) -> None: + nonlocal ok_c, fail_c + try: + await _nsfw_one(repo, token, True) + ok_c += 1 + except Exception as exc: + fail_c += 1 + logger.warning("admin import auto nsfw failed: token={} error={}", _mask(token), exc) + + await run_batch(manageable_tokens, _one, concurrency=_concurrency(None, "batch.nsfw_concurrency")) + logger.info( + "admin import auto nsfw completed: token_count={} skipped_non_manageable={} ok={} failed={}", + len(manageable_tokens), + skipped_c, + ok_c, + fail_c, + ) diff --git a/app/products/web/router.py b/app/products/web/router.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9ca67c393cca38ee774dcbef537454d7f16058 --- /dev/null +++ b/app/products/web/router.py @@ -0,0 +1,85 @@ +"""Web product — unified pages + API for the statics-based frontend.""" + +from pathlib import Path + +from fastapi import APIRouter, Depends, HTTPException, Query +from fastapi.responses import FileResponse, RedirectResponse + +from app.platform.auth.middleware import is_webui_enabled, verify_webui_key +from app.platform.meta import get_project_version +from app.platform.update_check import get_latest_release_info +from .static_html import serve_static_html +from .admin import router as admin_api_router +from .webui import router as webui_router + +router = APIRouter() + +# Mount admin API sub-router (/admin/api/*) +router.include_router(admin_api_router) +router.include_router(webui_router) + +_DIR = Path(__file__).resolve().parents[2] / "statics" + + +def _serve(path: str) -> FileResponse: + f = _DIR / path + if not f.exists(): + raise HTTPException(404, "Page not found") + return FileResponse(f) + + +def _serve_html(path: str): + return serve_static_html(_DIR / path) + + +@router.get("/", include_in_schema=False) +async def root(): + return RedirectResponse("/admin") + + +# --- Admin pages --- +@router.get("/admin", include_in_schema=False) +async def admin_root(): + return RedirectResponse("/admin/login") + +@router.get("/admin/login", include_in_schema=False) +async def admin_login(): + return _serve_html("admin/login.html") + +@router.get("/admin/account", include_in_schema=False) +async def admin_account(): + return _serve_html("admin/account.html") + +@router.get("/admin/config", include_in_schema=False) +async def admin_config(): + return _serve_html("admin/config.html") + +@router.get("/admin/cache", include_in_schema=False) +async def admin_cache(): + return _serve_html("admin/cache.html") + + +# --- WebUI --- +@router.get("/webui", include_in_schema=False) +async def webui_root(): + return RedirectResponse("/webui/login") + +@router.get("/webui/login", include_in_schema=False) +async def webui_login(): + if not is_webui_enabled(): + raise HTTPException(404, "Not Found") + return _serve_html("webui/login.html") + +@router.get("/webui/api/verify", dependencies=[Depends(verify_webui_key)], tags=["WebUI - System"]) +async def webui_verify(): + return {"status": "ok"} + + +@router.get("/meta", include_in_schema=False) +async def app_meta(): + return {"version": get_project_version()} + + +@router.get("/meta/update", include_in_schema=False) +async def app_update_meta(force: bool = Query(False)): + return await get_latest_release_info(force=force) diff --git a/app/products/web/static_html.py b/app/products/web/static_html.py new file mode 100644 index 0000000000000000000000000000000000000000..15315982ce2a5870951bf08877422774fb8559df --- /dev/null +++ b/app/products/web/static_html.py @@ -0,0 +1,26 @@ +"""Helpers for serving static HTML with lightweight version injection.""" + +from pathlib import Path + +from fastapi import HTTPException +from fastapi.responses import HTMLResponse + +from app.platform.meta import get_project_version + + +_VERSION_TOKEN = "{{APP_VERSION}}" + + +def serve_static_html(path: Path) -> HTMLResponse: + """Serve an HTML file, replacing the version token if present.""" + if not path.exists(): + raise HTTPException(status_code=404, detail="Page not found") + + body = path.read_text(encoding="utf-8") + if _VERSION_TOKEN in body: + body = body.replace(_VERSION_TOKEN, get_project_version()) + + return HTMLResponse(body, headers={"Cache-Control": "no-store"}) + + +__all__ = ["serve_static_html"] diff --git a/app/products/web/webui/__init__.py b/app/products/web/webui/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e91e825de320d03b1438c4a1058ec931b085bc8d --- /dev/null +++ b/app/products/web/webui/__init__.py @@ -0,0 +1,16 @@ +"""WebUI product package.""" + +from fastapi import APIRouter + +from .chat import router as chat_router +from .imagine import router as imagine_router +from .pages import router as pages_router +from .voice import router as voice_router + +router = APIRouter() +router.include_router(chat_router) +router.include_router(imagine_router, prefix="/webui/api") +router.include_router(voice_router) +router.include_router(pages_router) + +__all__ = ["router"] diff --git a/app/products/web/webui/chat.py b/app/products/web/webui/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..9d1dc2f9cd639064d95e139d44450cd6a0831ec4 --- /dev/null +++ b/app/products/web/webui/chat.py @@ -0,0 +1,47 @@ +"""WebUI chat API routes.""" + +import time + +from fastapi import APIRouter, Depends +from fastapi.responses import JSONResponse + +from app.control.model import registry as model_registry +from app.platform.auth.middleware import verify_webui_key +from app.products.openai.router import chat_completions_endpoint +from app.products.openai.schemas import ChatCompletionRequest + +router = APIRouter(prefix="/webui/api", dependencies=[Depends(verify_webui_key)], tags=["WebUI - Chat"]) + + +def _capability_name(spec) -> str: + if spec.is_image_edit(): + return "image_edit" + if spec.is_image(): + return "image" + if spec.is_video(): + return "video" + return "chat" + + +@router.get("/models") +async def list_webui_models(): + models = [ + { + "id": spec.model_name, + "object": "model", + "created": int(time.time()), + "owned_by": "xai", + "name": spec.public_name, + "capability": _capability_name(spec), + } + for spec in model_registry.list_enabled() + ] + return JSONResponse({"object": "list", "data": models}) + + +@router.post("/chat/completions") +async def webui_chat_completions(req: ChatCompletionRequest): + return await chat_completions_endpoint(req) + + +__all__ = ["router"] diff --git a/app/products/web/webui/imagine.py b/app/products/web/webui/imagine.py new file mode 100644 index 0000000000000000000000000000000000000000..e569d9863abdf4c85a19f964c0adedf982dfc948 --- /dev/null +++ b/app/products/web/webui/imagine.py @@ -0,0 +1,238 @@ +"""WebUI imagine endpoint backed by Grok Imagine WebSocket only.""" + +import asyncio +import hmac +import uuid +from typing import Optional + +import orjson +from fastapi import APIRouter, WebSocket, WebSocketDisconnect + +from app.platform.auth.middleware import get_webui_key, is_webui_enabled +from app.platform.config.snapshot import get_config +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_s +from app.products.openai.images import resolve_aspect_ratio + +router = APIRouter() + + +async def _acquire_token(): + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + return None, None + from app.control.model.registry import get as get_model + spec = get_model("grok-imagine-image") + if spec is None: + return None, None + acct = await _acct_dir.reserve( + pool_candidates=spec.pool_candidates(), + mode_id=int(spec.mode_id), + now_s_override=now_s(), + ) + if acct is None: + return None, None + return acct.token, acct + + +def _extract_token(value: str | None) -> str: + raw = str(value or "").strip() + if not raw: + return "" + scheme, _, token = raw.partition(" ") + if scheme.lower() == "bearer" and token: + return token.strip() + return raw + + +def _is_allowed(token: str) -> bool: + webui_key = get_webui_key() + if not webui_key: + return is_webui_enabled() + return bool(token) and hmac.compare_digest(token, webui_key) + + +def _websocket_token(websocket: WebSocket) -> str: + return ( + _extract_token(websocket.headers.get("authorization")) + or str(websocket.query_params.get("access_token") or "").strip() + ) + + +@router.websocket("/imagine/ws") +async def imagine_ws(websocket: WebSocket): + if not _is_allowed(_websocket_token(websocket)): + await websocket.close(code=1008) + return + + await websocket.accept() + stop_event = asyncio.Event() + run_task: Optional[asyncio.Task] = None + + async def _send(payload: dict) -> bool: + try: + await websocket.send_text(orjson.dumps(payload).decode()) + return True + except Exception: + return False + + async def _stop_run(): + nonlocal run_task + stop_event.set() + if run_task and not run_task.done(): + run_task.cancel() + try: + await run_task + except Exception: + pass + run_task = None + stop_event.clear() + + async def _run( + prompt: str, + aspect_ratio: str, + nsfw: Optional[bool], + count: int, + quality: str, + ): + from app.dataplane.account import _directory as _acct_dir + from app.dataplane.reverse.transport.imagine_ws import stream_images + + run_id = uuid.uuid4().hex + enable_pro = quality == "quality" + await _send({ + "type": "status", + "status": "running", + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "run_id": run_id, + "count": count, + "quality": quality, + }) + + acct = None + try: + token, acct = await _acquire_token() + if not token: + await _send({ + "type": "error", + "message": "No available accounts for this model tier", + "code": "rate_limit_exceeded", + }) + return + + enable_nsfw = nsfw if nsfw is not None else get_config().get_bool("features.enable_nsfw", True) + async for event in stream_images( + token, + prompt, + aspect_ratio=aspect_ratio, + n=count, + enable_nsfw=enable_nsfw, + enable_pro=enable_pro, + ): + if stop_event.is_set(): + return + if not isinstance(event, dict) or event.get("type") == "_meta": + continue + event.setdefault("run_id", run_id) + await _send(event) + if event.get("type") == "error": + return + + if not stop_event.is_set(): + await _send({ + "type": "status", + "status": "completed", + "run_id": run_id, + "count": count, + }) + except asyncio.CancelledError: + pass + except Exception as exc: + logger.error( + "webui imagine run failed: error_type={} error={}", + type(exc).__name__, + exc, + ) + await _send({ + "type": "error", + "message": str(exc), + "code": "internal_error", + }) + finally: + if acct and _acct_dir: + await _acct_dir.release(acct) + if stop_event.is_set(): + await _send({"type": "status", "status": "stopped", "run_id": run_id}) + + try: + while True: + try: + raw = await websocket.receive_text() + except (RuntimeError, WebSocketDisconnect): + break + + try: + payload = orjson.loads(raw) + except Exception: + await _send({ + "type": "error", + "message": "Invalid message format.", + "code": "invalid_payload", + }) + continue + + action = payload.get("type") + if action == "start": + prompt = str(payload.get("prompt") or "").strip() + if not prompt: + await _send({ + "type": "error", + "message": "Prompt cannot be empty.", + "code": "invalid_prompt", + }) + continue + aspect_ratio = resolve_aspect_ratio(str(payload.get("aspect_ratio") or "2:3").strip() or "2:3") + quality = str(payload.get("quality") or "speed").strip().lower() + if quality not in {"speed", "quality"}: + quality = "speed" + nsfw = payload.get("nsfw") + if nsfw is not None: + if isinstance(nsfw, str): + nsfw = nsfw.strip().lower() in {"1", "true", "yes", "on"} + else: + nsfw = bool(nsfw) + try: + count = int(payload.get("count") or 6) + except (TypeError, ValueError): + count = 6 + count = max(1, min(count, 6)) + await _stop_run() + run_task = asyncio.create_task(_run(prompt, aspect_ratio, nsfw, count, quality)) + continue + + if action == "stop": + await _stop_run() + continue + + await _send({ + "type": "error", + "message": "Unknown action.", + "code": "invalid_action", + }) + except WebSocketDisconnect: + pass + except Exception as exc: + logger.error( + "webui imagine websocket handler failed: error_type={} error={}", + type(exc).__name__, + exc, + ) + finally: + await _stop_run() + try: + from starlette.websockets import WebSocketState + if websocket.client_state == WebSocketState.CONNECTED: + await websocket.close(code=1000, reason="Server closing connection") + except Exception: + pass diff --git a/app/products/web/webui/pages.py b/app/products/web/webui/pages.py new file mode 100644 index 0000000000000000000000000000000000000000..45ceaadf7a751e03754aa0adffa36fb8046dbb10 --- /dev/null +++ b/app/products/web/webui/pages.py @@ -0,0 +1,48 @@ +"""Static page routes for the statics-based WebUI.""" + +from pathlib import Path + +from fastapi import APIRouter, HTTPException +from fastapi.responses import FileResponse + +from app.platform.auth.middleware import is_webui_enabled +from ..static_html import serve_static_html + +router = APIRouter(include_in_schema=False) + +STATIC_DIR = Path(__file__).resolve().parents[3] / "statics" / "webui" + + +def _serve(filename: str) -> FileResponse: + path = STATIC_DIR / filename + if not path.exists(): + raise HTTPException(status_code=404, detail="Page not found") + return FileResponse(path) + + +def _serve_html(filename: str): + return serve_static_html(STATIC_DIR / filename) + + +@router.get("/webui/chat") +async def webui_chat_page(): + if not is_webui_enabled(): + raise HTTPException(status_code=404, detail="Not Found") + return _serve_html("chat.html") + + +@router.get("/webui/chatkit") +async def webui_chatkit_page(): + if not is_webui_enabled(): + raise HTTPException(status_code=404, detail="Not Found") + return _serve_html("chatkit.html") + + +@router.get("/webui/masonry") +async def webui_masonry_page(): + if not is_webui_enabled(): + raise HTTPException(status_code=404, detail="Not Found") + return _serve_html("masonry.html") + + +__all__ = ["router"] diff --git a/app/products/web/webui/voice.py b/app/products/web/webui/voice.py new file mode 100644 index 0000000000000000000000000000000000000000..6994cced12d2850bef8113a512bc4a88ce473329 --- /dev/null +++ b/app/products/web/webui/voice.py @@ -0,0 +1,80 @@ +"""Voice token endpoint — LiveKit token acquisition.""" + +from fastapi import APIRouter, Depends +from pydantic import BaseModel + +from app.platform.errors import AppError, RateLimitError, UpstreamError +from app.platform.runtime.clock import now_s +from app.platform.auth.middleware import verify_webui_key + +router = APIRouter(prefix="/webui/api", dependencies=[Depends(verify_webui_key)], tags=["WebUI - Voice"]) + + +class VoiceTokenResponse(BaseModel): + token: str + url: str + participant_name: str = "" + room_name: str = "" + + +class VoiceTokenRequest(BaseModel): + voice: str = "ara" + personality: str = "assistant" + speed: float = 1.0 + instruction: str = "" + + +@router.post("/voice/token", response_model=VoiceTokenResponse) +async def voice_token(request: VoiceTokenRequest): + """Acquire a LiveKit voice session token.""" + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + # Voice uses auto mode, which is available on super/heavy pools only. + from app.control.model.enums import ModeId + + ts = now_s() + acct = await _acct_dir.reserve( + pool_candidates=(1, 2), + mode_id=int(ModeId.AUTO), + now_s_override=ts, + ) + if acct is None: + raise RateLimitError("No available tokens for voice mode") + + token = acct.token + try: + from app.dataplane.reverse.transport.livekit import fetch_livekit_token + data = await fetch_livekit_token( + token, + voice=request.voice, + personality=request.personality, + speed=request.speed, + custom_instruction=request.instruction.strip(), + ) + lk_token = data.get("token") + if not lk_token: + raise UpstreamError("Upstream returned no voice token") + return VoiceTokenResponse( + token=lk_token, + url=str(data.get("livekitUrl") or "wss://livekit.grok.com"), + participant_name=str( + data.get("participantName") + or data.get("participant_name") + or data.get("identity") + or "" + ), + room_name=str( + data.get("roomName") + or data.get("room_name") + or data.get("room") + or "" + ), + ) + except AppError: + raise + except Exception as e: + raise UpstreamError(f"Voice token error: {e}") + finally: + await _acct_dir.release(acct) diff --git a/app/statics/admin/account.html b/app/statics/admin/account.html new file mode 100644 index 0000000000000000000000000000000000000000..6ae3c23110adffd7bff84c9a57d9cfe974ed65aa --- /dev/null +++ b/app/statics/admin/account.html @@ -0,0 +1,2255 @@ + + + + + + Grok2API - 账户管理 + + + + + + + + +
+ + +
+ + +
+
+
账户列表
+
管理 Grok2API 的 xAI 服务账户池。
+
+
+ + +
+
+ +
+
账户概览
+
+ + +
+
+
+
账户总数
+ + + +
+
0
+
+
+
+
正常账户
+ + + +
+
0
+
+
+
+
限流账户
+ + + +
+
0
+
+
+
+
异常账户
+ + + +
+
0
+
+
+
+
禁用账户
+ + + +
+
0
+
+
+ + +
+
+
+
调用总数
+ + + +
+
0
+
+
+
+
Auto 余额
+ + + +
+
0
+
+
+
+
Fast 余额
+ + + +
+
0
+
+
+
+
Expert 余额
+ + + +
+
0
+
+
+
+
Heavy 余额
+ + + +
+
0
+
+
+
+
Console 余额
+ + + +
+
0
+
+
+ +
+
+
账户明细
+ 0 +
+
+ + +
+
+ +
+ 0 / 0 +
+ +
+
+
+ + +
+ + + + + + + + + + + + +
+
+ + +
+ + + + + + + + + + + + + + + + +
Token类型状态 + 额度 + + A + F + E + H + C + + 成功失败成功率最近使用操作
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/statics/admin/cache.html b/app/statics/admin/cache.html new file mode 100644 index 0000000000000000000000000000000000000000..13678256849909d03187b4817cda2a258c806cfb --- /dev/null +++ b/app/statics/admin/cache.html @@ -0,0 +1,1265 @@ + + + + + + Grok2API - 缓存管理 + + + + + + + + +
+ +
+ + +
+
+
缓存管理
+
统一查看本地缓存文件、容量上限与账户在线资产。
+
+
+ +
+
缓存概览
+
+ + +
+
+
+
图片缓存数量
+ + + +
+
—
+
+
+
+
视频缓存数量
+ + + +
+
—
+
+
+
+
图片缓存大小
+ + + +
+
—
+
—
+ +
+
+
+
视频缓存大小
+ + + +
+
—
+
—
+ +
+
+ +
+
缓存明细
+
+
+ + + +
+ + +
+
+
+ +
+ 第 0 / 0 页 +
+ +
+
+ + + +
+
+ +
+ + + + + + + + + + + +
文件名大小修改时间操作
+
+
+ + +
+
+
+ +
+
+ + + + +
+
+ + +
+ + + + + + + + + + + +
Token文件数操作
+
+
+ +
+ + + + + + + + + diff --git a/app/statics/admin/config.html b/app/statics/admin/config.html new file mode 100644 index 0000000000000000000000000000000000000000..51b015c5a77cb8895985c50ca545f08488c2a8f1 --- /dev/null +++ b/app/statics/admin/config.html @@ -0,0 +1,1357 @@ + + + + + + Grok2API - 配置管理 + + + + + + + + +
+ + +
+ +
+
+
配置管理
+
统一管理运行时参数与服务行为。保存后即时生效,部分配置需重启服务。
+
+
+ + +
+
+ + +
+ + +
+ +
+ + +
+
存在未保存的更改
+
+ + +
+
+ + + + + + + + + diff --git a/app/statics/admin/header.html b/app/statics/admin/header.html new file mode 100644 index 0000000000000000000000000000000000000000..bd4bfb34355df9d2b8814e9466a25cd8091a6e84 --- /dev/null +++ b/app/statics/admin/header.html @@ -0,0 +1,61 @@ +
+
+ + +
+ v0.2.1 +
+ + +
+ +
+
+
diff --git a/app/statics/admin/login.html b/app/statics/admin/login.html new file mode 100644 index 0000000000000000000000000000000000000000..de57d22e1fed1929e70b7623581b2dbeea53ad1d --- /dev/null +++ b/app/statics/admin/login.html @@ -0,0 +1,53 @@ + + + + + + Grok2API - Admin + + + + + + + + + + + + + + diff --git a/app/statics/css/app.css b/app/statics/css/app.css new file mode 100644 index 0000000000000000000000000000000000000000..4aca0c5aa230686a26b9686ef175bf344d5dd96a --- /dev/null +++ b/app/statics/css/app.css @@ -0,0 +1,1128 @@ +/* Grok2API — Design System */ +:root { + --bg:#fafafa; --bg-card:#fff; --fg:#000; --fg-muted:#666; --fg-subtle:#999; + --border:#e5e5e5; --radius:6px; --radius-xl:14px; + --success:#059669; --success-bg:#ecfdf5; --error:#dc2626; --error-bg:#fef2f2; --info:#525252; --info-bg:#f5f5f5; + --shadow-md:0 4px 16px rgba(0,0,0,.08); --shadow-lg:0 20px 50px rgba(0,0,0,.08); + --font-sans:'Geist Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif; +} +*,*::before,*::after{box-sizing:border-box;margin:0;padding:0} +body{font-family:var(--font-sans);background:var(--bg);color:var(--fg);line-height:1.5;-webkit-font-smoothing:antialiased;min-height:100vh} +a{color:inherit;text-decoration:none} +button,input,textarea{font:inherit;border:none;outline:none;background:none;color:inherit} +button{cursor:pointer} + +/* Login */ +.login-body{min-height:100vh;display:flex;align-items:center;justify-content:center;position:relative;overflow:hidden;background:#FAF9F5} +.login-bg{position:fixed;inset:0;z-index:0;background:#FAF9F5} +.login-shell{position:relative;z-index:1;width:min(420px,92vw);padding:24px} +.login-card{background:var(--bg-card);border:1px solid transparent;border-radius:var(--radius-xl);padding:22px;box-shadow:var(--shadow-lg);transition:border-color .2s} +.login-card:hover{border-color:var(--fg)} +.login-brand{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--fg-muted);font-weight:600} +.login-title{margin-top:6px;font-size:18px;font-weight:600} +.login-subtitle{margin-top:4px;font-size:12px;color:var(--fg-muted)} +.login-form{margin-top:16px;display:grid;gap:10px} + +/* Button */ +.btn{height:32px;padding:0 14px;border-radius:8px;font-size:13px;font-weight:600;display:inline-flex;align-items:center;justify-content:center;transition:opacity .15s;white-space:nowrap} +.btn-primary{background:var(--fg);color:var(--bg-card)} +.btn-primary:hover{opacity:.88} + +/* Input */ +.input{width:100%;height:34px;padding:0 10px;font-size:13px;border-radius:8px;border:1px solid var(--border);background:var(--bg-card);transition:border-color .15s} +.input:focus{border-color:#bbb;box-shadow:0 0 0 2px rgba(0,0,0,.04)} +.input::placeholder{color:var(--fg-subtle)} + +/* Toast */ +.toast-container{position:fixed;top:24px;left:50%;transform:translateX(-50%);z-index:200;display:flex;flex-direction:column;gap:10px;pointer-events:none;align-items:center} +.toast{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px;display:flex;align-items:center;gap:10px;min-width:260px;max-width:400px;pointer-events:auto;animation:toastIn .3s cubic-bezier(.16,1,.3,1) forwards;box-shadow:var(--shadow-md)} +.toast.out{animation:toastOut .2s ease forwards} +.toast-icon{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center;border-radius:50%} +.toast-success .toast-icon{background:var(--success-bg);color:var(--success)} +.toast-error .toast-icon{background:var(--error-bg);color:var(--error)} +.toast-info .toast-icon{background:var(--info-bg);color:var(--info)} +.toast-content{flex:1;font-size:12px;font-weight:500} +.toast-progress-label{font-size:12px;font-weight:500} +.toast-progress-track{height:3px;background:rgba(0,0,0,.08);border-radius:999px;margin-top:5px;overflow:hidden} +.toast-progress-fill{height:100%;background:var(--info);border-radius:999px;transition:width .3s} +.toast-success .toast-progress-fill{background:var(--success)} +.toast-error .toast-progress-fill{background:var(--error)} +.toast-progress-count{font-size:11px;color:#aaa;flex-shrink:0;margin-left:8px;font-variant-numeric:tabular-nums} +@keyframes toastIn{from{opacity:0;transform:translateY(16px) scale(.96)}to{opacity:1;transform:none}} +@keyframes toastOut{from{opacity:1}to{opacity:0;transform:translateY(8px) scale(.96)}} + +/* Helpers */ +.flex{display:flex}.items-center{align-items:center}.gap-2{gap:8px} +.mt-2{margin-top:8px}.text-xs{font-size:12px}.text-muted{color:var(--fg-muted)}.w-full{width:100%} + +/* Global footer */ +.site-footer{ + position:fixed; + right:18px; + bottom:10px; + z-index:40; + display:inline-flex; + align-items:center; + gap:6px; + color:rgba(23,23,23,.24); + font-size:11px; + font-weight:500; + letter-spacing:0; + line-height:1; + background:transparent; + pointer-events:none; + user-select:none; + white-space:nowrap; +} +.site-footer a{ + color:inherit; + text-decoration:none; + pointer-events:auto; + transition:color .15s, opacity .15s; +} +.site-footer a:hover{color:rgba(23,23,23,.42)} +.site-footer-version{font-variant-numeric:tabular-nums} + +/* Admin layout */ +.admin-header{background:#FAF9F5;position:fixed;top:0;left:0;right:0;z-index:100} +.admin-header-inner{max-width:1280px;width:100%;height:54px;margin:0 auto;padding:0 28px;display:grid;grid-template-columns:minmax(220px,260px) minmax(0,1fr) minmax(240px,272px);align-items:center;gap:16px} +.webui-header-bar{width:100%;background:#FAF9F5} +.webui-header-inner{max-width:none;padding:0 18px} +.admin-brand-wrap{display:flex;align-items:center;gap:8px;min-width:0;white-space:nowrap} +.admin-brand-link{display:inline-flex;align-items:center;gap:8px;min-width:0;color:inherit} +.admin-brand{font-size:14px;font-weight:700} +.admin-username{font-size:12px;color:var(--fg-muted);overflow:hidden;text-overflow:ellipsis} +.admin-nav{display:flex;align-items:center;justify-content:center;gap:0;min-width:0} +.admin-nav-link{font-size:14px;color:var(--fg-muted);padding:6px 14px;font-weight:500;transition:color .15s;border-radius:0} +.admin-nav-link:hover{color:var(--fg)} +.admin-nav-link.active{color:var(--fg);font-weight:600} +.admin-header-right{display:flex;align-items:center;justify-content:flex-end;gap:6px;min-width:0;white-space:nowrap} +.admin-header-version{ + display:inline-flex;align-items:center;height:28px;padding:0 10px;border-radius:999px; + position:relative;background:#f1ece2;color:#6a6459;font-size:11px;font-weight:600;letter-spacing:.02em;flex:0 0 auto; + cursor:pointer;user-select:none +} +.admin-header-version.has-update::after{ + content:"";position:absolute;top:2px;right:-3px;width:7px;height:7px;border-radius:999px;background:#2563eb +} +.admin-header-control{ + height:28px;padding:0 11px;border:0;border-radius:999px;background:transparent;color:#444; + font-size:11px;font-weight:600;transition:background .15s,color .15s +} +.admin-header-control:hover{background:#f1ece2;color:#222} +.admin-header-control:focus{box-shadow:none} +.admin-lang-menu{position:relative;flex:0 0 auto} +.admin-lang-trigger{ + gap:5px;padding:0 6px 0 8px;min-width:48px;border-radius:10px; + color:#6a6459 +} +.admin-lang-trigger svg{width:12px;height:12px;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;fill:none} +.admin-lang-trigger-code{font-size:11px;font-weight:600;letter-spacing:.02em;line-height:1} +.admin-lang-popover{ + position:absolute;top:calc(100% + 6px);right:0;min-width:138px;padding:4px;background:#faf9f5; + border:1px solid #ece3d6;border-radius:12px;box-shadow:0 12px 28px rgba(22,20,18,.07); + display:grid;gap:2px;opacity:0;pointer-events:none;transform:translateY(-4px); + transition:opacity .16s ease,transform .16s ease;z-index:140 +} +.admin-lang-menu.open .admin-lang-popover{opacity:1;pointer-events:auto;transform:translateY(0)} +.admin-lang-option{ + width:100%;min-height:30px;padding:0 8px;border-radius:9px;display:grid;grid-template-columns:26px minmax(0,1fr); + align-items:center;gap:8px;text-align:left;color:#2a2722 +} +.admin-lang-option:hover,.admin-lang-option.active{background:#f1ece2} +.admin-lang-option-code{font-size:11px;font-weight:600;letter-spacing:.02em;color:#6a6459} +.admin-lang-option-name{font-size:11px;font-weight:500;line-height:1.2;white-space:nowrap} +.admin-header-icon-btn{width:28px;min-width:28px;padding:0;justify-content:center;flex:0 0 auto} +.admin-header-icon-btn svg{width:13px;height:13px;stroke:currentColor;stroke-width:1.9;stroke-linecap:round;stroke-linejoin:round;fill:none} +.admin-badge{font-size:11px;font-weight:600;padding:3px 9px;border-radius:20px;border:1px solid;letter-spacing:.04em} +.admin-badge-green{color:#16a34a;border-color:#16a34a;background:#f0fdf4} +.admin-badge-blue{color:#2563eb;border-color:#2563eb;background:#eff6ff} +.admin-main{max-width:1280px;margin:0 auto;padding:78px 28px 24px} + +/* WebUI layout */ +.webui-page{--webui-control-surface:#f1ece2;min-height:100vh;background:#FAF9F5;color:#171717;padding-top:54px} +.webui-main{width:100%;max-width:none;margin:0;padding:6px 0 8px;box-sizing:border-box} +.webui-chat-layout{ + display:grid;grid-template-columns:284px minmax(0,1fr);gap:0; + height:calc(100vh - 54px);min-height:0;overflow:hidden +} +.webui-chatkit-main{width:100%;max-width:none;margin:0;padding:18px 28px 22px} +.webui-chatkit-shell{width:min(100%,1120px);margin:0 auto;display:grid;grid-template-columns:minmax(0,1fr);gap:18px;min-height:calc(100vh - 106px)} +.webui-chatkit-stage{display:grid;gap:18px;align-content:center} +.webui-chatkit-toolbar{ + width:min(100%,520px);margin:0 auto;min-width:0 +} +.webui-chatkit-toolbar-controls{ + display:grid;grid-template-columns:repeat(4,1fr);align-items:start;gap:10px;min-width:0 +} +@media (max-width: 600px){ + .webui-chatkit-toolbar{width:min(100%,100%)} + .webui-chatkit-toolbar-controls{grid-template-columns:repeat(2,1fr)} +} +.webui-chatkit-pill{ + width:100%;min-width:0;padding:0;border-radius:0;display:grid; + grid-template-columns:auto minmax(0,1fr);align-items:center;column-gap:10px;background:transparent +} +.webui-chatkit-pill-label{ + font-size:11px;font-weight:600;color:#7d786f;white-space:nowrap;line-height:1.2;text-align:left +} +.webui-chatkit-pill-input{ + width:100%;max-width:100%;min-width:0;height:30px;padding:0 26px 0 12px;border:0;border-radius:999px; + background:var(--webui-control-surface) !important;box-shadow:inset 0 1px 0 rgba(255,255,255,.42); + font-size:12px;font-weight:700;color:#111;background-position:right 10px center;background-size:10px 10px;text-align:left;text-align-last:left; + overflow:hidden;text-overflow:ellipsis;white-space:nowrap +} +.webui-chatkit-pill-input:focus{ + outline:none !important;box-shadow:none !important +} +.webui-chatkit-stage-card{ + min-height:calc(100vh - 300px);display:grid;place-items:center;align-content:center;text-align:center; + padding:28px 24px 20px;background:transparent;border:0;border-radius:0 +} +.webui-chatkit-orb-wrap{display:grid;justify-items:center;gap:22px} +.webui-chatkit-orb{ + --chatkit-level:0; + --chatkit-beat:0; + --chatkit-drift-a-x:0px; + --chatkit-drift-a-y:0px; + --chatkit-drift-b-x:0px; + --chatkit-drift-b-y:0px; + --chatkit-drift-c-x:0px; + --chatkit-drift-c-y:0px; + --chatkit-drift-d-x:0px; + --chatkit-drift-d-y:0px; + --chatkit-drift-e-x:0px; + --chatkit-drift-e-y:0px; + --bubble-a:#221e1a; + --bubble-b:#e8e0d3; + --bubble-c:#cfc3b5; + --bubble-d:#f2ece3; + --bubble-e:#b8bdb8; + --cluster-halo:rgba(255,255,255,.24); + --cluster-floor:rgba(188,176,159,.1); + --cluster-shadow:rgba(36,31,26,.08); + width:264px;height:244px;position:relative;display:block;isolation:isolate; + transition:filter .32s ease +} +.webui-chatkit-orb::before{ + content:"";position:absolute;inset:26px 34px 30px;border-radius:999px;pointer-events:none; + background:radial-gradient(circle at 50% 44%, var(--cluster-halo) 0%, rgba(255,255,255,.04) 44%, rgba(255,255,255,0) 76%); + filter:blur(24px);opacity:.44; + transform:scale(calc(1 + var(--chatkit-level) * .12)); + transition:transform .18s ease,opacity .18s ease,background .32s ease,filter .32s ease +} +.webui-chatkit-orb::after{ + content:"";position:absolute;left:62px;right:62px;bottom:18px;height:24px;border-radius:999px;pointer-events:none; + background:radial-gradient(circle at 50% 50%, var(--cluster-floor) 0%, rgba(188,176,159,.05) 58%, rgba(188,176,159,0) 100%); + filter:blur(14px);opacity:.38; + transform:scale(calc(1 + var(--chatkit-level) * .06)); + transition:transform .18s ease,opacity .18s ease,background .32s ease,filter .32s ease +} +.webui-chatkit-bubble{ + position:absolute;border-radius:999px;pointer-events:none; + box-shadow:0 14px 28px var(--cluster-shadow); + transition:transform .16s ease,box-shadow .16s ease,filter .16s ease,opacity .16s ease,background-color .32s ease; + will-change:transform,box-shadow,filter +} +.webui-chatkit-bubble-a{ + left:40px;top:54px;width:116px;height:116px;background:var(--bubble-a); + animation:webui-chatkit-bubble-a 8.8s ease-in-out infinite +} +.webui-chatkit-bubble-b{ + left:144px;top:34px;width:72px;height:72px;background:var(--bubble-b); + animation:webui-chatkit-bubble-b 10.2s ease-in-out infinite +} +.webui-chatkit-bubble-c{ + left:176px;top:108px;width:86px;height:86px;background:var(--bubble-c); + animation:webui-chatkit-bubble-c 9.6s ease-in-out infinite +} +.webui-chatkit-bubble-d{ + left:98px;top:156px;width:58px;height:58px;background:var(--bubble-d); + animation:webui-chatkit-bubble-d 7.8s ease-in-out infinite +} +.webui-chatkit-bubble-e{ + left:146px;top:144px;width:34px;height:34px;background:var(--bubble-e); + animation:webui-chatkit-bubble-e 8.4s ease-in-out infinite +} +.webui-chatkit-orb.is-idle{ + --bubble-a:#201c18; + --bubble-b:#e8dfd3; + --bubble-c:#cfc2b4; + --bubble-d:#f2ece3; + --bubble-e:#c0c4be; + --cluster-halo:rgba(255,255,255,.26); + --cluster-floor:rgba(192,181,165,.12); + animation:webui-chatkit-idle-float 11.4s ease-in-out infinite +} +.webui-chatkit-orb.is-connecting{ + --bubble-a:#5a4321; + --bubble-b:#ecd6a0; + --bubble-c:#c9964f; + --bubble-d:#f7edd2; + --bubble-e:#dfc17e; + --cluster-halo:rgba(248,228,183,.3); + --cluster-floor:rgba(210,180,120,.14); + --cluster-shadow:rgba(109,78,26,.1); + animation:webui-chatkit-connecting-pulse 4.8s ease-in-out infinite +} +.webui-chatkit-orb.is-live{ + --bubble-a:#161410; + --bubble-b:#e7efe8; + --bubble-c:#7ea592; + --bubble-d:#edf3ee; + --bubble-e:#bad0c2; + --cluster-halo:rgba(202,237,218,.3); + --cluster-floor:rgba(110,164,138,.16); + --cluster-shadow:rgba(28,61,49,.11); + animation:webui-chatkit-live-float 7.2s ease-in-out infinite +} +.webui-chatkit-orb.is-paused{ + --bubble-a:#2c2b30; + --bubble-b:#e2e5ec; + --bubble-c:#9ca7bb; + --bubble-d:#eef1f6; + --bubble-e:#cbd3e1; + --cluster-halo:rgba(214,221,236,.28); + --cluster-floor:rgba(146,158,188,.14); + animation:webui-chatkit-paused-hold 9.2s ease-in-out infinite +} +.webui-chatkit-orb.is-output-muted{ + --bubble-a:#322321; + --bubble-b:#f0dbd4; + --bubble-c:#d18a79; + --bubble-d:#f6e8e1; + --bubble-e:#e2b29f; + --cluster-halo:rgba(244,211,198,.3); + --cluster-floor:rgba(214,133,106,.15); + animation:webui-chatkit-muted-pulse 5.6s ease-in-out infinite +} +.webui-chatkit-orb.is-error{ + --bubble-a:#241614; + --bubble-b:#ead2ca; + --bubble-c:#b77668; + --bubble-d:#f0ddd6; + --bubble-e:#d4a195; + --cluster-halo:rgba(221,173,157,.26); + --cluster-floor:rgba(183,114,103,.12); + --cluster-shadow:rgba(100,43,31,.1); + animation:webui-chatkit-error-shift 6.4s ease-in-out infinite +} +.webui-chatkit-orb.is-connecting::before{opacity:.64} +.webui-chatkit-orb.is-live::before{opacity:.7} +.webui-chatkit-orb.is-paused::before{opacity:.58} +.webui-chatkit-orb.is-output-muted::before{opacity:.6} +.webui-chatkit-orb.is-live.is-speaking::before{ + opacity:.72;transform:scale(calc(1.02 + var(--chatkit-level) * .14)) +} +.webui-chatkit-orb.is-live.is-speaking::after{ + opacity:.48;transform:scale(calc(1.01 + var(--chatkit-level) * .06)) +} +.webui-chatkit-orb.is-live.is-speaking .webui-chatkit-bubble{ + box-shadow:0 18px 34px rgba(41,35,29,.1); + filter:saturate(calc(1 + var(--chatkit-level) * .08)) +} +.webui-chatkit-orb.is-live.is-speaking .webui-chatkit-bubble-a{ + transform:translate3d(calc(-11px * var(--chatkit-level) + var(--chatkit-drift-a-x) - 5px * var(--chatkit-beat)),calc(-10px * var(--chatkit-level) + var(--chatkit-drift-a-y) - 4px * var(--chatkit-beat)),0) scale(calc(1.03 + var(--chatkit-level) * .2 + var(--chatkit-beat) * .12)) +} +.webui-chatkit-orb.is-live.is-speaking .webui-chatkit-bubble-b{ + transform:translate3d(calc(11px * var(--chatkit-level) + var(--chatkit-drift-b-x) + 5px * var(--chatkit-beat)),calc(-8px * var(--chatkit-level) + var(--chatkit-drift-b-y) - 3px * var(--chatkit-beat)),0) scale(calc(1.03 + var(--chatkit-level) * .16 + var(--chatkit-beat) * .1)) +} +.webui-chatkit-orb.is-live.is-speaking .webui-chatkit-bubble-c{ + transform:translate3d(calc(12px * var(--chatkit-level) + var(--chatkit-drift-c-x) + 6px * var(--chatkit-beat)),calc(10px * var(--chatkit-level) + var(--chatkit-drift-c-y) + 5px * var(--chatkit-beat)),0) scale(calc(1.04 + var(--chatkit-level) * .18 + var(--chatkit-beat) * .11)) +} +.webui-chatkit-orb.is-live.is-speaking .webui-chatkit-bubble-d{ + transform:translate3d(calc(-9px * var(--chatkit-level) + var(--chatkit-drift-d-x) - 4px * var(--chatkit-beat)),calc(10px * var(--chatkit-level) + var(--chatkit-drift-d-y) + 5px * var(--chatkit-beat)),0) scale(calc(1.03 + var(--chatkit-level) * .16 + var(--chatkit-beat) * .1)) +} +.webui-chatkit-orb.is-live.is-speaking .webui-chatkit-bubble-e{ + transform:translate3d(calc(8px * var(--chatkit-level) + var(--chatkit-drift-e-x) + 3px * var(--chatkit-beat)),calc(-6px * var(--chatkit-level) + var(--chatkit-drift-e-y) - 3px * var(--chatkit-beat)),0) scale(calc(1.03 + var(--chatkit-level) * .14 + var(--chatkit-beat) * .08)) +} +.webui-chatkit-badge{ + height:24px;padding:0 11px;border-radius:999px;display:inline-flex;align-items:center; + background:rgba(245,241,232,.9);color:#5f594f;font-size:11px;font-weight:600; + box-shadow:none;transform:translateY(-8px); + transition:background-color .32s ease,color .32s ease,border-color .32s ease,opacity .24s ease,transform .24s ease +} +.webui-chatkit-badge[data-state="is-idle"]{background:rgba(245,241,232,.9);color:#5f594f} +.webui-chatkit-badge[data-state="is-connecting"]{background:rgba(245,226,184,.9);color:#7a5217} +.webui-chatkit-badge[data-state="is-live"]{background:rgba(222,240,229,.92);color:#245a42} +.webui-chatkit-badge[data-state="is-paused"]{background:rgba(229,234,244,.92);color:#4a5878} +.webui-chatkit-badge[data-state="is-output-muted"]{background:rgba(244,226,220,.92);color:#8b4d3e} +.webui-chatkit-badge[data-state="is-error"]{background:rgba(241,219,214,.92);color:#8a3e32} +} +.webui-chatkit-stage-copy{width:min(100%,540px);display:grid;gap:10px;max-width:540px;margin-top:34px;text-align:center} +.webui-chatkit-stage-title{font-size:30px;line-height:1.05;font-weight:700;letter-spacing:-.05em;color:#1c1a17} +.webui-chatkit-stage-text{font-size:14px;line-height:1.75;color:#6f6a62} +.webui-chatkit-controls{display:flex;justify-content:center;gap:8px;flex-wrap:wrap;margin-top:30px} +.webui-chatkit-icon-btn{ + width:40px;min-width:40px;height:40px;padding:0;border-radius:999px;display:grid;place-items:center; + background:#f6f2ea;color:#2a2824 +} +.webui-chatkit-icon-btn svg{ + width:18px;height:18px;stroke:currentColor;stroke-width:1.9;stroke-linecap:round;stroke-linejoin:round;fill:none +} +.webui-chatkit-icon-btn-primary svg{width:20px;height:20px} +.webui-chatkit-icon-btn-primary{background:#171511;color:#fff} +.webui-chatkit-icon-btn:disabled{opacity:.4} +.webui-chatkit-audio{display:none} +@keyframes webui-chatkit-idle-float{ + 0%,100%{transform:translate3d(0,0,0)} + 50%{transform:translate3d(0,-8px,0)} +} +@keyframes webui-chatkit-connecting-pulse{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 35%{transform:translate3d(0,-5px,0) scale(1.026)} + 70%{transform:translate3d(0,1px,0) scale(.988)} +} +@keyframes webui-chatkit-live-float{ + 0%,100%{transform:translate3d(0,0,0)} + 50%{transform:translate3d(0,-5px,0)} +} +@keyframes webui-chatkit-paused-hold{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 50%{transform:translate3d(0,-2px,0) scale(.994)} +} +@keyframes webui-chatkit-muted-pulse{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 45%{transform:translate3d(0,-3px,0) scale(1.014)} + 70%{transform:translate3d(0,0,0) scale(.996)} +} +@keyframes webui-chatkit-error-shift{ + 0%,100%{transform:translate3d(0,0,0)} + 50%{transform:translate3d(0,-4px,0)} +} +@keyframes webui-chatkit-bubble-a{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 50%{transform:translate3d(6px,-7px,0) scale(1.03)} +} +@keyframes webui-chatkit-bubble-b{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 50%{transform:translate3d(-5px,7px,0) scale(1.02)} +} +@keyframes webui-chatkit-bubble-c{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 50%{transform:translate3d(-8px,-6px,0) scale(1.03)} +} +@keyframes webui-chatkit-bubble-d{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 50%{transform:translate3d(5px,-5px,0) scale(1.02)} +} +@keyframes webui-chatkit-bubble-e{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 50%{transform:translate3d(-4px,4px,0) scale(1.03)} +} +.webui-chat-layout.sidebar-collapsed{grid-template-columns:56px minmax(0,1fr)} +.webui-sidebar{ + background:#FAF9F5;border-right:1px solid #ece8de;padding:10px 12px 14px 16px; + display:grid;grid-template-rows:auto minmax(0,1fr) auto;gap:10px; + height:100%;min-height:0;overflow:hidden +} +.webui-chat-layout.sidebar-collapsed .webui-sidebar{padding:8px 8px 16px} +.webui-sidebar-header{display:flex;align-items:center;justify-content:space-between;min-height:28px;padding:0 2px} +.webui-sidebar-headcopy{min-height:28px;display:flex;align-items:center} +.webui-sidebar-headtitle{font-size:18px;font-weight:700;color:#191713;line-height:1;letter-spacing:-.03em} +.webui-sidebar-headmeta{font-size:12px;color:#9a968e;line-height:1.2} +.webui-sidebar-actions{display:inline-flex;align-items:center;gap:6px;flex:0 0 auto} +.webui-sidebar-toggle{width:28px;height:28px;display:grid;place-items:center;color:#202020} +.webui-sidebar-toggle svg{width:22px;height:22px} +.webui-sidebar-new-btn svg{width:18px;height:18px} +.webui-chat-layout.sidebar-collapsed .webui-sidebar-header{justify-content:center} +.webui-chat-layout.sidebar-collapsed .webui-sidebar-headcopy, +.webui-chat-layout.sidebar-collapsed .webui-sidebar-new-btn, +.webui-chat-layout.sidebar-collapsed .webui-sidebar-create, +.webui-chat-layout.sidebar-collapsed .webui-sidebar-sessions, +.webui-chat-layout.sidebar-collapsed .webui-sidebar-settings{display:none} +.webui-sidebar-create{ + height:42px;border-radius:12px;padding:0 14px;background:#ecebe7;color:#181816; + display:flex;align-items:center;justify-content:flex-start;font-size:14px;font-weight:700 +} +.webui-sidebar-create:hover{background:#e7e5e0} +.webui-sidebar-sessions{display:grid;grid-template-rows:auto minmax(0,1fr);gap:6px;min-height:0} +.webui-session-list{display:grid;gap:3px;align-content:start;overflow:auto;padding-right:4px} +.webui-session-list:empty::before{ + content:attr(data-empty);padding:6px 12px;color:#a09d96;font-size:12px +} +.webui-session-item{ + min-height:30px;border-radius:8px;padding:6px 10px;background:transparent;color:#2d2c29; + text-align:left;font-size:13px;line-height:1.3;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:6px +} +.webui-session-item:hover{background:#efeeea} +.webui-session-item.active{background:#ece9e1} +.webui-session-title{white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.webui-session-actions{display:flex;align-items:center;gap:4px;opacity:0;transition:opacity .15s} +.webui-session-item:hover .webui-session-actions, +.webui-session-item.active .webui-session-actions{opacity:1} +.webui-session-action{ + width:24px;height:24px;border-radius:8px;display:grid;place-items:center;color:#75716b +} +.webui-session-action:hover{background:#e8e6e0;color:#1f1f1d} +.webui-session-action svg{width:14px;height:14px} +.webui-sidebar-settings{ + display:grid;grid-template-columns:minmax(0,1fr);align-items:center;gap:8px;align-content:start;padding:0 8px 2px 12px +} +.webui-control{display:grid;padding:0} +.webui-control .input{ + height:34px;border-radius:10px;border:0;background:var(--webui-control-surface);padding-left:12px;padding-right:12px;box-shadow:none;font-size:12px;color:#201d19 +} +.webui-status{ + display:inline-flex;align-items:center;gap:8px;min-height:18px;font-size:12px;font-weight:600;color:#5f5c57;padding:0 12px +} +.webui-status::before{ + content:"";width:7px;height:7px;border-radius:999px;background:#9ca3af;box-shadow:0 0 0 4px rgba(156,163,175,.12) +} +.webui-sidebar .modal .input{margin-top:0} +.webui-workspace{background:#FAF9F5;min-height:0;height:100%;overflow:hidden} +.webui-chat-pane{ + background:#FAF9F5;display:grid;grid-template-rows:minmax(0,1fr) auto;height:100%;min-height:0;overflow:hidden +} +.webui-thread-shell{padding:6px 24px 0;min-height:0;height:100%;overflow:hidden} +.webui-thread{ + position:relative;height:100%;min-height:0;overflow:auto;padding:0 6px 16px;background:transparent; + scrollbar-width:thin;scrollbar-color:rgba(17,24,39,.18) transparent +} +.webui-thread::-webkit-scrollbar{width:8px} +.webui-thread::-webkit-scrollbar-thumb{background:rgba(17,24,39,.16);border-radius:999px} +.webui-empty{ + position:absolute;inset:0;display:grid;place-items:center;padding:28px 18px;color:#6f6a62;pointer-events:none +} +.webui-empty-card{width:min(100%,540px);text-align:center;display:grid;gap:10px} +.webui-empty-title{font-size:30px;line-height:1.05;font-weight:700;letter-spacing:-.05em;color:#1c1a17} +.webui-empty-text{font-size:14px;line-height:1.75} +.msg{max-width:860px;margin:0 auto 28px;display:grid;gap:8px} +.msg.user{justify-items:end} +.msg-meta{font-size:11px;color:#a3a099} +.msg-actions{display:flex;align-items:center;justify-content:flex-end;gap:4px} +.msg-actions-assistant{width:min(100%,760px);justify-content:flex-start} +.msg-actions[hidden]{display:none !important} +.msg-action-group{display:flex;align-items:center;gap:4px} +.msg-action-btn{ + width:24px;height:24px;padding:0;border-radius:999px;display:grid;place-items:center;color:#7b776f;line-height:0 +} +.msg-action-btn:hover{background:#f2f0ea;color:#22201c} +.msg-action-btn.active{background:#ece8df;color:#171511} +.msg-action-btn svg{width:14px;height:14px;display:block} +.msg-action-btn-regen svg{width:12px;height:12px} +.msg-card-editing{ + width:min(100%,760px);background:#faf9f6;border:1px solid #e8e3d9;border-radius:14px;padding:14px 14px 12px +} +.msg-edit-textarea{ + width:100%;min-height:52px;resize:none;border:0;background:transparent;color:#171717; + font-size:14px;line-height:1.6;overflow:hidden +} +.msg-edit-textarea:focus{outline:none;box-shadow:none} +.msg-edit-footer{display:flex;align-items:center;justify-content:flex-end;gap:8px;margin-top:10px} +.msg-edit-cancel{ + height:32px;padding:0 10px;border-radius:999px;color:#5f5b55;font-size:13px;font-weight:500 +} +.msg-edit-cancel:hover{background:#f2efe8;color:#1f1d19} +.msg-edit-save{ + height:32px;padding:0 14px;border-radius:999px;background:#111;color:#fff;font-size:13px;font-weight:600 +} +.msg-edit-save:hover{background:#000} +.msg-card{ + width:min(100%,760px);padding:0;background:transparent;line-height:1.7;box-shadow:none;color:#20201e +} +.msg-card-user{white-space:pre-wrap;font-size:14px} +.msg-card-assistant{white-space:normal;font-size:14px} +.msg-loading{ + display:inline-flex;align-items:center;justify-content:flex-start;min-height:24px;padding:2px 0 +} +.msg-loading-spinner{ + width:16px;height:16px;border-radius:999px;border:1.8px solid rgba(28,26,23,.14);border-top-color:#171511; + animation:msg-loading-spin .72s linear infinite +} +.msg.user .msg-card{ + width:fit-content;max-width:min(100%,720px); + background:#f5f4f1;color:#141414;border-radius:14px;padding:12px 16px +} +.msg.error .msg-card{ + width:fit-content;max-width:min(100%,720px); + background:#f8ebe7;color:#8a3528;border-radius:14px;padding:12px 16px;font-size:13px;line-height:1.6 +} +.msg-user-parts{display:grid;gap:10px} +.msg-user-text{white-space:pre-wrap} +.msg-user-gallery{ + display:grid;grid-template-columns:repeat(auto-fit,minmax(136px,196px));gap:10px +} +.msg-user-files{ + display:flex;flex-wrap:wrap;gap:8px +} +.msg-user-file{ + max-width:100%;padding:8px 12px;border-radius:999px;background:#ebe9e4;color:#2b2a27; + font-size:12px;line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis +} +.msg-user-gallery img, +.msg-inline-media img{ + display:block;max-width:100%;max-height:240px;height:auto;border-radius:14px;object-fit:cover +} +.msg-inline-media{margin:0 0 12px} +.msg-card-assistant img{ + display:block;max-width:min(100%,400px);max-height:280px;height:auto;border-radius:14px +} +.msg-card-assistant video{ + display:block;width:min(100%,400px);max-height:300px;border-radius:16px;background:#111 +} +.msg-media-error{ + box-sizing:border-box;width:max-content;max-width:100%;margin-top:8px;padding:9px 11px;border-radius:10px; + background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;font-size:12px;line-height:1.5; + white-space:nowrap +} +.msg-card-assistant > *:first-child{margin-top:0} +.msg-card-assistant > *:last-child{margin-bottom:0} +.msg-card-assistant p, +.msg-card-assistant ul, +.msg-card-assistant ol, +.msg-card-assistant pre, +.msg-card-assistant blockquote, +.msg-card-assistant h1, +.msg-card-assistant h2, +.msg-card-assistant h3, +.msg-card-assistant h4, +.msg-card-assistant h5, +.msg-card-assistant h6{margin:0 0 12px} +.msg-card-assistant h1, +.msg-card-assistant h2, +.msg-card-assistant h3, +.msg-card-assistant h4, +.msg-card-assistant h5, +.msg-card-assistant h6{line-height:1.3;letter-spacing:-.02em} +.msg-card-assistant h1{font-size:24px} +.msg-card-assistant h2{font-size:20px} +.msg-card-assistant h3{font-size:17px} +.msg-card-assistant ul, +.msg-card-assistant ol{padding-left:22px} +.msg-card-assistant li + li{margin-top:4px} +.msg-card-assistant table{ + width:100%;border-collapse:collapse;margin:0 0 12px;font-size:14px;display:block;overflow-x:auto +} +.msg-card-assistant thead th{ + background:#f5f4f1;color:#2b2925;font-size:12px;font-weight:600;text-transform:none;letter-spacing:0;border-bottom:1px solid #e7e1d7 +} +.msg-card-assistant th, +.msg-card-assistant td{ + padding:10px 12px;border:1px solid #ece6dc;text-align:left;vertical-align:top;white-space:nowrap +} +.msg-card-assistant hr{ + border:0;border-top:1px solid #ebe5da;margin:18px 0 +} +.msg-card-assistant a{color:#0f62fe;text-decoration:none} +.msg-card-assistant a:hover{text-decoration:underline} +.msg-card-assistant code{ + font-family:'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace; + font-size:.92em;padding:2px 6px;border-radius:8px;background:#f3f1eb +} +.msg-card-assistant pre{ + overflow:auto;padding:14px 16px;border-radius:16px;background:#171717;color:#f7f7f5 +} +.msg-card-assistant pre code{ + padding:0;background:transparent;color:inherit;font-size:13px;line-height:1.7 +} +.msg-card-assistant blockquote{ + padding-left:14px;border-left:3px solid #ddd7cb;color:#6c675f +} +.msg-reasoning{ + width:min(100%,760px);display:grid;gap:10px;padding:2px 0 4px;background:transparent;color:#8b887f;font-size:12px;line-height:1.5 +} +.msg-reasoning[hidden]{display:none !important} +.msg-reasoning-toggle{ + width:max-content;max-width:100%;min-width:0;height:24px;padding:0 2px;border-radius:8px;display:inline-flex;align-items:center;gap:4px; + color:#8a8479;background:transparent;border:0;box-shadow:none; + font-size:12px;font-weight:500;letter-spacing:0;line-height:1;white-space:nowrap +} +.msg-reasoning-toggle:hover{background:transparent;color:#575249} +.msg-reasoning-toggle svg{width:12px;height:12px;flex:0 0 auto;opacity:.72;transition:transform .18s ease,opacity .18s ease} +.msg-reasoning-toggle[aria-expanded="true"] svg{opacity:1} +.msg-reasoning-label{display:block;overflow:hidden;text-overflow:ellipsis} +.msg-reasoning-body{ + margin-left:10px;padding-left:14px;border-left:1.5px solid #ece6da; + white-space:pre-wrap;font-size:12px;line-height:1.8 +} +.msg-reasoning.is-collapsed .msg-reasoning-toggle svg{transform:rotate(-90deg)} +.msg-reasoning.is-collapsed .msg-reasoning-body{display:none} +@keyframes msg-loading-spin{ + to{transform:rotate(360deg)} +} +.webui-composer{ + position:sticky;bottom:0;z-index:2;padding:0 24px 16px;background:linear-gradient(180deg,rgba(250,249,245,0),#FAF9F5 34%);border-top:0;display:flex;flex-direction:column;align-items:center +} +.webui-upload-meta{ + width:min(100%,940px);padding:0 2px 8px;overflow-x:auto;overflow-y:hidden; + scrollbar-width:none;-ms-overflow-style:none +} +.webui-upload-meta::-webkit-scrollbar{display:none} +.webui-upload-meta-row{ + display:inline-flex;align-items:center;gap:8px;min-width:100%;white-space:nowrap +} +.webui-upload-meta-chip{ + display:inline-flex;align-items:center;gap:6px;max-width:220px;height:30px;padding:0 8px 0 12px;border-radius:999px; + background:#f3f1ec;color:#5d5952;font-size:12px;line-height:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; + flex:0 0 auto +} +.webui-upload-meta-chip-label{ + display:block;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap +} +.webui-upload-meta-chip-remove{ + width:18px;height:18px;padding:0;border-radius:999px;display:grid;place-items:center;flex:0 0 auto;color:#7a766e +} +.webui-upload-meta-chip-remove:hover{background:rgba(0,0,0,.06);color:#2b2a27} +.webui-upload-meta-chip-remove svg{width:12px;height:12px} +.webui-input-shell{ + width:min(100%,940px);display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:center; + background:var(--webui-control-surface);border:0;border-radius:999px;padding:8px 10px 8px 12px; + box-shadow:inset 0 1px 0 rgba(255,255,255,.45);outline:none +} +.webui-upload-btn{ + width:30px;height:30px;border-radius:999px;color:#4b463f;display:grid;place-items:center;flex:0 0 auto +} +.webui-upload-btn:hover{background:rgba(0,0,0,.05);color:#1f1c18} +.webui-upload-btn svg{width:18px;height:18px;stroke-width:1.9} +.webui-sendbar{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex:0 0 auto} +.webui-sendbar-model{ + display:grid; + min-width:180px; + max-width:220px; + flex:0 1 220px; +} +.webui-sendbar-model .input{ + height:36px; + border:0; + border-radius:0; + background:transparent; + box-shadow:none; + padding-left:8px; + padding-right:6px; + color:#201d19; + font-size:12px; + letter-spacing:-.01em; + text-align:right; + text-align-last:right; + appearance:none; + background-image:none; +} +.webui-sendbar-model .input:focus{ + outline:none; + box-shadow:none; + border:0; +} +.webui-textarea{ + height:36px;min-height:36px;max-height:none;padding:8px 0 !important;margin:0;display:block;align-self:center;overflow:hidden;resize:none !important; + border-radius:0 !important;border:0 !important;background:transparent !important;line-height:20px;font-size:14px;color:#20201e +} +.webui-textarea:focus{outline:none !important;box-shadow:none !important} +.webui-textarea::placeholder{line-height:20px;color:#8d877d} +.webui-primary-btn{ + width:36px;height:36px;padding:0;border-radius:999px;background:#111;color:#fff;font-size:0;font-weight:700;display:grid;place-items:center;flex:0 0 auto +} +.webui-primary-btn svg{width:18px;height:18px;display:block} +.webui-primary-btn path{stroke:currentColor;stroke-width:2.2;stroke-linecap:round;stroke-linejoin:round} +.webui-primary-btn:disabled{opacity:.45;cursor:default} +.webui-auth-main{ + min-height:calc(100vh - 92px);display:grid;place-items:center;padding:28px 24px 36px +} +.webui-auth-shell{width:min(980px,100%);display:grid;grid-template-columns:minmax(0,1.1fr) minmax(360px,420px);gap:28px;align-items:center} +.webui-auth-copy{display:grid;gap:14px;padding:12px 4px} +.webui-auth-kicker{ + display:inline-flex;align-items:center;gap:8px;font-size:12px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:#6e6a64 +} +.webui-auth-card{ + padding:22px;display:grid;gap:16px;border-radius:28px; + background:rgba(255,255,255,.76);border:1px solid rgba(255,255,255,.76); + backdrop-filter:blur(18px);box-shadow:0 18px 48px rgba(15,23,42,.1) +} +.webui-auth-head{display:grid;gap:6px} +.webui-auth-title{font-size:28px;line-height:1.05;letter-spacing:-.05em;font-weight:700} +.webui-auth-subtitle{font-size:14px;line-height:1.6;color:#66635f} +.webui-auth-form{display:grid;gap:12px} +.webui-auth-form .input{ + height:46px;border-radius:16px;border-color:rgba(17,24,39,.08); + background:rgba(255,255,255,.88) +} +.webui-auth-submit{height:46px;border-radius:16px;font-size:14px} +.webui-auth-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap} +.webui-link{font-size:13px;color:#5e5b56;transition:color .15s} +.webui-link:hover{color:#111} + +.webui-masonry-main{width:100%;max-width:none;padding:18px 24px 24px} +.webui-masonry-shell{ + width:100%;max-width:none;margin:0;display:grid;grid-template-rows:auto minmax(0,1fr) auto;gap:16px; + min-height:calc(100vh - 96px) +} +.webui-masonry-head{display:flex;align-items:flex-start;justify-content:flex-start;gap:12px} +.webui-masonry-title{font-size:30px;line-height:1;font-weight:700;letter-spacing:-.05em;color:#191713} +.webui-masonry-feed{min-height:0;overflow:auto;padding-right:4px;display:grid;align-content:start;gap:24px} +.webui-masonry-empty{ + min-height:calc(100vh - 300px);display:grid;place-items:center;padding:28px 12px;color:#6f6a62 +} +.webui-masonry-empty[hidden]{display:none !important} +.webui-masonry-empty-card{width:min(100%,540px);text-align:center;display:grid;gap:10px} +.webui-masonry-empty-title{font-size:30px;line-height:1.05;font-weight:700;letter-spacing:-.05em;color:#1c1a17} +.webui-masonry-empty-text{font-size:14px;line-height:1.75} +.webui-masonry-batch{display:grid;gap:14px} +.webui-masonry-batch-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px} +.webui-masonry-batch-prompt{ + font-size:16px;font-weight:600;line-height:1.55;color:#181614;word-break:break-word;max-width:760px +} +.webui-masonry-batch-meta{display:flex;align-items:center;justify-content:flex-end;gap:6px;flex-wrap:wrap} +.webui-masonry-batch-chip{ + height:22px;padding:0 9px;border-radius:11px;display:inline-flex;align-items:center;justify-content:center; + background:#FAF9F5;color:#615a51;font-size:11px;font-weight:600;white-space:nowrap; + border:1px solid rgba(97,90,81,.07);box-shadow:inset 0 1px 0 rgba(255,255,255,.46) +} +.webui-masonry-batch-chip.is-round{ + background:#171511;color:#fff;border-color:#171511;box-shadow:none +} +.webui-masonry-batch-chip.is-count{ + min-width:40px;font-variant-numeric:tabular-nums +} +.webui-masonry-batch-chip.is-state{ + background:#f1eee7;color:#625c52 +} +.webui-masonry-batch-chip.is-state[data-state="generating"]{ + background:#efe9de;color:#6a6257 +} +.webui-masonry-batch-chip.is-state[data-state="success"]{ + background:#e4efe7;color:#355847 +} +.webui-masonry-batch-chip.is-state[data-state="partial"]{ + background:#eee6da;color:#7a5f38 +} +.webui-masonry-batch-chip.is-state[data-state="failed"]{ + background:#f1dfd9;color:#914738 +} +.webui-masonry-grid{ + --masonry-columns: 6; + display:grid; + grid-template-columns:repeat(var(--masonry-columns), minmax(0,1fr)); + gap:12px +} +.webui-masonry-tile{ + position:relative;display:block;margin:0;border-radius:14px;overflow:hidden; + background:transparent;box-shadow:none +} +.webui-masonry-tile-body{ + min-height:0;aspect-ratio:var(--tile-aspect, 1 / 1);display:grid;place-items:center;background: + linear-gradient(135deg,rgba(255,255,255,.46) 0%,rgba(255,255,255,.08) 34%,rgba(255,255,255,.28) 62%,rgba(255,255,255,.1) 100%), + linear-gradient(180deg,#f3efe7 0%,#ece6db 100%) +} +.webui-masonry-tile.is-pending .webui-masonry-tile-body{ + background: + linear-gradient(135deg,rgba(255,255,255,.56) 0%,rgba(255,255,255,.12) 34%,rgba(255,255,255,.34) 62%,rgba(255,255,255,.1) 100%), + linear-gradient(180deg,#f2ede4 0%,#e9e2d6 100%); + background-size:200% 200%,100% 100%; + animation:webui-masonry-pending-shift 5.6s ease-in-out infinite +} +.webui-masonry-tile.is-ready .webui-masonry-tile-body{min-height:0;background:transparent} +.webui-masonry-tile.is-filtered .webui-masonry-tile-body{background:#ede8df} +.webui-masonry-tile-link{display:block} +.webui-masonry-tile img{display:block;width:100%;height:auto;aspect-ratio:var(--tile-aspect, auto);object-fit:cover} +.webui-masonry-tile-badge{ + position:absolute;top:10px;left:10px;z-index:1;display:inline-flex;align-items:center;justify-content:center; + color:rgba(78,72,64,.72);font-size:10px;font-weight:700;letter-spacing:.02em +} +.webui-masonry-tile-label{ + display:inline-flex;align-items:center;justify-content:center; + color:#6b6459;font-size:12px;font-weight:600 +} +.webui-masonry-tile-progress{ + width:min(72%,124px);display:grid;gap:7px;padding:0;border-radius:0; + background:transparent;backdrop-filter:none +} +.webui-masonry-tile-progress-value{ + font-size:16px;line-height:1;font-weight:700;color:#4f493f;letter-spacing:-.03em;text-align:center; + font-variant-numeric:tabular-nums +} +.webui-masonry-tile-progress-track{ + height:3px;border-radius:999px;background:transparent;overflow:hidden +} +.webui-masonry-tile-progress-fill{ + height:100%;border-radius:999px;background:linear-gradient(90deg,#514b42 0%,#82786b 100%);transition:width .25s ease +} +@keyframes webui-masonry-pending-shift{ + 0%,100%{background-position:0% 50%,0 0} + 50%{background-position:100% 50%,0 0} +} +.webui-masonry-composer{ + position:sticky;bottom:0;z-index:2;padding-top:8px;background:linear-gradient(180deg,rgba(250,249,245,0),#faf9f5 30%) +} +.webui-masonry-input-shell{ + width:min(100%,920px);margin:0 auto;display:grid;gap:12px; + background:var(--webui-control-surface);border-radius:28px;padding:14px 14px 12px; + box-shadow:0 10px 30px rgba(24,22,20,.05), inset 0 1px 0 rgba(255,255,255,.38) +} +.webui-masonry-controls{display:flex;align-items:center;gap:8px;flex-wrap:wrap;min-width:0} +.webui-masonry-toggle{ + height:32px;padding:3px;border-radius:999px;display:inline-flex;align-items:center;gap:1px; + background:#FAF9F5 +} +.webui-masonry-toggle-btn{ + min-width:56px;height:26px;padding:0 9px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center; + color:#7d786f;font-size:10px;font-weight:600;transition:background .15s ease,color .15s ease,box-shadow .15s ease +} +.webui-masonry-toggle-btn.is-active{ + background:#111;color:#fff;box-shadow:none +} +.webui-masonry-toggle-btn:disabled{opacity:.45;cursor:default} +.webui-masonry-ratio{ + width:96px;height:32px;padding:0 10px;border-radius:999px;display:grid;grid-template-columns:1fr 2fr;align-items:center;column-gap:6px;background:#FAF9F5; +} +.webui-masonry-ratio-icon{ + width:10px;height:18px;border-radius:4px;background:#111;display:block;justify-self:center +} +.webui-masonry-ratio[data-ratio="1:1"] .webui-masonry-ratio-icon{width:15px;height:15px;border-radius:4px} +.webui-masonry-ratio[data-ratio="3:2"] .webui-masonry-ratio-icon{width:18px;height:12px;border-radius:4px} +.webui-masonry-ratio[data-ratio="16:9"] .webui-masonry-ratio-icon{width:19px;height:11px;border-radius:4px} +.webui-masonry-ratio[data-ratio="2:3"] .webui-masonry-ratio-icon{width:11px;height:18px;border-radius:4px} +.webui-masonry-ratio[data-ratio="9:16"] .webui-masonry-ratio-icon{width:10px;height:19px;border-radius:4px} +.webui-masonry-ratio .input{ + width:100%;min-width:0;height:26px;padding:0 14px 0 0;border:0;border-radius:0;background:transparent;box-shadow:none; + font-size:10px;font-weight:600;color:#111;background-position:right 0 center;background-size:10px 10px;text-align:left +} +.webui-masonry-ratio .input:focus{ + outline:none !important; + box-shadow:none !important; +} +.webui-masonry-toolbar{ + display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0 +} +.webui-masonry-actions{display:flex;align-items:center;justify-content:flex-end;flex:0 0 auto} +.webui-masonry-send{ + width:34px;min-width:34px;height:34px;padding:0;border-radius:999px; + font-size:10px;font-weight:700;display:inline-flex;align-items:center;justify-content:center +} +.webui-masonry-send svg{width:14px;height:14px;display:block;fill:none} +.webui-masonry-send path{stroke:currentColor;stroke-width:2.1;stroke-linecap:round;stroke-linejoin:round} +.webui-masonry-send rect{stroke:currentColor;stroke-width:2.1;stroke-linecap:round;stroke-linejoin:round;fill:none} + +/* Stat cards */ +.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:20px} +.stat-card{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-xl);padding:16px 18px} +.stat-label{font-size:12px;color:var(--fg-muted)} +.stat-value{font-size:26px;font-weight:600;margin-top:4px;line-height:1} + +/* Toolbar & tabs */ +.toolbar{display:flex;align-items:center;gap:8px;margin-bottom:12px;flex-wrap:wrap} +.toolbar-tabs{display:flex;gap:4px;flex:1;flex-wrap:wrap} +.tab{height:28px;padding:0 10px;border-radius:6px;font-size:12px;font-weight:500;color:var(--fg-muted);transition:background .15s,color .15s} +.tab:hover{background:var(--border)} +.tab.active{background:var(--fg);color:var(--bg-card)} +.tab-count{margin-left:4px;font-size:11px;opacity:.7} + +/* Table */ +.table-card{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-xl);overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch} +.table-wrap{overflow-x:auto} +.table-card>table{width:max-content;min-width:100%;border-collapse:collapse} +.table-freeze-last{--table-sticky-bg:var(--bg-card);--table-sticky-hover-bg:var(--bg)} +.table-freeze-last th:last-child, +.table-freeze-last td:last-child{position:sticky;right:0} +.table-freeze-last th:last-child{z-index:3;background:var(--table-sticky-bg)} +.table-freeze-last td:last-child{z-index:2;background:var(--table-sticky-bg);box-shadow:inset 1px 0 0 rgba(0,0,0,.05)} +.table-freeze-last tr:hover td:last-child{background:var(--table-sticky-hover-bg)} +table{width:100%;border-collapse:collapse} +th{background:var(--bg);font-size:11px;font-weight:600;color:var(--fg-muted);text-transform:uppercase;letter-spacing:.05em;padding:8px 12px;text-align:left;border-bottom:1px solid var(--border);white-space:nowrap} +td{font-size:12px;padding:10px 12px;border-bottom:1px solid var(--border);vertical-align:middle} +tr:last-child td{border-bottom:none} +tr:hover td{background:var(--bg)} +.token-cell{font-family:ui-monospace,monospace;font-size:11px} + +/* Badges */ +.badge{display:inline-block;font-size:11px;font-weight:600;padding:2px 7px;border-radius:20px;white-space:nowrap} +.badge-active{background:#ecfdf5;color:#059669} +.badge-cooling{background:#fff7ed;color:#ea580c} +.badge-expired,.badge-invalid,.badge-failed{background:#fef2f2;color:#dc2626} +.badge-basic{background:#f5f5f5;color:#555} +.badge-premium{background:#eff6ff;color:#2563eb} +.badge-pro{background:#faf5ff;color:#7c3aed} + +/* Buttons */ +.btn-ghost{border:1px solid var(--border);background:var(--bg-card)} +.btn-ghost:hover{background:var(--bg)} +.btn-danger{background:#fef2f2;color:#dc2626;border:1px solid #fecaca} +.btn-danger:hover{background:#fee2e2} +.btn-sm{height:26px;padding:0 10px;font-size:12px} +.btn-xs{height:22px;padding:0 8px;font-size:11px} + +/* Form elements */ +select.input{cursor:pointer;padding-right:28px;appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 8px center} +textarea.input{height:auto;padding:8px 10px;resize:vertical} +textarea.input.webui-textarea{padding:8px 0 !important;resize:none !important} + +@media (max-width: 960px){ + .admin-header-inner{ + height:auto;padding:10px 12px; + grid-template-columns:minmax(0,1fr) auto; + grid-template-areas: + "brand actions" + "nav nav"; + align-items:start;gap:8px;row-gap:8px + } + .admin-brand-wrap{grid-area:brand;gap:6px;min-height:30px;align-self:center} + .admin-brand-link{min-width:0;max-width:100%} + .admin-brand{font-size:13px;line-height:1} + .admin-nav{ + grid-area:nav;justify-content:flex-start;gap:4px;overflow-x:auto;overflow-y:hidden; + padding:0 0 2px;scrollbar-width:none;-ms-overflow-style:none;white-space:nowrap; + align-self:start + } + .admin-nav::-webkit-scrollbar{display:none} + .admin-nav-link{ + flex:0 0 auto;padding:6px 10px;font-size:13px;line-height:1;border-radius:999px;background:transparent + } + .admin-nav-link.active{background:#efe8dc} + .admin-header-right{grid-area:actions;gap:4px;align-self:center} + .admin-header-version{height:30px;padding:0 8px;font-size:10px} + .admin-header-version.has-update::after{top:6px;right:4px} + .admin-header-control{height:30px} + .admin-lang-trigger{min-width:44px;padding:0 5px 0 7px} + .admin-header-icon-btn{width:30px;min-width:30px} + .admin-username{display:none} + .webui-chat-layout,.webui-auth-shell,.webui-chatkit-shell{grid-template-columns:1fr} + .webui-main{padding:4px 0 6px} + .webui-page{padding-top:88px} + .webui-chat-layout{height:calc(100vh - 88px);min-height:0} + .webui-chatkit-main{padding:12px 12px 16px} + .webui-sidebar{grid-template-rows:auto minmax(0,1fr) auto;padding:8px 12px 14px;height:100%} + .webui-sidebar-settings{grid-template-columns:1fr;gap:6px;padding:0} + .webui-sidebar-caption{padding:2px 12px 0} + .webui-control{padding:0 8px} + .webui-thread-shell{padding:6px 12px 0} + .webui-composer{padding:0 12px 12px} + .webui-input-shell{grid-template-columns:1fr;gap:8px;border-radius:22px;padding:10px 12px} + .webui-upload-btn{display:none} + .webui-sendbar{justify-content:flex-end} + .webui-sendbar-model{min-width:0;max-width:none;flex:1 1 auto} + .webui-sidebar-headtitle{font-size:17px} + .webui-masonry-main{height:calc(100dvh - 88px);padding:14px 12px 18px;overflow:hidden} + .webui-masonry-shell{height:100%;min-height:0;gap:14px} + .webui-masonry-head{display:grid;justify-content:flex-start} + .webui-masonry-title{font-size:26px} + .webui-masonry-batch-head{display:grid} + .webui-masonry-grid{gap:10px} + .webui-masonry-tile{border-radius:12px} + .webui-masonry-input-shell{gap:10px;padding:12px} + .webui-masonry-controls{ + gap:6px;flex:1 1 auto;min-width:0;flex-wrap:nowrap; + overflow-x:auto;overflow-y:hidden;scrollbar-width:none;-ms-overflow-style:none + } + .webui-masonry-controls::-webkit-scrollbar{display:none} + .webui-masonry-toggle{height:30px} + .webui-masonry-toggle-btn{min-width:52px;height:24px;padding:0 7px} + .webui-masonry-ratio{width:90px;height:30px} + .webui-masonry-ratio .input{height:24px} + .webui-masonry-toolbar{ + display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:nowrap + } + .webui-masonry-actions{justify-content:flex-end;flex:0 0 auto} + .webui-masonry-send{width:34px;min-width:34px} + .webui-chatkit-shell{gap:18px;min-height:auto} + .webui-chatkit-stage{min-height:calc(100vh - 148px);align-content:center} + .webui-chatkit-stage-card{min-height:calc(100vh - 300px);padding:12px 0 8px;background:transparent} + .webui-chatkit-orb-wrap{gap:14px} + .webui-chatkit-orb{width:222px;height:222px} + .webui-chatkit-orb::before{inset:16px 28px 30px;filter:blur(22px)} + .webui-chatkit-orb::after{left:48px;right:48px;bottom:14px;height:22px;filter:blur(12px)} + .webui-chatkit-bubble-a{left:34px;top:52px;width:100px;height:100px} + .webui-chatkit-bubble-b{left:132px;top:38px;width:64px;height:64px} + .webui-chatkit-bubble-c{left:154px;top:102px;width:74px;height:74px} + .webui-chatkit-bubble-d{left:86px;top:148px;width:52px;height:52px} + .webui-chatkit-bubble-e{left:132px;top:138px;width:30px;height:30px} + .webui-chatkit-stage-copy{gap:10px;margin-top:24px} + .webui-chatkit-stage-text{font-size:14px;line-height:1.75} + .webui-chatkit-controls{margin-top:22px} + .webui-chatkit-icon-btn{width:38px;min-width:38px;height:38px} +} + +@media (max-width: 520px){ + .site-footer{right:12px;bottom:8px;font-size:10px} + .admin-header-inner{padding:10px 10px 8px} + .admin-brand{font-size:12px} + .admin-nav-link{padding:6px 9px;font-size:12px} + .admin-lang-popover{right:0;min-width:128px} + .admin-header-version{display:none} + .admin-version-modal-row{grid-template-columns:72px minmax(0,1fr);gap:8px} + .webui-empty-title{font-size:24px;line-height:1.05} + .webui-chatkit-stage-title{font-size:24px;line-height:1.05} + .webui-masonry-title{font-size:24px} + .webui-masonry-grid{gap:8px} + .webui-masonry-empty-title{font-size:24px} +} + +/* Modal */ +.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.3);z-index:300;display:flex;align-items:center;justify-content:center;opacity:0;pointer-events:none;transition:opacity .2s} +.modal-overlay.open{opacity:1;pointer-events:auto} +.modal{background:var(--bg-card);border-radius:var(--radius-xl);padding:20px;width:min(480px,92vw);box-shadow:var(--shadow-lg);transform:scale(.96);transition:transform .2s} +.modal-overlay.open .modal{transform:none} +.modal-title{font-size:15px;font-weight:600;margin-bottom:14px} +.modal-footer{display:flex;justify-content:flex-end;gap:8px;margin-top:16px} +.admin-version-modal{ + width:min(560px,92vw);max-height:min(80vh,720px); + display:grid;grid-template-rows:auto auto minmax(0,1fr) auto +} +.admin-version-modal-head{ + display:flex;align-items:flex-start;justify-content:space-between;gap:12px +} +.admin-version-modal-head .modal-title{margin-bottom:14px} +.admin-version-modal-badge{ + min-height:28px;padding:0 12px;border-radius:999px;display:inline-flex;align-items:center;flex:0 0 auto; + font-size:12px;font-weight:600;white-space:nowrap +} +.admin-version-modal-badge.is-update{background:#eff6ff;color:#2563eb} +.admin-version-modal-badge.is-current{background:#ecfdf5;color:#059669} +.admin-version-modal-badge.is-muted{background:#f5f5f5;color:#666} +.admin-version-modal-meta{display:grid;gap:8px;margin-bottom:14px} +.admin-version-modal-status{ + min-height:28px;padding:0 12px;border-radius:999px;display:inline-flex;align-items:center;width:max-content; + font-size:12px;font-weight:600 +} +.admin-version-modal-status.is-update{background:#eff6ff;color:#2563eb} +.admin-version-modal-status.is-current{background:#ecfdf5;color:#059669} +.admin-version-modal-status.is-muted{background:#f5f5f5;color:#666} +.admin-version-modal-status.is-hidden{display:none} +.admin-version-modal-row{display:grid;grid-template-columns:84px minmax(0,1fr);gap:10px;align-items:start} +.admin-version-modal-label{font-size:12px;color:#8a8478} +.admin-version-modal-value{font-size:12px;color:#26231f;word-break:break-word} +.admin-version-modal-notes{ + min-height:0;overflow:auto;padding:14px 16px;border-radius:16px;background:#f6f1e7; + color:#2e2a25;font-size:12px;line-height:1.7 +} +.admin-version-modal-notes > :first-child{margin-top:0} +.admin-version-modal-notes > :last-child{margin-bottom:0} +.admin-version-modal-notes h1, +.admin-version-modal-notes h2, +.admin-version-modal-notes h3, +.admin-version-modal-notes h4, +.admin-version-modal-notes h5, +.admin-version-modal-notes h6{margin:0 0 10px;font-size:13px;line-height:1.5;font-weight:700;color:#1f1c18} +.admin-version-modal-notes p{margin:0 0 10px} +.admin-version-modal-notes ul, +.admin-version-modal-notes ol{margin:0 0 10px 18px;padding:0} +.admin-version-modal-notes li + li{margin-top:4px} +.admin-version-modal-notes a{ + text-decoration:underline;text-underline-offset:2px; + overflow-wrap:anywhere;word-break:break-word +} +.admin-version-modal-notes strong{font-weight:700} +.admin-version-modal-notes em{font-style:italic} +.admin-version-modal-notes hr{height:1px;margin:12px 0;border:0;background:rgba(31,28,24,.1)} +.admin-version-modal-notes blockquote{ + margin:0 0 10px;padding-left:12px;border-left:2px solid rgba(31,28,24,.16);color:#6a6459 +} +.admin-version-modal-notes code{ + padding:1px 5px;border-radius:6px;background:rgba(31,28,24,.07); + font-family:'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace;font-size:11px +} +.admin-version-modal-notes pre{ + margin:0 0 10px;padding:10px 12px;border-radius:12px;background:#efe8dc;overflow:auto +} +.admin-version-modal-notes pre code{display:block;padding:0;background:transparent} +.admin-version-modal-link{display:inline-flex;align-items:center} + +/* Pagination */ +.pagination{display:flex;align-items:center;gap:6px;padding:10px 14px;border-top:1px solid var(--border);flex-wrap:wrap} +.page-btn{width:28px;height:28px;border-radius:6px;font-size:12px;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--border);background:var(--bg-card);transition:background .1s} +.page-btn:hover{background:var(--bg)} +.page-btn.active{background:var(--fg);color:var(--bg-card);border-color:var(--fg)} +.page-info{font-size:12px;color:var(--fg-muted);margin-left:auto} + +/* Misc */ +.cb{width:14px;height:14px;accent-color:var(--fg);cursor:pointer} +.action-btns{display:flex;gap:4px} +.empty-state{text-align:center;padding:40px;color:var(--fg-muted);font-size:13px} diff --git a/app/statics/favicon.ico b/app/statics/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..1e4505886c2bdb36c01dada0d7c58698df36e2b7 Binary files /dev/null and b/app/statics/favicon.ico differ diff --git a/app/statics/i18n/de.json b/app/statics/i18n/de.json new file mode 100644 index 0000000000000000000000000000000000000000..7559c74241578159b6197685fa8a9322bd88048d --- /dev/null +++ b/app/statics/i18n/de.json @@ -0,0 +1,519 @@ +{ + "common": { + "invalidKey": "Ungültiger Schlüssel", + "connectionFailed": "Verbindung fehlgeschlagen" + }, + "login": { + "adminPageTitle": "Grok2API - Admin", + "adminTitle": "Administrationsbereich", + "adminSubtitle": "Geben Sie das Administratorpasswort ein, um fortzufahren", + "adminPlaceholder": "Administratorpasswort", + "continue": "Weiter", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "Geben Sie den Zugriffsschlüssel ein", + "webuiPlaceholder": "Zugriffsschlüssel", + "enter": "Öffnen", + "goToAdmin": "Zum Administrationsbereich" + }, + "webui": { + "header": { + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "Chats", + "newChat": "Neuer Chat", + "toggleSidebar": "Seitenleiste umschalten", + "upload": "Datei hochladen", + "noSessions": "Noch keine Chats", + "untitled": "Neuer Chat", + "rename": "Umbenennen", + "delete": "Löschen", + "edit": "Bearbeiten", + "copy": "Kopieren", + "regenerate": "Neu generieren", + "like": "Gefällt mir", + "dislike": "Gefällt mir nicht", + "reasoning": "Denken", + "save": "Speichern", + "cancel": "Abbrechen", + "confirm": "Bestätigen", + "copySuccess": "Kopiert", + "renamePrompt": "Chat umbenennen", + "deleteConfirm": "Diesen Chat löschen?", + "modelLabel": "Modell", + "emptyTitle": "Grok Chat", + "empty": "Beginnen Sie eine neue Unterhaltung, indem Sie eine Nachricht senden.", + "promptPlaceholder": "Geben Sie Ihre Nachricht ein. Enter zum Senden, Shift+Enter für eine neue Zeile.", + "editPlaceholder": "Diese Nachricht bearbeiten", + "stop": "Stoppen", + "send": "Senden", + "statusReady": "Bereit", + "statusConnecting": "Verbinden...", + "statusThinking": "Denkt...", + "statusGenerating": "Generiert...", + "statusDone": "Abgeschlossen", + "statusStopped": "Gestoppt", + "statusFailed": "Fehlgeschlagen", + "statusInitFailed": "Initialisierung fehlgeschlagen", + "errors": { + "enterPrompt": "Bitte geben Sie eine Nachricht ein", + "imageRequired": "Für die Bildbearbeitung ist mindestens ein Referenzbild erforderlich", + "imageOnly": "Die Bildbearbeitung unterstützt nur Bild-Uploads", + "videoImageOnly": "Die Videogenerierung unterstützt nur Bild-Uploads als Referenz", + "imageProxyRequired": "Bild konnte nicht geladen werden. Konfigurieren Sie die APP-Basis-URL und ändern Sie das Bildausgabeformat in local_url, local_md oder base64.", + "videoProxyRequired": "Das Laden des Videos ergab 403. Öffnen Sie die Admin-Seite, konfigurieren Sie die APP-Basis-URL und ändern Sie das Videoausgabeformat in den lokalen Proxy-Modus (local_url oder local_html). Versuchen Sie es dann erneut.", + "requestFailed": "Anfrage fehlgeschlagen", + "initFailed": "Initialisierung der Chat-Seite fehlgeschlagen" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "voiceLabel": "Stimme", + "personalityLabel": "Persönlichkeit", + "speedLabel": "Geschwindigkeit", + "start": "Start", + "pause": "Pause", + "mute": "Stumm", + "unmute": "Stummschaltung aufheben", + "newSession": "Neue Sitzung", + "statusIdle": "Nicht verbunden", + "statusConnecting": "Verbindung wird hergestellt", + "statusLive": "Live", + "statusMuted": "Stumm", + "statusPaused": "Pausiert", + "statusError": "Fehlgeschlagen", + "idleText": "Klicken Sie und autorisieren Sie den Zugriff, um über ChatKit-Sprachsitzungen eine Verbindung zu Grok Voice herzustellen.", + "connectingText": "Grok-Voice-Sitzung wird angefordert und mit LiveKit verbunden...", + "liveText": "Verbindung hergestellt. Sie können jetzt direkt mit Grok sprechen.", + "outputMutedText": "Der Lautsprecher ist stummgeschaltet, Sie können aber weiter sprechen.", + "pausedText": "Die Sitzung ist pausiert. Klicken Sie auf Start, um die aktuelle Sprachsitzung fortzusetzen.", + "errorText": "Die Verbindung konnte nicht hergestellt werden. Prüfen Sie den Mikrofonzugriff und versuchen Sie es erneut.", + "endedText": "Die Sprachsitzung wurde beendet. Sie können jederzeit neu starten.", + "livekitLoadFailed": "LiveKit-SDK konnte nicht geladen werden", + "invalidToken": "Ungültige Antwort für Sprach-Token" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "qualitySpeed": "Tempo", + "qualityQuality": "Qualität", + "modeRounds": "Runden", + "modeCycles": "Zyklen", + "promptPlaceholder": "Beschreiben Sie das gewünschte Bild. Enter zum Generieren, Shift+Enter für eine neue Zeile.", + "generate": "Generieren", + "stop": "Stoppen", + "openImage": "Bild öffnen", + "statusReady": "Bereit", + "statusConnecting": "Verbinden...", + "statusGenerating": "Wird generiert", + "statusCompleted": "Abgeschlossen", + "statusStopped": "Gestoppt", + "statusFailed": "Fehlgeschlagen", + "statusSuccess": "Erfolgreich", + "statusPartialFailure": "Teilweise fehlgeschlagen", + "statusBatchFailed": "Fehlgeschlagen", + "emptyTitle": "Mit einem Prompt beginnen", + "emptyText": "Geben Sie einen Prompt ein und die Bilder erscheinen hier der Reihe nach.", + "roundLabel": "Runde {n}", + "batchFiltered": "Gefiltert", + "errors": { + "enterPrompt": "Bitte geben Sie einen Prompt ein", + "requestFailed": "Anfrage fehlgeschlagen", + "initFailed": "Initialisierung der Masonry-Seite fehlgeschlagen" + } + } + }, + "header": { + "account": "Kontoverwaltung", + "config": "Konfigurationsverwaltung", + "cache": "Cache-Verwaltung", + "languageLabel": "Sprache", + "logout": "Abmelden", + "versionDialogTitle": "Version", + "versionCurrent": "Aktuell", + "versionLatest": "Neueste", + "versionPublishedAt": "Veröffentlicht", + "versionUpToDate": "Sie verwenden bereits die neueste Version.", + "versionUpdateAvailable": "Eine neue Version ist verfügbar.", + "versionChecking": "Suche nach Updates...", + "versionRefresh": "Jetzt prüfen", + "versionUnavailable": "Update-Prüfung fehlgeschlagen.", + "versionNotesEmpty": "Keine Versionshinweise verfügbar.", + "versionOpenRelease": "Release öffnen", + "versionClose": "Schließen" + }, + "account": { + "pageTitle": "Grok2API - Konten", + "pageHeading": "Kontoverwaltung", + "pageSubtitle": "Verwalten Sie den xAI-Kontopool, den Quotenstatus und den Laufzeitstatus von Grok2API.", + "actionImport": "Konten importieren", + "actionAdd": "Konto hinzufügen", + "actionImportShort": "Import", + "actionAddShort": "Neu", + "sectionOverview": "Übersicht", + "sectionTable": "Kontoliste", + "statTotal": "Konten gesamt", + "statActive": "Aktiv", + "statCooling": "Ratenbegrenzt", + "statInvalid": "Fehlerhaft", + "statDisabled": "Deaktiviert", + "statCalls": "Aufrufe gesamt", + "statSuccessTotal": "Erfolgreiche Aufrufe", + "statAuto": "Auto-Guthaben", + "statFast": "Fast-Guthaben", + "statExpert": "Expert-Guthaben", + "statHeavy": "Heavy-Guthaben", + "filterStatusLabel": "Status", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "Typ", + "filterStatusAll": "Alle", + "filterStatusActive": "Aktiv", + "filterStatusCooling": "Ratenbegrenzt", + "filterStatusInvalid": "Fehlerhaft", + "filterStatusDisabled": "Deaktiviert", + "filterNsfwAll": "Alle", + "filterNsfwEnabled": "Ein", + "filterNsfwDisabled": "Aus", + "filterTypeAll": "Alle", + "filter": "Filtern", + "export": "Daten exportieren", + "batchNsfw": "NSFW aktivieren", + "batchNsfwDisable": "NSFW deaktivieren", + "rowActionNotSupported": "Der aktuelle Status unterstützt diese Aktion nicht", + "batchRefresh": "Auswahl aktualisieren", + "batchDisable": "Auswahl deaktivieren", + "batchRestore": "Auswahl wiederherstellen", + "batchDelete": "Auswahl löschen", + "colToken": "Token", + "colType": "Kontotyp", + "colStatus": "Laufzeitstatus", + "colQuota": "Quote", + "colSuccess": "Erfolgreich", + "colFail": "Fehlgeschlagen", + "colRate": "Erfolgsquote", + "colLastUsed": "Zuletzt verwendet", + "colActions": "Aktionen", + "actionCopy": "Kopieren", + "actionRefresh": "Quote aktualisieren", + "actionDisable": "Konto deaktivieren", + "actionRestore": "Konto wiederherstellen", + "actionEdit": "Bearbeiten", + "actionDelete": "Löschen", + "empty": "Keine Konten verfügbar. Verwenden Sie „Konten importieren“ oder „Konto hinzufügen“.", + "pageInfo": "{n} gesamt", + "pageIndicator": "Seite {current} / {total}", + "pageSizeOption": "{n} / Seite", + "addTitle": "Konto hinzufügen", + "addHint": "Geben Sie ein Token pro Zeile ein. Vorhandene Tokens werden automatisch übersprungen.", + "addPlaceholder": "Tokens einfügen, eines pro Zeile...", + "importTitle": "Konten importieren", + "importHintDefault": "Unterstützt .txt (ein Token pro Zeile) und .json ({pool:[tokens]}).", + "importHintJson": "Die JSON-Datei enthält bereits Informationen zum Kontotyp. Eine zusätzliche Auswahl ist nicht erforderlich.", + "importHintTxt": "Geben Sie ein Token pro Zeile ein. Importierte Tokens werden dem ausgewählten Kontotyp hinzugefügt.", + "labelType": "Typ", + "labelFile": "Datei", + "editTitle": "Konto bearbeiten", + "editTokenPlaceholder": "Aktualisierten Token eingeben", + "exportTitle": "Konten exportieren", + "exportCountPrefix": "", + "exportCountSuffix": " Tokens", + "exportJson": "JSON-Format (vollständig)", + "exportTxt": "TXT-Format (nur Tokens)", + "confirmTitle": "Aktion bestätigen", + "cancel": "Abbrechen", + "confirm": "Bestätigen", + "save": "Änderungen speichern", + "noFile": "Keine Datei ausgewählt", + "copied": "Kopiert", + "copyFailed": "Kopieren fehlgeschlagen", + "loadFailed": "Laden fehlgeschlagen", + "notFound": "Konto nicht gefunden", + "enterToken": "Token eingeben", + "selectFile": "Datei auswählen", + "readFileFailed": "Datei konnte nicht gelesen werden", + "jsonInvalid": "Ungültiges JSON-Format", + "jsonShapeInvalid": "Ungültige JSON-Struktur. Erwartet wurde {pool:[tokens]}.", + "jsonEmpty": "Keine importierbaren Tokens in der JSON-Datei gefunden", + "fileEmpty": "Keine importierbaren Tokens in der Datei gefunden", + "adding": "{n} Konten werden hinzugefügt…", + "addDone": "Konten hinzugefügt", + "addFailed": "Konten konnten nicht hinzugefügt werden", + "importing": "{n} Konten werden importiert…", + "importDone": "Import abgeschlossen", + "importJsonDone": "Import abgeschlossen: {n} Konten verarbeitet", + "importFailed": "Import fehlgeschlagen", + "saving": "Änderungen werden gespeichert…", + "editDone": "Änderungen gespeichert", + "editFailed": "Änderungen konnten nicht gespeichert werden", + "saveResult": "{prefix}: {count} Konten hinzugefügt", + "saveResultSkipped": "{prefix}: {count} hinzugefügt, {skipped} waren bereits vorhanden", + "exportEmpty": "Keine Konten zum Exportieren vorhanden", + "deleteConfirmTitle": "Löschen bestätigen", + "deleteConfirmOne": "{token} löschen?
Diese Aktion kann nicht rückgängig gemacht werden.", + "deleteConfirmMany": "{n} Konten löschen?
Diese Aktion kann nicht rückgängig gemacht werden.", + "deleting": "{n} Konten werden gelöscht…", + "deleteDone": "{n} gelöscht", + "deleteFailed": "Löschen fehlgeschlagen", + "refreshing": "Quoteninformationen für {n} Konten werden aktualisiert…", + "refreshDone": "Aktualisierung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "refreshFailed": "Aktualisierung fehlgeschlagen", + "disableConfirmTitle": "Konto deaktivieren", + "disableConfirmBody": "{token} deaktivieren?
Das Konto nimmt bis zur Wiederherstellung nicht mehr an der Anfrageverteilung teil.", + "disablingOne": "Konto wird deaktiviert…", + "disableDone": "Konto deaktiviert", + "restoreConfirmTitle": "Konto wiederherstellen", + "restoreConfirmBody": "{token} wiederherstellen?
Das Konto nimmt danach wieder an der Anfrageverteilung teil.", + "restoringOne": "Konto wird wiederhergestellt…", + "restoreDone": "Konto wiederhergestellt", + "batchDisableConfirmTitle": "Konten deaktivieren", + "batchDisableConfirmBody": "Die ausgewählten {n} Konten deaktivieren?
Deaktivierte Konten werden nicht für Anfragen verwendet und können später wiederhergestellt werden.", + "disablingMany": "{n} Konten werden deaktiviert…", + "disableManyDone": "Deaktivierung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "batchRestoreConfirmTitle": "Konten wiederherstellen", + "batchRestoreConfirmBody": "Die ausgewählten {n} Konten wiederherstellen?
Wiederhergestellte Konten werden erneut für Anfragen verwendet.", + "restoringMany": "{n} Konten werden wiederhergestellt…", + "restoreManyDone": "Wiederherstellung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "nsfwConfirmTitle": "NSFW aktivieren", + "nsfwConfirmBody": "NSFW für {n} ausgewählte Konten aktivieren?", + "nsfwEnablingOne": "NSFW wird aktiviert…", + "nsfwEnabling": "NSFW wird für {n} Konten aktiviert…", + "nsfwDone": "NSFW-Aktualisierung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "nsfwDisablingOne": "NSFW wird deaktiviert…", + "nsfwDisableDone": "NSFW-Deaktivierung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "operationFailed": "Vorgang fehlgeschlagen", + "unknown": "Unbekannt", + "na": "—", + "pool": { + "autoRecommended": "Automatisch erkennen (empfohlen)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" + }, + "status": { + "active": "Aktiv", + "cooling": "Ratenbegrenzt", + "disabled": "Deaktiviert", + "expired": "Abgelaufen", + "invalid": "Fehlerhaft" + } + }, + "config": { + "pageTitle": "Grok2API - Konfigurationsverwaltung", + "pageHeading": "Konfigurationsverwaltung", + "pageSubtitle": "Verwalten Sie die Laufzeitparameter von Grok2API und das Standardverhalten des Dienstes.", + "resetShort": "Zurücksetzen", + "saveShort": "Speichern", + "resetChanges": "Änderungen zurücksetzen", + "saveChanges": "Änderungen speichern", + "unsavedDefault": "Nicht gespeicherte Änderungen vorhanden", + "unsavedSingle": "1 nicht gespeicherte Änderung vorhanden", + "unsavedMultiple": "{n} nicht gespeicherte Änderungen vorhanden", + "discardShort": "Rückgängig", + "saveBarShort": "Speichern", + "discardChanges": "Änderungen verwerfen", + "randomize": "Wert generieren", + "loadFailed": "Konfiguration konnte nicht geladen werden: {message}", + "saving": "Änderungen werden gespeichert...", + "saveSuccess": "Änderungen gespeichert", + "saveFailed": "Änderungen konnten nicht gespeichert werden: {message}", + "resetSuccess": "Nicht gespeicherte Änderungen verworfen", + "disabledTip": { + "appUrlRequired": "Konfigurieren Sie zuerst die APP-Basis-URL" + }, + "schema": { + "tabs": { + "system": "System", + "features": "Funktionen", + "schedule": "Zeitplanung", + "proxy": "Netzwerk", + "cache": "Cache-Speicher", + "image": "Bildpipeline" + }, + "groups": { + "baseAccess": "Zugriffskontrolle", + "features": "Kernfunktionen", + "mediaFormat": "Medienausgabe", + "refreshSchedule": "Quotenaktualisierung", + "selection": "Auswahl-Nebenläufigkeit", + "batchConcurrency": "Batch-Konkurrenz", + "egressProxy": "Ausgehender Proxy", + "clearance": "Cloudflare Clearance", + "retry": "Wiederholungsrichtlinie", + "timeouts": "Zeitlimits", + "imageProtocol": "NSFW und Bild-Streaming", + "logging": "Protokollierung", + "localMediaCache": "Lokaler Medien-Cache" + }, + "options": { + "imageFormat": { + "grokUrl": "URL (Grok-Nativ)", + "localUrl": "URL (Lokaler Proxy)", + "grokMarkdown": "Markdown (Grok-Nativ)", + "localMarkdown": "Markdown (Lokaler Proxy)", + "base64": "Base64 (Inline)" + }, + "videoFormat": { + "grokUrl": "URL (Grok-Nativ)", + "localUrl": "URL (Lokaler Proxy)", + "grokHtml": "HTML (Grok-Nativ)", + "localHtml": "HTML (Lokaler Proxy)" + }, + "proxyMode": { + "direct": "Direkt", + "singleProxy": "Fester Proxy", + "proxyPool": "Proxy-Pool" + }, + "clearanceMode": { + "none": "Deaktiviert", + "manual": "Manuell", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { "label": "APP-Basis-URL" }, + "appKey": { "label": "APP-Zugriffspasswort" }, + "apiKey": { "label": "API-Zugriffsschlüssel" }, + "webuiEnabled": { "label": "WebUI aktivieren" }, + "webuiKey": { "label": "WebUI-Zugriffspasswort" }, + "temporary": { "label": "Temporäre Sitzungen" }, + "memory": { "label": "Konversationsspeicher" }, + "stream": { "label": "Standard-Streaming" }, + "thinking": { "label": "Standard-Ausgabe für Reasoning" }, + "autoChatModeFallback": { "label": "AUTO-Chatmodus-Fallback" }, + "thinkingSummary": { "label": "Kompakte Reasoning-Ausgabe" }, + "dynamicStatsig": { "label": "Dynamisches Statsig" }, + "enableNsfw": { "label": "NSFW-Erzeugung zulassen" }, + "showSearchSources": { "label": "Quellen an Inhalt anhängen", "desc": "Suchquellen werden immer im Feld search_sources ausgegeben. Diese Option steuert, ob zusätzlich ein ## Sources-Abschnitt an den Inhalt angehängt wird (für Abwärtskompatibilität mit textbasierten Clients)." }, + "customInstruction": { "label": "Globale Zusatzanweisung" }, + "imageFormat": { "label": "Bildausgabeformat", "desc": "grok_url und grok_md geben die native Grok-CDN-Adresse standardmäßig direkt zurück. local_* Modi laden Assets zuerst auf den Server herunter und stellen sie über den lokalen Proxy bereit. base64 gibt eine eingebettete Data URI zurück. Wenn der Imagine-Public-Bildproxy aktiviert ist, werden vom WebSocket zurückgegebene imagine-public-Bilder ebenfalls lokal proxied." }, + "imaginePublicImageProxy": { "label": "Imagine-Public-Bildproxy", "desc": "Wenn aktiviert, werden vom WebSocket zurückgegebene imagine-public-Bilder auf den Server heruntergeladen und über den lokalen Proxy ausgeliefert. Wenn deaktiviert, werden öffentliche Bilder direkt zurückgegeben." }, + "videoFormat": { "label": "Videoausgabeformat" }, + "refreshEnabled": { "label": "Quotenaktualisierung aktivieren", "desc": "Wenn aktiviert, wechselt das System automatisch in den Quotenaktualisierungsmodus. Wenn deaktiviert, wechselt es automatisch in den Auto-Retry-Modus.", "help": "Ein: Quotenaktualisierung. Der Scheduler synchronisiert regelmäßig echte Quoten, die Auswahl erfolgt nach Bewertung.\nAus: Auto-Retry-Modus. Keine aktive upstream-Abfrage, zufällige Auswahl und automatischer Kontowechsel bei Fehlern mit bis zu 5 Wiederholungen.\nEmpfehlung: Bei mehr als 10.000 Konten ausschalten, um upstream 429 durch aktive Abfragen zu vermeiden." }, + "maxInflight": { "label": "Max. laufende Anfragen pro Konto", "desc": "Maximale Anzahl gleichzeitig laufender Anfragen pro Konto. Konten am Limit werden von der Auswahl übersprungen (für beide Modi gemeinsam)." }, + "basicInterval": { "label": "Basic-Zyklus (s)", "desc": "Gemeinsamer Zyklus für den Basic-Pool: wird im Quota-Modus für den Hintergrund-Refresh und im Random-Modus für die 429-Abkühlung verwendet. Standardwert: 86400s." }, + "superInterval": { "label": "Super-Zyklus (s)", "desc": "Gemeinsamer Zyklus für den Super-Pool: wird im Quota-Modus für den Hintergrund-Refresh und im Random-Modus für die 429-Abkühlung verwendet. Standardwert: 7200s." }, + "heavyInterval": { "label": "Heavy-Zyklus (s)", "desc": "Gemeinsamer Zyklus für den Heavy-Pool: wird im Quota-Modus für den Hintergrund-Refresh und im Random-Modus für die 429-Abkühlung verwendet. Standardwert: 7200s." }, + "usageConcurrency": { "label": "Aktualisierungs-Konkurrenz", "desc": "Maximale Anzahl paralleler usage-Aufrufe während der Quotenaktualisierung." }, + "onDemandMinInterval": { "label": "On-Demand-Aktualisierungsintervall (s)", "desc": "Drosselungsfenster für durch Requests ausgelöste Aktualisierungen, z. B. nach 429. Wiederholte Auslöser innerhalb des Intervalls werden zu einer Aktualisierung zusammengefasst." }, + "imageCacheMaxMb": { "label": "Bild-Cache-Limit (MB)", "desc": "0 deaktiviert das Limit. Gilt nur für lokal per Proxy gespeicherte Mediendateien. Wird das Limit überschritten, werden zuerst die ältesten Dateien entfernt, bis die Nutzung wieder auf 60% des Limits fällt." }, + "videoCacheMaxMb": { "label": "Video-Cache-Limit (MB)", "desc": "0 deaktiviert das Limit. Gilt nur für lokal per Proxy gespeicherte Mediendateien. Wird das Limit überschritten, werden zuerst die ältesten Dateien entfernt, bis die Nutzung wieder auf 60% des Limits fällt." }, + "nsfwConcurrency": { "label": "Konkurrenz für NSFW-Aktivierung" }, + "refreshConcurrency": { "label": "Usage-Aktualisierungskonkurrenz" }, + "assetUploadConcurrency": { "label": "Asset-Upload-Konkurrenz" }, + "assetListConcurrency": { "label": "Asset-Listen-Konkurrenz" }, + "assetDeleteConcurrency": { "label": "Asset-Lösch-Konkurrenz" }, + "proxyMode": { "label": "Proxy-Modus" }, + "proxyUrl": { "label": "Primäre Proxy-URL" }, + "resourceProxyUrl": { "label": "Ressourcen-Proxy-URL" }, + "proxyPool": { "label": "Primärer Proxy-Pool" }, + "resourceProxyPool": { "label": "Ressourcen-Proxy-Pool" }, + "skipSslVerify": { "label": "SSL-Prüfung überspringen" }, + "clearanceMode": { "label": "Clearance-Modus" }, + "browserFingerprint": { "label": "Browser-Fingerprint" }, + "userAgent": { "label": "User-Agent" }, + "cfCookies": { "label": "Cloudflare-Cookies" }, + "flaresolverrUrl": { "label": "FlareSolverr-URL" }, + "challengeTimeout": { "label": "Challenge-Timeout (s)" }, + "refreshInterval": { "label": "Aktualisierungsintervall (s)" }, + "maxRetries": { "label": "Konto-Wiederholungslimit" }, + "retryCodes": { "label": "Retry-Statuscodes" }, + "resetSessionCodes": { "label": "Statuscodes für Sitzungsreset" }, + "chatTimeout": { "label": "Chat-Timeout (s)" }, + "imageTimeout": { "label": "Bild-Timeout (s)" }, + "videoTimeout": { "label": "Video-Timeout (s)" }, + "voiceTimeout": { "label": "Sprach-Timeout (s)" }, + "nsfwTimeout": { "label": "NSFW-Timeout (s)" }, + "assetUploadTimeout": { "label": "Asset-Upload-Timeout (s)" }, + "assetDownloadTimeout": { "label": "Asset-Download-Timeout (s)" }, + "assetListTimeout": { "label": "Asset-Listen-Timeout (s)" }, + "assetDeleteTimeout": { "label": "Asset-Lösch-Timeout (s)" }, + "streamTimeout": { "label": "Streaming-Leerlauf-Timeout (s)" }, + "interRoundWait": { "label": "Wartezeit zwischen Runden (s)" }, + "fileLogLevel": { "label": "Datei-Protokollebene", "desc": "Mindeststufe für Protokolldateien, unabhängig von der Konsole konfigurierbar. Standard: INFO." }, + "logMaxFiles": { "label": "Protokoll-Aufbewahrung (Tage)", "desc": "Maximale Anzahl täglicher Protokolldateien bei der Rotation. Standard: 7." } + } + } + }, + "cache": { + "pageTitle": "Grok2API - Cache-Verwaltung", + "pageHeading": "Cache-Verwaltung", + "pageSubtitle": "Lokale Cache-Dateien, Speichergrenzen und Online-Assets der Konten anzeigen und verwalten.", + "sectionOverview": "Übersicht", + "statImageCount": "Bild-Cache-Dateien", + "statImageSize": "Bild-Cache-Größe", + "statVideoCount": "Video-Cache-Dateien", + "statVideoSize": "Video-Cache-Größe", + "usageSummaryUnlimited": "Verwendet {used} · Unbegrenzt", + "usageSummaryLimited": "Verwendet {used} / {limit} · {percent}", + "sectionDetails": "Details", + "tabLocal": "Lokaler Cache", + "tabLocalImage": "Lokale Bilder", + "tabLocalVideo": "Lokale Videos", + "tabOnline": "Online-Assets", + "typeImage": "Bilder", + "typeVideo": "Videos", + "typeImageNoun": "Bild", + "typeVideoNoun": "Video", + "clearCurrent": "Aktuellen Cache leeren", + "deleteSelected": "Auswahl löschen", + "clearSelected": "Auswahl bereinigen", + "colFileName": "Dateiname", + "colSize": "Größe", + "colModified": "Zuletzt geändert", + "colActions": "Aktionen", + "colToken": "Token", + "colFileCount": "Dateien", + "onlineAssetLead": "Online-Assets", + "onlineAssetDesc": "sind Bilder und Anhänge, die auf der Grok-Plattform gespeichert sind. Die Bereinigung betrifft nur Remote-Dateien und löscht keinen lokalen Cache.", + "loadAssets": "Asset-Bestand laden", + "clearAll": "Alle löschen", + "cancel": "Abbrechen", + "assetSummaryIdle": "Online-Assets rechts laden", + "assetSummary": "{accounts} Konten · {files} Dateien", + "pageIndicator": "Seite {current} / {total}", + "pageSizeOption": "{n} / Seite", + "fileCount": "{n} Dateien", + "emptyLocal": "Keine Cache-Dateien gefunden", + "emptyAssetsIdle": "Klicke oben rechts, um die Online-Assets zu laden", + "emptyAccounts": "Keine Kontodaten verfügbar", + "actionView": "Ansehen", + "actionDelete": "Löschen", + "actionClear": "Bereinigen", + "loadFailed": "Laden fehlgeschlagen: {message}", + "clearLocalConfirm": "Alle lokalen {type}-Cache-Dateien löschen?", + "clearLocalDone": "{count} {type}-Datei(en) entfernt", + "clearFailed": "Bereinigung fehlgeschlagen: {message}", + "deleted": "Gelöscht", + "deleteSelectedConfirm": "Die ausgewählten {n} Datei(en) löschen?", + "deleteSelectedDone": "{count} Datei(en) gelöscht", + "deleteFailed": "Löschen fehlgeschlagen: {message}", + "viewUnavailable": "Für diese Datei ist keine Vorschau verfügbar", + "loading": "Wird geladen...", + "refreshList": "Liste aktualisieren", + "expand": "Erweitern", + "collapse": "Einklappen", + "clearTokenConfirm": "Alle Online-Assets für {token} löschen?", + "clearTokenDone": "{count} Datei(en) gelöscht", + "clearSelectedConfirm": "Online-Assets der ausgewählten {n} Konten löschen?", + "clearAllConfirm": "Online-Assets für alle {n} Konten löschen? Diese Aktion kann nicht rückgängig gemacht werden.", + "clearingAssets": "Online-Assets werden bereinigt...", + "clearAllDone": "Bereinigung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "cancelled": "Abgebrochen", + "clearFailedPlain": "Bereinigung fehlgeschlagen", + "connectionInterrupted": "Verbindung unterbrochen", + "startFailed": "Start fehlgeschlagen: {message}", + "cancelInProgress": "Abbruch angefordert. Bitte warten Sie, bis der aktuelle Batch abgeschlossen ist.", + "na": "—" + } +} diff --git a/app/statics/i18n/en.json b/app/statics/i18n/en.json new file mode 100644 index 0000000000000000000000000000000000000000..3fed2d4775f68ad415ab8fdc611e182f6d7236a4 --- /dev/null +++ b/app/statics/i18n/en.json @@ -0,0 +1,708 @@ +{ + "common": { + "invalidKey": "Invalid key", + "connectionFailed": "Connection failed" + }, + "login": { + "adminPageTitle": "Grok2API - Admin", + "adminTitle": "Admin Panel", + "adminSubtitle": "Enter admin password to continue", + "adminPlaceholder": "Admin password", + "continue": "Continue", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "Enter access key", + "webuiPlaceholder": "Access Key", + "enter": "Enter", + "goToAdmin": "Go to Admin Panel" + }, + "header": { + "account": "Account Management", + "config": "Configuration Management", + "cache": "Cache Management", + "languageLabel": "Language", + "logout": "Sign Out", + "versionDialogTitle": "Version", + "versionCurrent": "Current", + "versionLatest": "Latest", + "versionPublishedAt": "Published", + "versionUpToDate": "You are already on the latest version.", + "versionUpdateAvailable": "A new version is available.", + "versionChecking": "Checking for updates...", + "versionRefresh": "Check Now", + "versionUnavailable": "Failed to check for updates.", + "versionNotesEmpty": "No release notes available.", + "versionOpenRelease": "Open Release", + "versionClose": "Close" + }, + "webui": { + "header": { + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "Chats", + "newChat": "New Chat", + "toggleSidebar": "Toggle sidebar", + "upload": "Upload file", + "noSessions": "No chats yet", + "untitled": "New Chat", + "rename": "Rename", + "delete": "Delete", + "edit": "Edit", + "copy": "Copy", + "regenerate": "Regenerate", + "like": "Like", + "dislike": "Dislike", + "reasoning": "Thinking", + "save": "Save", + "cancel": "Cancel", + "confirm": "Confirm", + "copySuccess": "Copied", + "renamePrompt": "Rename session", + "deleteConfirm": "Delete this session?", + "modelLabel": "Model", + "emptyTitle": "Grok Chat", + "empty": "Start a new conversation by sending a message.", + "promptPlaceholder": "Type your message. Press Enter to send and Shift+Enter for a new line.", + "editPlaceholder": "Edit this message", + "stop": "Stop", + "send": "Send", + "statusReady": "Ready", + "statusConnecting": "Connecting...", + "statusThinking": "Thinking...", + "statusGenerating": "Generating...", + "statusDone": "Completed", + "statusStopped": "Stopped", + "statusFailed": "Failed", + "statusInitFailed": "Initialization failed", + "errors": { + "enterPrompt": "Please enter a message", + "imageRequired": "Image edit requires at least one reference image", + "imageOnly": "Image edit only supports image uploads", + "videoImageOnly": "Video generation only supports image reference uploads", + "imageProxyRequired": "Image failed to load. Set APP Base URL and change image output format to local_url, local_md, or base64.", + "videoProxyRequired": "Video loading returned 403. Go to the admin page, set the APP Base URL, then change the video output format to local proxy mode (local_url or local_html) and retry.", + "requestFailed": "Request failed", + "initFailed": "Chat page initialization failed" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "voiceLabel": "Voice", + "personalityLabel": "Personality", + "instructionLabel": "Prompt", + "speedLabel": "Speed", + "start": "Start", + "pause": "Pause", + "mute": "Mute", + "unmute": "Unmute", + "newSession": "New Session", + "statusIdle": "Not connected", + "statusConnecting": "Connecting", + "statusLive": "Live", + "statusMuted": "Muted", + "statusPaused": "Paused", + "statusError": "Failed", + "idleText": "Click and authorize to connect to Grok Voice through ChatKit voice sessions.", + "connectingText": "Requesting a Grok Voice session and connecting to LiveKit...", + "liveText": "Connection established. You can now speak directly with Grok.", + "outputMutedText": "Speaker output is muted, but you can keep speaking.", + "pausedText": "The session is paused. Click start to continue the current voice session.", + "errorText": "The connection did not complete. Check microphone access and try again.", + "endedText": "The voice session has ended. You can start again at any time.", + "livekitLoadFailed": "LiveKit SDK failed to load", + "invalidToken": "Voice token response invalid" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "qualitySpeed": "Speed", + "qualityQuality": "Quality", + "modeRounds": "Rounds", + "modeCycles": "Cycles", + "promptPlaceholder": "Describe the image you want. Press Enter to generate and Shift+Enter for a new line.", + "generate": "Generate", + "stop": "Stop", + "openImage": "Open image", + "statusReady": "Ready", + "statusConnecting": "Connecting...", + "statusGenerating": "Generating", + "statusCompleted": "Completed", + "statusStopped": "Stopped", + "statusFailed": "Failed", + "statusSuccess": "Success", + "statusPartialFailure": "Partial failure", + "statusBatchFailed": "Failed", + "emptyTitle": "Start with a prompt", + "emptyText": "Enter a prompt and images will appear here in order.", + "roundLabel": "Round {n}", + "batchFiltered": "Filtered", + "errors": { + "enterPrompt": "Please enter a prompt", + "requestFailed": "Request failed", + "initFailed": "Masonry page initialization failed" + } + } + }, + "account": { + "pageTitle": "Grok2API - Accounts", + "pageHeading": "Account Management", + "pageSubtitle": "Manage the xAI account pool, quota posture, and runtime state used by Grok2API.", + "actionImport": "Import Accounts", + "actionAdd": "Add Account", + "actionImportShort": "Import", + "actionAddShort": "Add", + "sectionOverview": "Overview", + "sectionTable": "Account List", + "statTotal": "Total Accounts", + "statActive": "Active", + "statCooling": "Rate-Limited", + "statInvalid": "Abnormal", + "statDisabled": "Disabled", + "statCalls": "Total Calls", + "statSuccessTotal": "Successful Calls", + "statAuto": "Auto Balance", + "statFast": "Fast Balance", + "statExpert": "Expert Balance", + "statHeavy": "Heavy Balance", + "filterStatusLabel": "Status", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "Type", + "filterStatusAll": "All", + "filterStatusActive": "Active", + "filterStatusCooling": "Rate-Limited", + "filterStatusInvalid": "Abnormal", + "filterStatusDisabled": "Disabled", + "filterNsfwAll": "All", + "filterNsfwEnabled": "On", + "filterNsfwDisabled": "Off", + "filterTypeAll": "All", + "filter": "Filter", + "export": "Export Data", + "batchNsfw": "Enable NSFW", + "batchNsfwDisable": "Disable NSFW", + "rowActionNotSupported": "Current status does not support this action", + "batchRefresh": "Refresh Selected", + "batchDisable": "Disable Selected", + "batchRestore": "Restore Selected", + "batchDelete": "Delete Selected", + "colToken": "Token", + "colType": "Account Type", + "colStatus": "Runtime Status", + "colQuota": "Quota", + "colSuccess": "Success", + "colFail": "Failed", + "colRate": "Success Rate", + "colLastUsed": "Last Used", + "colActions": "Actions", + "actionCopy": "Copy", + "actionRefresh": "Refresh Quota", + "actionDisable": "Disable Account", + "actionRestore": "Restore Account", + "actionEdit": "Edit", + "actionDelete": "Delete", + "empty": "No accounts available. Use Import Accounts or Add Account to continue.", + "pageInfo": "{n} total", + "pageIndicator": "Page {current} / {total}", + "pageSizeOption": "{n} / page", + "addTitle": "Add Account", + "addHint": "Enter one token per line. Existing tokens will be skipped automatically.", + "addPlaceholder": "Paste tokens, one per line...", + "importTitle": "Import Accounts", + "importHintDefault": "Supports .txt (one token per line) and .json ({pool:[tokens]}) formats.", + "importHintJson": "The JSON payload already includes account type metadata. No additional selection is required.", + "importHintTxt": "Enter one token per line. Imported tokens will be appended to the selected account type.", + "labelType": "Type", + "labelFile": "File", + "editTitle": "Edit Account", + "editTokenPlaceholder": "Enter the updated token", + "exportTitle": "Export Accounts", + "exportCountPrefix": "", + "exportCountSuffix": " tokens", + "exportJson": "JSON Format (full fidelity)", + "exportTxt": "TXT Format (token-only)", + "confirmTitle": "Confirm Action", + "cancel": "Cancel", + "confirm": "Confirm", + "save": "Save Changes", + "noFile": "No file selected", + "copied": "Copied", + "copyFailed": "Copy failed", + "loadFailed": "Load failed", + "notFound": "Account not found", + "enterToken": "Enter a token", + "selectFile": "Select a file", + "readFileFailed": "Failed to read file", + "jsonInvalid": "Invalid JSON format", + "jsonShapeInvalid": "Invalid JSON structure. Expected {pool:[tokens]}.", + "jsonEmpty": "No importable tokens found in the JSON file", + "fileEmpty": "No importable tokens found in the file", + "adding": "Adding {n} accounts…", + "addDone": "Accounts added", + "addFailed": "Failed to add accounts", + "importing": "Importing {n} accounts…", + "importDone": "Import completed", + "importJsonDone": "Import completed: {n} accounts processed", + "importFailed": "Import failed", + "saving": "Saving changes…", + "editDone": "Changes saved", + "editFailed": "Failed to save changes", + "saveResult": "{prefix}: {count} accounts added", + "saveResultSkipped": "{prefix}: {count} added, {skipped} already existed", + "exportEmpty": "There are no accounts to export", + "deleteConfirmTitle": "Confirm Delete", + "deleteConfirmOne": "Delete {token}?
This action cannot be undone.", + "deleteConfirmMany": "Delete {n} accounts?
This action cannot be undone.", + "deleting": "Deleting {n} accounts…", + "deleteDone": "Deleted {n}", + "deleteFailed": "Delete failed", + "refreshing": "Refreshing quota data for {n} accounts…", + "refreshDone": "Refresh completed: {ok} succeeded, {fail} failed", + "refreshFailed": "Refresh failed", + "disableConfirmTitle": "Disable Account", + "disableConfirmBody": "Disable {token}?
The account will be removed from request allocation until it is restored.", + "disablingOne": "Disabling account…", + "disableDone": "Account disabled", + "restoreConfirmTitle": "Restore Account", + "restoreConfirmBody": "Restore {token}?
The account will be returned to request allocation.", + "restoringOne": "Restoring account…", + "restoreDone": "Account restored", + "batchDisableConfirmTitle": "Disable Accounts", + "batchDisableConfirmBody": "Disable the selected {n} accounts?
Disabled accounts are removed from request allocation and can be restored later.", + "disablingMany": "Disabling {n} accounts…", + "disableManyDone": "Disable completed: {ok} succeeded, {fail} failed", + "batchRestoreConfirmTitle": "Restore Accounts", + "batchRestoreConfirmBody": "Restore the selected {n} accounts?
Restored accounts will be returned to request allocation.", + "restoringMany": "Restoring {n} accounts…", + "restoreManyDone": "Restore completed: {ok} succeeded, {fail} failed", + "nsfwConfirmTitle": "Enable NSFW", + "nsfwConfirmBody": "Enable NSFW for {n} selected accounts?", + "nsfwEnablingOne": "Enabling NSFW…", + "nsfwEnabling": "Enabling NSFW for {n} accounts…", + "nsfwDone": "NSFW update completed: {ok} succeeded, {fail} failed", + "nsfwDisablingOne": "Disabling NSFW…", + "nsfwDisableDone": "NSFW disable completed: {ok} succeeded, {fail} failed", + "operationFailed": "Operation failed", + "autoNsfwOnImport": "Auto-enable NSFW after import", + "autoNsfwHint": "Requires additional time to detect account status", + "unknown": "Unknown", + "na": "—", + "pool": { + "autoRecommended": "Auto Detect (Recommended)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" + }, + "status": { + "active": "Active", + "cooling": "Rate-Limited", + "disabled": "Disabled", + "expired": "Expired", + "invalid": "Abnormal" + }, + "autoNsfwOnImport": "Auto-enable NSFW after import", + "autoNsfwHint": "Requires additional time to detect account status" + }, + "config": { + "pageTitle": "Grok2API - Configuration Management", + "pageHeading": "Configuration Management", + "pageSubtitle": "Manage Grok2API runtime parameters and default service behavior.", + "resetShort": "Reset", + "saveShort": "Save", + "resetChanges": "Reset Changes", + "saveChanges": "Save Changes", + "unsavedDefault": "Unsaved changes detected", + "unsavedSingle": "1 unsaved change detected", + "unsavedMultiple": "{n} unsaved changes detected", + "discardShort": "Undo", + "saveBarShort": "Save", + "discardChanges": "Discard Changes", + "randomize": "Generate Value", + "loadFailed": "Failed to load configuration: {message}", + "saving": "Saving changes...", + "saveSuccess": "Changes saved", + "saveFailed": "Failed to save changes: {message}", + "resetSuccess": "Unsaved changes discarded", + "disabledTip": { + "appUrlRequired": "Configure the APP Base URL first" + }, + "schema": { + "tabs": { + "system": "System", + "features": "Features", + "schedule": "Scheduling", + "proxy": "Networking", + "cache": "Cache Storage", + "image": "Image Pipeline" + }, + "groups": { + "baseAccess": "Access Control", + "features": "Core Features", + "mediaFormat": "Media Output", + "refreshSchedule": "Quota Refresh", + "selection": "Selection Concurrency", + "batchConcurrency": "Batch Concurrency", + "egressProxy": "Egress Proxy", + "clearance": "Cloudflare Clearance", + "retry": "Retry Policy", + "timeouts": "Request Timeouts", + "imageProtocol": "NSFW and Image Streaming", + "logging": "Logging", + "localMediaCache": "Local Media Cache" + }, + "options": { + "imageFormat": { + "grokUrl": "URL (Grok Native)", + "localUrl": "URL (Local Proxy)", + "grokMarkdown": "Markdown (Grok Native)", + "localMarkdown": "Markdown (Local Proxy)", + "base64": "Base64 (Inline)" + }, + "videoFormat": { + "grokUrl": "URL (Grok Native)", + "localUrl": "URL (Local Proxy)", + "grokHtml": "HTML (Grok Native)", + "localHtml": "HTML (Local Proxy)" + }, + "proxyMode": { + "direct": "Direct", + "singleProxy": "Fixed Proxy", + "proxyPool": "Proxy Pool" + }, + "clearanceMode": { + "none": "Disabled", + "manual": "Manual", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { + "label": "APP Base URL", + "desc": "Root URL exposed by the application, for example https://your-domain.com. Required when local proxy delivery is enabled." + }, + "appKey": { + "label": "APP Access Password", + "desc": "Authentication password for the admin surface. Existing sessions are invalidated immediately after a change." + }, + "apiKey": { + "label": "API Access Key", + "desc": "Authentication key for the OpenAI-compatible API. Separate multiple values with commas. Leave blank to disable authentication." + }, + "webuiEnabled": { + "label": "Enable WebUI", + "desc": "Exposes the WebUI entry point. When disabled, related routes return 404." + }, + "webuiKey": { + "label": "WebUI Access Password", + "desc": "Authentication password required to access the WebUI when enabled." + }, + "temporary": { + "label": "Temporary Sessions", + "desc": "Requests are excluded from Grok conversation history, providing an ephemeral chat mode." + }, + "memory": { + "label": "Conversation Memory", + "desc": "Enables Grok Memory so the model can retain user preferences and context across sessions." + }, + "stream": { + "label": "Default Streaming", + "desc": "Default value applied when the request does not explicitly provide the stream parameter." + }, + "thinking": { + "label": "Default Reasoning Output", + "desc": "Default value applied when the request does not explicitly provide the thinking parameter. When enabled, reasoning steps are returned in reasoning_content." + }, + "autoChatModeFallback": { + "label": "AUTO Chat Mode Fallback", + "desc": "When an AUTO chat model has no available auto quota, automatically try the fast and expert chat quota windows." + }, + "thinkingSummary": { + "label": "Condensed Reasoning", + "desc": "When enabled, reasoning steps are condensed into a structured summary. When disabled, the full raw reasoning stream is output, with multi-agent collaboration details and tool call traces." + }, + "dynamicStatsig": { + "label": "Dynamic Statsig", + "desc": "Generates a fresh Statsig device fingerprint for each request to reduce the likelihood of risk-control challenges." + }, + "enableNsfw": { + "label": "Allow NSFW Generation", + "desc": "Permits the image generation endpoint to bypass NSFW content filtering." + }, + "showSearchSources": { + "label": "Append Sources to Content", + "desc": "Search sources are always output in the search_sources field. This option controls whether to also append a ## Sources section to the response content (for backward compatibility with text-parsing clients)." + }, + "customInstruction": { + "label": "Global Supplemental Instruction", + "desc": "Injects a consistent system message into every request to enforce model behavior or establish a fixed role." + }, + "imageFormat": { + "label": "Image Output Format", + "desc": "grok_url and grok_md return the native Grok CDN address directly by default. local_* modes download assets to the server first and re-expose them through the local proxy. base64 returns an inline Data URI. When Imagine Public Image Proxy is enabled, imagine-public images returned by the WebSocket are also proxied locally." + }, + "imaginePublicImageProxy": { + "label": "Imagine Public Image Proxy", + "desc": "When enabled, imagine-public images returned by the WebSocket are downloaded to the server and delivered through the local proxy. When disabled, public images are returned directly." + }, + "videoFormat": { + "label": "Video Output Format", + "desc": "local_* modes download video assets to the server and deliver them through the local proxy. Configure the APP Base URL first and account for outbound bandwidth usage." + }, + "refreshEnabled": { + "label": "Enable Quota Refresh", + "desc": "When enabled, the system automatically switches to quota refresh mode. When disabled, it automatically switches to auto-retry mode.", + "help": "On: quota refresh mode. The scheduler periodically syncs real quota, and selection uses scoring.\nOff: auto-retry mode. No upstream probing, uniform random selection, and auto-swap on errors for up to 5 retries.\nRecommendation: turn this off for >10k accounts to avoid self-triggering upstream 429s." + }, + "maxInflight": { + "label": "Max Inflight per Account", + "desc": "Maximum concurrent in-flight requests per account. Accounts at this limit are skipped by the selector (shared by both modes)." + }, + "basicInterval": { + "label": "Basic Cycle (s)", + "desc": "Shared cycle for the basic pool: used for background refresh in quota mode and for 429 cooldown in random mode. Default 86400s." + }, + "superInterval": { + "label": "Super Cycle (s)", + "desc": "Shared cycle for the super pool: used for background refresh in quota mode and for 429 cooldown in random mode. Default 7200s." + }, + "heavyInterval": { + "label": "Heavy Cycle (s)", + "desc": "Shared cycle for the heavy pool: used for background refresh in quota mode and for 429 cooldown in random mode. Default 7200s." + }, + "usageConcurrency": { + "label": "Refresh Concurrency", + "desc": "Maximum number of parallel usage calls allowed during quota refresh." + }, + "onDemandMinInterval": { + "label": "On-Demand Refresh Interval (s)", + "desc": "Throttle window for request-triggered refreshes such as 429 handling. Repeated triggers within the interval are coalesced into a single refresh." + }, + "imageCacheMaxMb": { + "label": "Image Cache Limit (MB)", + "desc": "0 disables the limit. Applies only to locally proxied media files. When the limit is exceeded, the oldest files are removed until usage falls back to 60% of the limit." + }, + "videoCacheMaxMb": { + "label": "Video Cache Limit (MB)", + "desc": "0 disables the limit. Applies only to locally proxied media files. When the limit is exceeded, the oldest files are removed until usage falls back to 60% of the limit." + }, + "nsfwConcurrency": { + "label": "NSFW Enablement Concurrency", + "desc": "Token-level concurrency for bulk NSFW enablement. Each token requires three network calls." + }, + "refreshConcurrency": { + "label": "Usage Refresh Concurrency", + "desc": "Token-level concurrency used during bulk quota refresh." + }, + "assetUploadConcurrency": { + "label": "Asset Upload Concurrency", + "desc": "Global maximum concurrency for asset uploads triggered by file attachments across all incoming requests." + }, + "assetListConcurrency": { + "label": "Asset Listing Concurrency", + "desc": "Global maximum concurrency for the list_assets endpoint across all requests." + }, + "assetDeleteConcurrency": { + "label": "Asset Deletion Concurrency", + "desc": "Global maximum concurrency for the delete_asset endpoint. Also used as the default token-level concurrency for bulk cleanup in the admin UI." + }, + "proxyMode": { + "label": "Proxy Mode", + "desc": "Controls outbound proxy routing. direct sends traffic without a proxy, single_proxy uses a fixed proxy, and proxy_pool rotates across a pool." + }, + "proxyUrl": { + "label": "Primary Proxy URL", + "desc": "Outbound proxy endpoint for API traffic. Supports http, https, and socks5." + }, + "resourceProxyUrl": { + "label": "Resource Proxy URL", + "desc": "Dedicated proxy endpoint for downloading images, videos, and other media assets. Falls back to the primary proxy when left blank." + }, + "proxyPool": { + "label": "Primary Proxy Pool", + "desc": "Pool of outbound proxies for API traffic, one proxy URL per line." + }, + "resourceProxyPool": { + "label": "Resource Proxy Pool", + "desc": "Dedicated proxy pool for media downloads, one proxy URL per line. Falls back to the primary pool when left blank." + }, + "skipSslVerify": { + "label": "Skip SSL Verification", + "desc": "Bypasses TLS certificate validation for the proxy server. Enable only when using self-signed certificates." + }, + "clearanceMode": { + "label": "Clearance Mode", + "desc": "Controls how Cloudflare Clearance is obtained and refreshed." + }, + "browserFingerprint": { + "label": "Browser Fingerprint", + "desc": "curl_cffi browser fingerprint identifier. It should align with the JA3 profile expected by Cloudflare, for example chrome136." + }, + "userAgent": { + "label": "User-Agent", + "desc": "Request header User-Agent. It must match the browser used when the Cloudflare cookie was validated." + }, + "cfCookies": { + "label": "Cloudflare Cookies", + "desc": "Full cookie string issued by Cloudflare, including fields such as cf_clearance." + }, + "flaresolverrUrl": { + "label": "FlareSolverr URL", + "desc": "HTTP endpoint for the FlareSolverr instance." + }, + "challengeTimeout": { + "label": "Challenge Timeout (s)", + "desc": "Maximum time allowed for FlareSolverr to complete the Cloudflare challenge." + }, + "refreshInterval": { + "label": "Refresh Interval (s)", + "desc": "Scheduling interval for the prewarm task that refreshes the clearance cookie." + }, + "maxRetries": { + "label": "Application Retry Limit", + "desc": "Maximum number of application-layer retries after a request failure. A value of 0 disables retries. Applies to chat.completions and responses." + }, + "retryCodes": { + "label": "Application Retry Status Codes", + "desc": "HTTP status codes that trigger application-layer retries. Separate multiple values with commas, for example 429,503." + }, + "resetSessionCodes": { + "label": "Transport Session Rebuild Status Codes", + "desc": "HTTP status codes that trigger a transport-session rebuild for the proxy layer. Separate multiple values with commas." + }, + "chatTimeout": { + "label": "Chat Request Timeout (s)", + "desc": "HTTP connection timeout for chat and image-edit requests." + }, + "imageTimeout": { + "label": "Image Request Timeout (s)", + "desc": "Overall timeout for image generation WebSocket requests." + }, + "videoTimeout": { + "label": "Video Request Timeout (s)", + "desc": "Unified timeout for video generation requests." + }, + "voiceTimeout": { + "label": "Voice Request Timeout (s)", + "desc": "Unified timeout for voice requests." + }, + "nsfwTimeout": { + "label": "NSFW Processing Timeout (s)", + "desc": "Timeout applied to set_birth_date and enable_nsfw requests." + }, + "assetUploadTimeout": { + "label": "Asset Upload Timeout (s)", + "desc": "Timeout for the asset upload endpoint." + }, + "assetDownloadTimeout": { + "label": "Asset Download Timeout (s)", + "desc": "Timeout for the asset download endpoint." + }, + "assetListTimeout": { + "label": "Asset Listing Timeout (s)", + "desc": "Timeout for the asset listing endpoint." + }, + "assetDeleteTimeout": { + "label": "Asset Deletion Timeout (s)", + "desc": "Timeout for the asset deletion endpoint." + }, + "streamTimeout": { + "label": "Streaming Idle Timeout (s)", + "desc": "Maximum idle time tolerated while receiving streamed image data." + }, + "interRoundWait": { + "label": "Inter-Round Wait (s)", + "desc": "Wait time used after each image round to determine whether the server keeps the connection open. If CLOSE is not received in time, the existing connection is reused for the next round." + }, + "fileLogLevel": { + "label": "File Log Level", + "desc": "Minimum log level written to log files. Can be configured independently from the console. Default: INFO." + }, + "logMaxFiles": { + "label": "Log Retention (days)", + "desc": "Maximum number of daily log files to keep during rotation. Default: 7." + } + } + } + }, + "cache": { + "pageTitle": "Grok2API - Cache Management", + "pageHeading": "Cache Management", + "pageSubtitle": "View and manage local cache files, storage limits, and online account assets.", + "sectionOverview": "Overview", + "statImageCount": "Image Cache Files", + "statImageSize": "Image Cache Size", + "statVideoCount": "Video Cache Files", + "statVideoSize": "Video Cache Size", + "usageSummaryUnlimited": "Used {used} · Unlimited", + "usageSummaryLimited": "Used {used} / {limit} · {percent}", + "sectionDetails": "Details", + "tabLocal": "Local Cache", + "tabLocalImage": "Local Images", + "tabLocalVideo": "Local Videos", + "tabOnline": "Online Assets", + "typeImage": "Images", + "typeVideo": "Videos", + "typeImageNoun": "image", + "typeVideoNoun": "video", + "clearCurrent": "Clear Current Cache", + "deleteSelected": "Delete Selected", + "clearSelected": "Clear Selected", + "colFileName": "File Name", + "colSize": "Size", + "colModified": "Last Modified", + "colActions": "Actions", + "colToken": "Token", + "colFileCount": "Files", + "onlineAssetLead": "Online Assets", + "onlineAssetDesc": "are images and attachments stored on the Grok platform. Cleanup affects only remote files and does not remove local cache data.", + "loadAssets": "Load Asset Inventory", + "clearAll": "Clear All", + "cancel": "Cancel", + "assetSummaryIdle": "Load online assets from the right side", + "assetSummary": "{accounts} accounts · {files} files", + "pageIndicator": "Page {current} / {total}", + "pageSizeOption": "{n} / page", + "fileCount": "{n} files", + "emptyLocal": "No cached files found", + "emptyAssetsIdle": "Click the top-right button to load online assets", + "emptyAccounts": "No account data available", + "actionView": "View", + "actionDelete": "Delete", + "actionClear": "Clear", + "loadFailed": "Load failed: {message}", + "clearLocalConfirm": "Clear all local {type} cache files?", + "clearLocalDone": "Removed {count} {type} file(s)", + "clearFailed": "Clear failed: {message}", + "deleted": "Deleted", + "deleteSelectedConfirm": "Delete the selected {n} file(s)?", + "deleteSelectedDone": "Deleted {count} file(s)", + "deleteFailed": "Delete failed: {message}", + "viewUnavailable": "Preview is unavailable for this file", + "loading": "Loading...", + "refreshList": "Refresh List", + "expand": "Expand", + "collapse": "Collapse", + "clearTokenConfirm": "Clear all online assets for {token}?", + "clearTokenDone": "Deleted {count} file(s)", + "clearSelectedConfirm": "Clear online assets for the selected {n} account(s)?", + "clearAllConfirm": "Clear online assets for all {n} accounts? This action cannot be undone.", + "clearingAssets": "Clearing online assets...", + "clearAllDone": "Cleanup completed: {ok} succeeded, {fail} failed", + "cancelled": "Cancelled", + "clearFailedPlain": "Cleanup failed", + "connectionInterrupted": "Connection interrupted", + "startFailed": "Failed to start: {message}", + "cancelInProgress": "Cancellation requested. Wait for the current batch to finish.", + "na": "—" + } +} \ No newline at end of file diff --git a/app/statics/i18n/es.json b/app/statics/i18n/es.json new file mode 100644 index 0000000000000000000000000000000000000000..0743720be0ea98454ca1662e9daaf11353737100 --- /dev/null +++ b/app/statics/i18n/es.json @@ -0,0 +1,519 @@ +{ + "common": { + "invalidKey": "Clave no válida", + "connectionFailed": "Error de conexión" + }, + "login": { + "adminPageTitle": "Grok2API - Administración", + "adminTitle": "Panel de Administración", + "adminSubtitle": "Introduzca la contraseña de administrador para continuar", + "adminPlaceholder": "Contraseña de administrador", + "continue": "Continuar", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "Introduzca la clave de acceso", + "webuiPlaceholder": "Clave de acceso", + "enter": "Entrar", + "goToAdmin": "Ir al Panel de Administración" + }, + "webui": { + "header": { + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "Chats", + "newChat": "Nuevo chat", + "toggleSidebar": "Alternar barra lateral", + "upload": "Subir archivo", + "noSessions": "Aún no hay chats", + "untitled": "Nuevo chat", + "rename": "Renombrar", + "delete": "Eliminar", + "edit": "Editar", + "copy": "Copiar", + "regenerate": "Regenerar", + "like": "Me gusta", + "dislike": "No me gusta", + "reasoning": "Pensamiento", + "save": "Guardar", + "cancel": "Cancelar", + "confirm": "Confirmar", + "copySuccess": "Copiado", + "renamePrompt": "Renombrar chat", + "deleteConfirm": "¿Eliminar este chat?", + "modelLabel": "Modelo", + "emptyTitle": "Grok Chat", + "empty": "Inicie una nueva conversación enviando un mensaje.", + "promptPlaceholder": "Escriba su mensaje. Enter para enviar y Shift+Enter para una nueva línea.", + "editPlaceholder": "Editar este mensaje", + "stop": "Detener", + "send": "Enviar", + "statusReady": "Listo", + "statusConnecting": "Conectando...", + "statusThinking": "Pensando...", + "statusGenerating": "Generando...", + "statusDone": "Completado", + "statusStopped": "Detenido", + "statusFailed": "Fallido", + "statusInitFailed": "Fallo en la inicialización", + "errors": { + "enterPrompt": "Introduzca un mensaje", + "imageRequired": "La edición de imagen requiere al menos una imagen de referencia", + "imageOnly": "La edición de imagen solo admite cargas de imágenes", + "videoImageOnly": "La generación de vídeo solo admite imágenes como referencia", + "imageProxyRequired": "No se pudo cargar la imagen. Configure la URL base de APP y cambie el formato de salida de imagen a local_url, local_md o base64.", + "videoProxyRequired": "La carga del vídeo devolvió 403. Vaya a la página de administración, configure la URL base de APP y cambie el formato de salida de vídeo al modo de proxy local (local_url o local_html). Después, inténtelo de nuevo.", + "requestFailed": "La solicitud falló", + "initFailed": "La inicialización de la página de chat falló" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "voiceLabel": "Voz", + "personalityLabel": "Personalidad", + "speedLabel": "Velocidad", + "start": "Iniciar", + "pause": "Pausar", + "mute": "Silenciar", + "unmute": "Activar sonido", + "newSession": "Nueva sesión", + "statusIdle": "Sin conexión", + "statusConnecting": "Conectando", + "statusLive": "En vivo", + "statusMuted": "Silenciado", + "statusPaused": "Pausado", + "statusError": "Fallido", + "idleText": "Haga clic y autorice para conectarse a Grok Voice a través de las sesiones de voz de ChatKit.", + "connectingText": "Solicitando una sesión de voz de Grok y conectando con LiveKit...", + "liveText": "Conexión establecida. Ahora puede hablar directamente con Grok.", + "outputMutedText": "El altavoz está silenciado, pero todavía puede seguir hablando.", + "pausedText": "La sesión está en pausa. Pulse iniciar para continuar la sesión de voz actual.", + "errorText": "No se pudo completar la conexión. Compruebe el acceso al micrófono e inténtelo de nuevo.", + "endedText": "La sesión de voz ha finalizado. Puede iniciar otra en cualquier momento.", + "livekitLoadFailed": "No se pudo cargar el SDK de LiveKit", + "invalidToken": "Respuesta de token de voz no válida" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "qualitySpeed": "Velocidad", + "qualityQuality": "Calidad", + "modeRounds": "Rondas", + "modeCycles": "Ciclos", + "promptPlaceholder": "Describa la imagen que desea. Enter para generar y Shift+Enter para nueva línea.", + "generate": "Generar", + "stop": "Detener", + "openImage": "Abrir imagen", + "statusReady": "Listo", + "statusConnecting": "Conectando...", + "statusGenerating": "Generando", + "statusCompleted": "Completado", + "statusStopped": "Detenido", + "statusFailed": "Fallido", + "statusSuccess": "Generado", + "statusPartialFailure": "Fallo parcial", + "statusBatchFailed": "Falló", + "emptyTitle": "Empiece con un prompt", + "emptyText": "Introduzca un prompt y las imágenes aparecerán aquí en orden.", + "roundLabel": "Ronda {n}", + "batchFiltered": "Filtrado", + "errors": { + "enterPrompt": "Introduzca un prompt", + "requestFailed": "La solicitud falló", + "initFailed": "La inicialización de la página Masonry falló" + } + } + }, + "header": { + "account": "Gestión de Cuentas", + "config": "Gestión de Configuración", + "cache": "Gestión de Caché", + "languageLabel": "Idioma", + "logout": "Cerrar sesión", + "versionDialogTitle": "Versión", + "versionCurrent": "Actual", + "versionLatest": "Última", + "versionPublishedAt": "Publicada", + "versionUpToDate": "Ya está usando la versión más reciente.", + "versionUpdateAvailable": "Hay una nueva versión disponible.", + "versionChecking": "Comprobando actualizaciones...", + "versionRefresh": "Buscar actualizaciones", + "versionUnavailable": "No se pudo comprobar las actualizaciones.", + "versionNotesEmpty": "No hay notas de versión disponibles.", + "versionOpenRelease": "Abrir release", + "versionClose": "Cerrar" + }, + "account": { + "pageTitle": "Grok2API - Cuentas", + "pageHeading": "Gestión de Cuentas", + "pageSubtitle": "Administre el pool de cuentas de xAI, la postura de cuota y el estado operativo utilizado por Grok2API.", + "actionImport": "Importar cuentas", + "actionAdd": "Agregar cuenta", + "actionImportShort": "Importar", + "actionAddShort": "Agregar", + "sectionOverview": "Resumen", + "sectionTable": "Lista de cuentas", + "statTotal": "Cuentas totales", + "statActive": "Activas", + "statCooling": "Limitadas", + "statInvalid": "Anómalas", + "statDisabled": "Desactivadas", + "statCalls": "Llamadas totales", + "statSuccessTotal": "Éxitos totales", + "statAuto": "Saldo Auto", + "statFast": "Saldo Fast", + "statExpert": "Saldo Expert", + "statHeavy": "Saldo Heavy", + "filterStatusLabel": "Estado", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "Tipo", + "filterStatusAll": "Todas", + "filterStatusActive": "Activas", + "filterStatusCooling": "Limitadas", + "filterStatusInvalid": "Anómalas", + "filterStatusDisabled": "Desactivadas", + "filterNsfwAll": "Todas", + "filterNsfwEnabled": "Activado", + "filterNsfwDisabled": "Desactivado", + "filterTypeAll": "Todos", + "filter": "Filtrar", + "export": "Exportar datos", + "batchNsfw": "Activar NSFW", + "batchNsfwDisable": "Desactivar NSFW", + "rowActionNotSupported": "El estado actual no admite esta acción", + "batchRefresh": "Actualizar selección", + "batchDisable": "Desactivar selección", + "batchRestore": "Restaurar selección", + "batchDelete": "Eliminar selección", + "colToken": "Token", + "colType": "Tipo de cuenta", + "colStatus": "Estado operativo", + "colQuota": "Cuota", + "colSuccess": "Éxito", + "colFail": "Error", + "colRate": "Tasa de éxito", + "colLastUsed": "Último uso", + "colActions": "Acciones", + "actionCopy": "Copiar", + "actionRefresh": "Actualizar cuota", + "actionDisable": "Desactivar cuenta", + "actionRestore": "Restaurar cuenta", + "actionEdit": "Editar", + "actionDelete": "Eliminar", + "empty": "No hay cuentas disponibles. Use Importar cuentas o Agregar cuenta para continuar.", + "pageInfo": "{n} en total", + "pageIndicator": "Página {current} / {total}", + "pageSizeOption": "{n} / página", + "addTitle": "Agregar cuenta", + "addHint": "Introduzca un token por línea. Los tokens existentes se omitirán automáticamente.", + "addPlaceholder": "Pegue los tokens, uno por línea...", + "importTitle": "Importar cuentas", + "importHintDefault": "Admite formatos .txt (un token por línea) y .json ({pool:[tokens]}).", + "importHintJson": "El archivo JSON ya incluye la información del tipo de cuenta. No se requiere una selección adicional.", + "importHintTxt": "Introduzca un token por línea. Los tokens importados se agregarán al tipo de cuenta seleccionado.", + "labelType": "Tipo", + "labelFile": "Archivo", + "editTitle": "Editar cuenta", + "editTokenPlaceholder": "Introduzca el token actualizado", + "exportTitle": "Exportar cuentas", + "exportCountPrefix": "", + "exportCountSuffix": " tokens", + "exportJson": "Formato JSON (exportación completa)", + "exportTxt": "Formato TXT (solo tokens)", + "confirmTitle": "Confirmar acción", + "cancel": "Cancelar", + "confirm": "Confirmar", + "save": "Guardar cambios", + "noFile": "No se seleccionó ningún archivo", + "copied": "Copiado", + "copyFailed": "Error al copiar", + "loadFailed": "Error al cargar", + "notFound": "Cuenta no encontrada", + "enterToken": "Introduzca un token", + "selectFile": "Seleccione un archivo", + "readFileFailed": "No se pudo leer el archivo", + "jsonInvalid": "Formato JSON no válido", + "jsonShapeInvalid": "Estructura JSON no válida. Se esperaba {pool:[tokens]}.", + "jsonEmpty": "No se encontraron tokens importables en el archivo JSON", + "fileEmpty": "No se encontraron tokens importables en el archivo", + "adding": "Agregando {n} cuentas…", + "addDone": "Cuentas agregadas", + "addFailed": "No se pudieron agregar las cuentas", + "importing": "Importando {n} cuentas…", + "importDone": "Importación completada", + "importJsonDone": "Importación completada: {n} cuentas procesadas", + "importFailed": "La importación falló", + "saving": "Guardando cambios…", + "editDone": "Cambios guardados", + "editFailed": "No se pudieron guardar los cambios", + "saveResult": "{prefix}: {count} cuentas agregadas", + "saveResultSkipped": "{prefix}: {count} agregadas, {skipped} ya existían", + "exportEmpty": "No hay cuentas para exportar", + "deleteConfirmTitle": "Confirmar eliminación", + "deleteConfirmOne": "¿Eliminar {token}?
Esta acción no se puede deshacer.", + "deleteConfirmMany": "¿Eliminar {n} cuentas?
Esta acción no se puede deshacer.", + "deleting": "Eliminando {n} cuentas…", + "deleteDone": "Se eliminaron {n}", + "deleteFailed": "La eliminación falló", + "refreshing": "Actualizando la información de cuota de {n} cuentas…", + "refreshDone": "Actualización completada: {ok} correctas, {fail} fallidas", + "refreshFailed": "La actualización falló", + "disableConfirmTitle": "Desactivar cuenta", + "disableConfirmBody": "¿Desactivar {token}?
La cuenta dejará de participar en la asignación de solicitudes hasta que se restaure.", + "disablingOne": "Desactivando cuenta…", + "disableDone": "Cuenta desactivada", + "restoreConfirmTitle": "Restaurar cuenta", + "restoreConfirmBody": "¿Restaurar {token}?
La cuenta volverá a participar en la asignación de solicitudes.", + "restoringOne": "Restaurando cuenta…", + "restoreDone": "Cuenta restaurada", + "batchDisableConfirmTitle": "Desactivar cuentas", + "batchDisableConfirmBody": "¿Desactivar las {n} cuentas seleccionadas?
Las cuentas desactivadas no participarán en la asignación de solicitudes y podrán restaurarse más tarde.", + "disablingMany": "Desactivando {n} cuentas…", + "disableManyDone": "Desactivación completada: {ok} correctas, {fail} fallidas", + "batchRestoreConfirmTitle": "Restaurar cuentas", + "batchRestoreConfirmBody": "¿Restaurar las {n} cuentas seleccionadas?
Las cuentas restauradas volverán a participar en la asignación de solicitudes.", + "restoringMany": "Restaurando {n} cuentas…", + "restoreManyDone": "Restauración completada: {ok} correctas, {fail} fallidas", + "nsfwConfirmTitle": "Activar NSFW", + "nsfwConfirmBody": "¿Activar NSFW para {n} cuentas seleccionadas?", + "nsfwEnablingOne": "Activando NSFW…", + "nsfwEnabling": "Activando NSFW para {n} cuentas…", + "nsfwDone": "Actualización de NSFW completada: {ok} correctas, {fail} fallidas", + "nsfwDisablingOne": "Desactivando NSFW…", + "nsfwDisableDone": "Desactivación de NSFW completada: {ok} correctas, {fail} fallidas", + "operationFailed": "La operación falló", + "unknown": "Desconocido", + "na": "—", + "pool": { + "autoRecommended": "Detección automática (recomendada)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" + }, + "status": { + "active": "Activa", + "cooling": "Limitada", + "disabled": "Desactivada", + "expired": "Expirada", + "invalid": "Anómalo" + } + }, + "config": { + "pageTitle": "Grok2API - Gestión de Configuración", + "pageHeading": "Gestión de Configuración", + "pageSubtitle": "Administre los parámetros de ejecución de Grok2API y el comportamiento predeterminado del servicio.", + "resetShort": "Restablecer", + "saveShort": "Guardar", + "resetChanges": "Restablecer cambios", + "saveChanges": "Guardar cambios", + "unsavedDefault": "Hay cambios sin guardar", + "unsavedSingle": "Hay 1 cambio sin guardar", + "unsavedMultiple": "Hay {n} cambios sin guardar", + "discardShort": "Deshacer", + "saveBarShort": "Guardar", + "discardChanges": "Descartar cambios", + "randomize": "Generar valor", + "loadFailed": "No se pudo cargar la configuración: {message}", + "saving": "Guardando cambios...", + "saveSuccess": "Cambios guardados", + "saveFailed": "No se pudieron guardar los cambios: {message}", + "resetSuccess": "Se descartaron los cambios no guardados", + "disabledTip": { + "appUrlRequired": "Configure primero la URL base de APP" + }, + "schema": { + "tabs": { + "system": "Sistema", + "features": "Funciones", + "schedule": "Programación", + "proxy": "Red", + "cache": "Almacenamiento de caché", + "image": "Canal de imagen" + }, + "groups": { + "baseAccess": "Control de acceso", + "features": "Funciones principales", + "mediaFormat": "Salida multimedia", + "refreshSchedule": "Actualización de cuota", + "selection": "Concurrencia de selección", + "batchConcurrency": "Concurrencia por lotes", + "egressProxy": "Proxy de salida", + "clearance": "Cloudflare Clearance", + "retry": "Política de reintentos", + "timeouts": "Tiempos de espera", + "imageProtocol": "NSFW y transmisión de imágenes", + "logging": "Registro", + "localMediaCache": "Caché multimedia local" + }, + "options": { + "imageFormat": { + "grokUrl": "URL (Nativo de Grok)", + "localUrl": "URL (Proxy local)", + "grokMarkdown": "Markdown (Nativo de Grok)", + "localMarkdown": "Markdown (Proxy local)", + "base64": "Base64 (Integrado)" + }, + "videoFormat": { + "grokUrl": "URL (Nativo de Grok)", + "localUrl": "URL (Proxy local)", + "grokHtml": "HTML (Nativo de Grok)", + "localHtml": "HTML (Proxy local)" + }, + "proxyMode": { + "direct": "Directo", + "singleProxy": "Proxy fijo", + "proxyPool": "Pool de proxies" + }, + "clearanceMode": { + "none": "Desactivado", + "manual": "Manual", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { "label": "URL base de APP" }, + "appKey": { "label": "Contraseña de acceso APP" }, + "apiKey": { "label": "Clave de acceso API" }, + "webuiEnabled": { "label": "Activar WebUI" }, + "webuiKey": { "label": "Contraseña de acceso WebUI" }, + "temporary": { "label": "Sesiones temporales" }, + "memory": { "label": "Memoria de conversación" }, + "stream": { "label": "Streaming predeterminado" }, + "thinking": { "label": "Salida de razonamiento predeterminada" }, + "autoChatModeFallback": { "label": "Reserva de modo AUTO para chat" }, + "thinkingSummary": { "label": "Razonamiento condensado" }, + "dynamicStatsig": { "label": "Statsig dinámico" }, + "enableNsfw": { "label": "Permitir generación NSFW" }, + "showSearchSources": { "label": "Agregar fuentes al contenido", "desc": "Las fuentes de búsqueda siempre se incluyen en el campo search_sources. Esta opción controla si también se agrega una sección ## Sources al contenido (para compatibilidad con clientes que analizan texto)." }, + "customInstruction": { "label": "Instrucción suplementaria global" }, + "imageFormat": { "label": "Formato de salida de imagen", "desc": "grok_url y grok_md devuelven directamente la dirección nativa del CDN de Grok de forma predeterminada. Los modos local_* descargan primero los recursos en el servidor y los vuelven a exponer mediante el proxy local. base64 devuelve un Data URI integrado. Cuando el proxy de imágenes Imagine Public está activado, las imágenes imagine-public devueltas por WebSocket también se sirven mediante el proxy local." }, + "imaginePublicImageProxy": { "label": "Proxy de imágenes Imagine Public", "desc": "Cuando está activado, las imágenes imagine-public devueltas por WebSocket se descargan en el servidor y se entregan mediante el proxy local. Cuando está desactivado, las imágenes públicas se devuelven directamente." }, + "videoFormat": { "label": "Formato de salida de video" }, + "refreshEnabled": { "label": "Activar actualización de cuota", "desc": "Al activarlo, el sistema cambia automáticamente al modo de actualización de cuota. Al desactivarlo, cambia automáticamente al modo de reintento automático.", "help": "Activado: modo de actualización de cuota. El scheduler sincroniza periódicamente la cuota real y la selección usa puntuación.\nDesactivado: modo de reintento automático. No comprueba upstream activamente, usa selección aleatoria y cambia de cuenta al fallar hasta 5 reintentos.\nRecomendación: desactívalo con más de 10.000 cuentas para evitar provocar 429 de upstream con comprobaciones activas." }, + "maxInflight": { "label": "Máximo en curso por cuenta", "desc": "Máximo de solicitudes simultáneas en curso por cuenta. Las cuentas en ese límite se omiten en la selección (compartido por ambos modos)." }, + "basicInterval": { "label": "Ciclo Basic (s)", "desc": "Ciclo compartido del pool Basic: se usa para la actualización en segundo plano en modo quota y para el enfriamiento tras 429 en modo random. Valor por defecto: 86400s." }, + "superInterval": { "label": "Ciclo Super (s)", "desc": "Ciclo compartido del pool Super: se usa para la actualización en segundo plano en modo quota y para el enfriamiento tras 429 en modo random. Valor por defecto: 7200s." }, + "heavyInterval": { "label": "Ciclo Heavy (s)", "desc": "Ciclo compartido del pool Heavy: se usa para la actualización en segundo plano en modo quota y para el enfriamiento tras 429 en modo random. Valor por defecto: 7200s." }, + "usageConcurrency": { "label": "Concurrencia de actualización", "desc": "Número máximo de llamadas usage paralelas permitidas durante la actualización de cuota." }, + "onDemandMinInterval": { "label": "Intervalo de actualización bajo demanda (s)", "desc": "Ventana de limitación para actualizaciones activadas por solicitudes, como el manejo de 429. Los disparos repetidos dentro del intervalo se agrupan en una sola actualización." }, + "imageCacheMaxMb": { "label": "Límite de caché de imágenes (MB)", "desc": "0 desactiva el límite. Solo se aplica a los archivos multimedia guardados por el proxy local. Cuando se supera el límite, se eliminan primero los archivos más antiguos hasta volver al 60% del límite." }, + "videoCacheMaxMb": { "label": "Límite de caché de video (MB)", "desc": "0 desactiva el límite. Solo se aplica a los archivos multimedia guardados por el proxy local. Cuando se supera el límite, se eliminan primero los archivos más antiguos hasta volver al 60% del límite." }, + "nsfwConcurrency": { "label": "Concurrencia de activación NSFW" }, + "refreshConcurrency": { "label": "Concurrencia de refresco de Usage" }, + "assetUploadConcurrency": { "label": "Concurrencia de carga de Asset" }, + "assetListConcurrency": { "label": "Concurrencia de listado de Asset" }, + "assetDeleteConcurrency": { "label": "Concurrencia de eliminación de Asset" }, + "proxyMode": { "label": "Modo de proxy" }, + "proxyUrl": { "label": "URL de proxy principal" }, + "resourceProxyUrl": { "label": "URL de proxy de recursos" }, + "proxyPool": { "label": "Pool de proxy principal" }, + "resourceProxyPool": { "label": "Pool de proxy de recursos" }, + "skipSslVerify": { "label": "Omitir verificación SSL" }, + "clearanceMode": { "label": "Modo de Clearance" }, + "browserFingerprint": { "label": "Huella del navegador" }, + "userAgent": { "label": "User-Agent" }, + "cfCookies": { "label": "Cookies de Cloudflare" }, + "flaresolverrUrl": { "label": "URL de FlareSolverr" }, + "challengeTimeout": { "label": "Tiempo de espera del desafío (s)" }, + "refreshInterval": { "label": "Intervalo de actualización (s)" }, + "maxRetries": { "label": "Límite de reintentos de cuenta" }, + "retryCodes": { "label": "Códigos de estado para reintento" }, + "resetSessionCodes": { "label": "Códigos para reinicio de sesión" }, + "chatTimeout": { "label": "Tiempo de espera de chat (s)" }, + "imageTimeout": { "label": "Tiempo de espera de imagen (s)" }, + "videoTimeout": { "label": "Tiempo de espera de video (s)" }, + "voiceTimeout": { "label": "Tiempo de espera de voz (s)" }, + "nsfwTimeout": { "label": "Tiempo de espera de NSFW (s)" }, + "assetUploadTimeout": { "label": "Tiempo de espera de carga de Asset (s)" }, + "assetDownloadTimeout": { "label": "Tiempo de espera de descarga de Asset (s)" }, + "assetListTimeout": { "label": "Tiempo de espera de listado de Asset (s)" }, + "assetDeleteTimeout": { "label": "Tiempo de espera de eliminación de Asset (s)" }, + "streamTimeout": { "label": "Tiempo de espera de inactividad en streaming (s)" }, + "interRoundWait": { "label": "Espera entre rondas (s)" }, + "fileLogLevel": { "label": "Nivel de registro en archivo", "desc": "Nivel mínimo escrito en archivos de registro, configurable independientemente de la consola. Por defecto: INFO." }, + "logMaxFiles": { "label": "Retención de registros (días)", "desc": "Número máximo de archivos de registro diarios a conservar durante la rotación. Por defecto: 7." } + } + } + }, + "cache": { + "pageTitle": "Grok2API - Gestión de Caché", + "pageHeading": "Gestión de Caché", + "pageSubtitle": "Vea y gestione los archivos de caché local, los límites de almacenamiento y los activos en línea de las cuentas.", + "sectionOverview": "Resumen", + "statImageCount": "Archivos de caché de imagen", + "statImageSize": "Tamaño de caché de imagen", + "statVideoCount": "Archivos de caché de video", + "statVideoSize": "Tamaño de caché de video", + "usageSummaryUnlimited": "Usado {used} · Sin límite", + "usageSummaryLimited": "Usado {used} / {limit} · {percent}", + "sectionDetails": "Detalles", + "tabLocal": "Caché local", + "tabLocalImage": "Imágenes locales", + "tabLocalVideo": "Vídeos locales", + "tabOnline": "Activos en línea", + "typeImage": "Imágenes", + "typeVideo": "Videos", + "typeImageNoun": "imagen", + "typeVideoNoun": "video", + "clearCurrent": "Vaciar caché actual", + "deleteSelected": "Eliminar seleccionados", + "clearSelected": "Limpiar seleccionados", + "colFileName": "Nombre del archivo", + "colSize": "Tamaño", + "colModified": "Última modificación", + "colActions": "Acciones", + "colToken": "Token", + "colFileCount": "Archivos", + "onlineAssetLead": "Activos en línea", + "onlineAssetDesc": "son imágenes y adjuntos almacenados en la plataforma Grok. La limpieza afecta solo a los archivos remotos y no elimina la caché local.", + "loadAssets": "Cargar inventario de activos", + "clearAll": "Eliminar todo", + "cancel": "Cancelar", + "assetSummaryIdle": "Cargar activos en línea desde la derecha", + "assetSummary": "{accounts} cuentas · {files} archivos", + "pageIndicator": "Página {current} / {total}", + "pageSizeOption": "{n} / página", + "fileCount": "{n} archivos", + "emptyLocal": "No se encontraron archivos en caché", + "emptyAssetsIdle": "Haz clic en el botón superior derecho para cargar los activos en línea", + "emptyAccounts": "No hay datos de cuentas disponibles", + "actionView": "Ver", + "actionDelete": "Eliminar", + "actionClear": "Limpiar", + "loadFailed": "Error al cargar: {message}", + "clearLocalConfirm": "¿Vaciar todos los archivos de caché local de {type}?", + "clearLocalDone": "Se eliminaron {count} archivo(s) de {type}", + "clearFailed": "La limpieza falló: {message}", + "deleted": "Eliminado", + "deleteSelectedConfirm": "¿Eliminar los {n} archivos seleccionados?", + "deleteSelectedDone": "Se eliminaron {count} archivo(s)", + "deleteFailed": "La eliminación falló: {message}", + "viewUnavailable": "No se puede previsualizar este archivo", + "loading": "Cargando...", + "refreshList": "Actualizar lista", + "expand": "Expandir", + "collapse": "Contraer", + "clearTokenConfirm": "¿Eliminar todos los activos en línea de {token}?", + "clearTokenDone": "Se eliminaron {count} archivo(s)", + "clearSelectedConfirm": "¿Limpiar los activos en línea de las {n} cuentas seleccionadas?", + "clearAllConfirm": "¿Eliminar los activos en línea de las {n} cuentas? Esta acción no se puede deshacer.", + "clearingAssets": "Limpiando activos en línea...", + "clearAllDone": "Limpieza completada: {ok} correctas, {fail} fallidas", + "cancelled": "Cancelado", + "clearFailedPlain": "La limpieza falló", + "connectionInterrupted": "Conexión interrumpida", + "startFailed": "No se pudo iniciar: {message}", + "cancelInProgress": "Se solicitó la cancelación. Espere a que finalice el lote actual.", + "na": "—" + } +} diff --git a/app/statics/i18n/fr.json b/app/statics/i18n/fr.json new file mode 100644 index 0000000000000000000000000000000000000000..f0dedf5b8bcb322c710dd0541e1fec80b317ab27 --- /dev/null +++ b/app/statics/i18n/fr.json @@ -0,0 +1,519 @@ +{ + "common": { + "invalidKey": "Clé invalide", + "connectionFailed": "Échec de la connexion" + }, + "login": { + "adminPageTitle": "Grok2API - Administration", + "adminTitle": "Panneau d’administration", + "adminSubtitle": "Saisissez le mot de passe administrateur pour continuer", + "adminPlaceholder": "Mot de passe administrateur", + "continue": "Continuer", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "Saisissez la clé d’accès", + "webuiPlaceholder": "Clé d’accès", + "enter": "Entrer", + "goToAdmin": "Accéder au panneau d’administration" + }, + "webui": { + "header": { + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "Chats", + "newChat": "Nouveau chat", + "toggleSidebar": "Basculer la barre latérale", + "upload": "Téléverser un fichier", + "noSessions": "Aucun chat pour le moment", + "untitled": "Nouveau chat", + "rename": "Renommer", + "delete": "Supprimer", + "edit": "Modifier", + "copy": "Copier", + "regenerate": "Régénérer", + "like": "J’aime", + "dislike": "Je n’aime pas", + "reasoning": "Réflexion", + "save": "Enregistrer", + "cancel": "Annuler", + "confirm": "Confirmer", + "copySuccess": "Copié", + "renamePrompt": "Renommer le chat", + "deleteConfirm": "Supprimer ce chat ?", + "modelLabel": "Modèle", + "emptyTitle": "Grok Chat", + "empty": "Commencez une nouvelle conversation en envoyant un message.", + "promptPlaceholder": "Saisissez votre message. Entrée pour envoyer, Shift+Entrée pour une nouvelle ligne.", + "editPlaceholder": "Modifier ce message", + "stop": "Arrêter", + "send": "Envoyer", + "statusReady": "Prêt", + "statusConnecting": "Connexion...", + "statusThinking": "Réflexion...", + "statusGenerating": "Génération...", + "statusDone": "Terminé", + "statusStopped": "Arrêté", + "statusFailed": "Échec", + "statusInitFailed": "Échec de l’initialisation", + "errors": { + "enterPrompt": "Veuillez saisir un message", + "imageRequired": "L’édition d’image nécessite au moins une image de référence", + "imageOnly": "L’édition d’image ne prend en charge que les téléversements d’images", + "videoImageOnly": "La génération vidéo n’accepte que les images comme référence", + "imageProxyRequired": "Échec du chargement de l’image. Configurez l’URL de base APP et changez le format de sortie image en local_url, local_md ou base64.", + "videoProxyRequired": "Le chargement de la vidéo a renvoyé 403. Accédez à la page d’administration, configurez l’URL de base APP, puis passez le format de sortie vidéo en mode proxy local (local_url ou local_html) et réessayez.", + "requestFailed": "Échec de la requête", + "initFailed": "Échec de l’initialisation de la page de chat" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "voiceLabel": "Voix", + "personalityLabel": "Personnalité", + "speedLabel": "Vitesse", + "start": "Démarrer", + "pause": "Pause", + "mute": "Muet", + "unmute": "Réactiver le son", + "newSession": "Nouvelle session", + "statusIdle": "Non connecté", + "statusConnecting": "Connexion", + "statusLive": "En direct", + "statusMuted": "Muet", + "statusPaused": "En pause", + "statusError": "Échec", + "idleText": "Cliquez et autorisez l’accès pour vous connecter à Grok Voice via les sessions vocales ChatKit.", + "connectingText": "Demande d’une session vocale Grok et connexion à LiveKit...", + "liveText": "Connexion établie. Vous pouvez maintenant parler directement avec Grok.", + "outputMutedText": "Le haut-parleur est coupé, mais vous pouvez continuer à parler.", + "pausedText": "La session est en pause. Cliquez sur démarrer pour reprendre la session vocale en cours.", + "errorText": "La connexion n’a pas abouti. Vérifiez l’accès au micro puis réessayez.", + "endedText": "La session vocale est terminée. Vous pouvez en démarrer une nouvelle à tout moment.", + "livekitLoadFailed": "Échec du chargement du SDK LiveKit", + "invalidToken": "Réponse de jeton vocal invalide" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "qualitySpeed": "Vitesse", + "qualityQuality": "Qualité", + "modeRounds": "Rounds", + "modeCycles": "Cycles", + "promptPlaceholder": "Décrivez l’image souhaitée. Entrée pour générer, Shift+Entrée pour une nouvelle ligne.", + "generate": "Générer", + "stop": "Arrêter", + "openImage": "Ouvrir l’image", + "statusReady": "Prêt", + "statusConnecting": "Connexion...", + "statusGenerating": "Génération", + "statusCompleted": "Terminé", + "statusStopped": "Arrêté", + "statusFailed": "Échec", + "statusSuccess": "Succès", + "statusPartialFailure": "Échec partiel", + "statusBatchFailed": "Échec", + "emptyTitle": "Commencez avec un prompt", + "emptyText": "Saisissez un prompt et les images apparaîtront ici dans l’ordre.", + "roundLabel": "Round {n}", + "batchFiltered": "Filtré", + "errors": { + "enterPrompt": "Veuillez saisir un prompt", + "requestFailed": "Échec de la requête", + "initFailed": "Échec de l’initialisation de la page Masonry" + } + } + }, + "header": { + "account": "Gestion des Comptes", + "config": "Gestion de la Configuration", + "cache": "Gestion du Cache", + "languageLabel": "Langue", + "logout": "Se déconnecter", + "versionDialogTitle": "Version", + "versionCurrent": "Actuelle", + "versionLatest": "Dernière", + "versionPublishedAt": "Publication", + "versionUpToDate": "Vous utilisez déjà la version la plus récente.", + "versionUpdateAvailable": "Une nouvelle version est disponible.", + "versionChecking": "Vérification des mises à jour...", + "versionRefresh": "Vérifier", + "versionUnavailable": "Échec de la vérification des mises à jour.", + "versionNotesEmpty": "Aucune note de version disponible.", + "versionOpenRelease": "Ouvrir la release", + "versionClose": "Fermer" + }, + "account": { + "pageTitle": "Grok2API - Comptes", + "pageHeading": "Gestion des Comptes", + "pageSubtitle": "Gérez le pool de comptes xAI, la posture de quota et l’état d’exécution utilisés par Grok2API.", + "actionImport": "Importer des comptes", + "actionAdd": "Ajouter un compte", + "actionImportShort": "Importer", + "actionAddShort": "Ajouter", + "sectionOverview": "Vue d’ensemble", + "sectionTable": "Liste des comptes", + "statTotal": "Nombre total de comptes", + "statActive": "Actifs", + "statCooling": "Limités", + "statInvalid": "Anormaux", + "statDisabled": "Désactivés", + "statCalls": "Appels totaux", + "statSuccessTotal": "Succès totaux", + "statAuto": "Solde Auto", + "statFast": "Solde Fast", + "statExpert": "Solde Expert", + "statHeavy": "Solde Heavy", + "filterStatusLabel": "Statut", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "Type", + "filterStatusAll": "Tous", + "filterStatusActive": "Actifs", + "filterStatusCooling": "Limités", + "filterStatusInvalid": "Anormaux", + "filterStatusDisabled": "Désactivés", + "filterNsfwAll": "Tous", + "filterNsfwEnabled": "Activé", + "filterNsfwDisabled": "Désactivé", + "filterTypeAll": "Tous", + "filter": "Filtrer", + "export": "Exporter les données", + "batchNsfw": "Activer NSFW", + "batchNsfwDisable": "Désactiver NSFW", + "rowActionNotSupported": "Le statut actuel ne prend pas en charge cette action", + "batchRefresh": "Actualiser la sélection", + "batchDisable": "Désactiver la sélection", + "batchRestore": "Restaurer la sélection", + "batchDelete": "Supprimer la sélection", + "colToken": "Token", + "colType": "Type de compte", + "colStatus": "Statut d’exécution", + "colQuota": "Quota", + "colSuccess": "Succès", + "colFail": "Échec", + "colRate": "Taux de réussite", + "colLastUsed": "Dernière utilisation", + "colActions": "Actions", + "actionCopy": "Copier", + "actionRefresh": "Actualiser le quota", + "actionDisable": "Désactiver le compte", + "actionRestore": "Restaurer le compte", + "actionEdit": "Modifier", + "actionDelete": "Supprimer", + "empty": "Aucun compte disponible. Utilisez Importer des comptes ou Ajouter un compte pour continuer.", + "pageInfo": "{n} au total", + "pageIndicator": "Page {current} / {total}", + "pageSizeOption": "{n} / page", + "addTitle": "Ajouter un compte", + "addHint": "Saisissez un token par ligne. Les tokens existants seront ignorés automatiquement.", + "addPlaceholder": "Collez les tokens, un par ligne...", + "importTitle": "Importer des comptes", + "importHintDefault": "Prend en charge les formats .txt (un token par ligne) et .json ({pool:[tokens]}).", + "importHintJson": "Le fichier JSON inclut déjà les informations de type de compte. Aucune sélection supplémentaire n’est requise.", + "importHintTxt": "Saisissez un token par ligne. Les tokens importés seront ajoutés au type de compte sélectionné.", + "labelType": "Type", + "labelFile": "Fichier", + "editTitle": "Modifier le compte", + "editTokenPlaceholder": "Saisissez le token mis à jour", + "exportTitle": "Exporter les comptes", + "exportCountPrefix": "", + "exportCountSuffix": " tokens", + "exportJson": "Format JSON (export complet)", + "exportTxt": "Format TXT (tokens uniquement)", + "confirmTitle": "Confirmer l’action", + "cancel": "Annuler", + "confirm": "Confirmer", + "save": "Enregistrer les modifications", + "noFile": "Aucun fichier sélectionné", + "copied": "Copié", + "copyFailed": "Échec de la copie", + "loadFailed": "Échec du chargement", + "notFound": "Compte introuvable", + "enterToken": "Saisissez un token", + "selectFile": "Sélectionnez un fichier", + "readFileFailed": "Impossible de lire le fichier", + "jsonInvalid": "Format JSON invalide", + "jsonShapeInvalid": "Structure JSON invalide. Format attendu : {pool:[tokens]}.", + "jsonEmpty": "Aucun token importable trouvé dans le fichier JSON", + "fileEmpty": "Aucun token importable trouvé dans le fichier", + "adding": "Ajout de {n} comptes…", + "addDone": "Comptes ajoutés", + "addFailed": "Échec de l’ajout des comptes", + "importing": "Importation de {n} comptes…", + "importDone": "Importation terminée", + "importJsonDone": "Importation terminée : {n} comptes traités", + "importFailed": "Échec de l’importation", + "saving": "Enregistrement des modifications…", + "editDone": "Modifications enregistrées", + "editFailed": "Impossible d’enregistrer les modifications", + "saveResult": "{prefix} : {count} comptes ajoutés", + "saveResultSkipped": "{prefix} : {count} ajoutés, {skipped} existaient déjà", + "exportEmpty": "Aucun compte à exporter", + "deleteConfirmTitle": "Confirmer la suppression", + "deleteConfirmOne": "Supprimer {token} ?
Cette action est irréversible.", + "deleteConfirmMany": "Supprimer {n} comptes ?
Cette action est irréversible.", + "deleting": "Suppression de {n} comptes…", + "deleteDone": "{n} supprimé(s)", + "deleteFailed": "Échec de la suppression", + "refreshing": "Actualisation des informations de quota pour {n} comptes…", + "refreshDone": "Actualisation terminée : {ok} réussites, {fail} échecs", + "refreshFailed": "Échec de l’actualisation", + "disableConfirmTitle": "Désactiver le compte", + "disableConfirmBody": "Désactiver {token} ?
Le compte sera retiré de l’allocation des requêtes jusqu’à sa restauration.", + "disablingOne": "Désactivation du compte…", + "disableDone": "Compte désactivé", + "restoreConfirmTitle": "Restaurer le compte", + "restoreConfirmBody": "Restaurer {token} ?
Le compte reprendra la participation à l’allocation des requêtes.", + "restoringOne": "Restauration du compte…", + "restoreDone": "Compte restauré", + "batchDisableConfirmTitle": "Désactiver les comptes", + "batchDisableConfirmBody": "Désactiver les {n} comptes sélectionnés ?
Les comptes désactivés ne participeront plus à l’allocation des requêtes et pourront être restaurés plus tard.", + "disablingMany": "Désactivation de {n} comptes…", + "disableManyDone": "Désactivation terminée : {ok} réussies, {fail} échouées", + "batchRestoreConfirmTitle": "Restaurer les comptes", + "batchRestoreConfirmBody": "Restaurer les {n} comptes sélectionnés ?
Les comptes restaurés participeront de nouveau à l’allocation des requêtes.", + "restoringMany": "Restauration de {n} comptes…", + "restoreManyDone": "Restauration terminée : {ok} réussies, {fail} échouées", + "nsfwConfirmTitle": "Activer NSFW", + "nsfwConfirmBody": "Activer NSFW pour {n} comptes sélectionnés ?", + "nsfwEnablingOne": "Activation de NSFW…", + "nsfwEnabling": "Activation de NSFW pour {n} comptes…", + "nsfwDone": "Mise à jour NSFW terminée : {ok} réussites, {fail} échecs", + "nsfwDisablingOne": "Désactivation de NSFW…", + "nsfwDisableDone": "Désactivation de NSFW terminée : {ok} réussites, {fail} échecs", + "operationFailed": "L’opération a échoué", + "unknown": "Inconnu", + "na": "—", + "pool": { + "autoRecommended": "Détection automatique (recommandée)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" + }, + "status": { + "active": "Actif", + "cooling": "Limité", + "disabled": "Désactivé", + "expired": "Expiré", + "invalid": "Anormal" + } + }, + "config": { + "pageTitle": "Grok2API - Gestion de la Configuration", + "pageHeading": "Gestion de la Configuration", + "pageSubtitle": "Gérez les paramètres d’exécution de Grok2API et le comportement par défaut du service.", + "resetShort": "Réinitialiser", + "saveShort": "Enregistrer", + "resetChanges": "Réinitialiser les modifications", + "saveChanges": "Enregistrer les modifications", + "unsavedDefault": "Des modifications non enregistrées ont été détectées", + "unsavedSingle": "1 modification non enregistrée a été détectée", + "unsavedMultiple": "{n} modifications non enregistrées ont été détectées", + "discardShort": "Annuler", + "saveBarShort": "Enregistrer", + "discardChanges": "Ignorer les modifications", + "randomize": "Générer une valeur", + "loadFailed": "Impossible de charger la configuration : {message}", + "saving": "Enregistrement des modifications...", + "saveSuccess": "Modifications enregistrées", + "saveFailed": "Impossible d’enregistrer les modifications : {message}", + "resetSuccess": "Les modifications non enregistrées ont été ignorées", + "disabledTip": { + "appUrlRequired": "Configurez d’abord l’URL de base de l’application" + }, + "schema": { + "tabs": { + "system": "Système", + "features": "Fonctionnalités", + "schedule": "Planification", + "proxy": "Réseau", + "cache": "Stockage du cache", + "image": "Pipeline d’image" + }, + "groups": { + "baseAccess": "Contrôle d’accès", + "features": "Fonctionnalités principales", + "mediaFormat": "Sortie multimédia", + "refreshSchedule": "Actualisation du quota", + "selection": "Concurrence de sélection", + "batchConcurrency": "Concurrence par lot", + "egressProxy": "Proxy sortant", + "clearance": "Cloudflare Clearance", + "retry": "Politique de reprise", + "timeouts": "Délais d’attente", + "imageProtocol": "NSFW et streaming d'images", + "logging": "Journalisation", + "localMediaCache": "Cache multimédia local" + }, + "options": { + "imageFormat": { + "grokUrl": "URL (Natif Grok)", + "localUrl": "URL (Proxy local)", + "grokMarkdown": "Markdown (Natif Grok)", + "localMarkdown": "Markdown (Proxy local)", + "base64": "Base64 (Intégré)" + }, + "videoFormat": { + "grokUrl": "URL (Natif Grok)", + "localUrl": "URL (Proxy local)", + "grokHtml": "HTML (Natif Grok)", + "localHtml": "HTML (Proxy local)" + }, + "proxyMode": { + "direct": "Direct", + "singleProxy": "Proxy fixe", + "proxyPool": "Pool de proxys" + }, + "clearanceMode": { + "none": "Désactivé", + "manual": "Manuel", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { "label": "URL de base APP" }, + "appKey": { "label": "Mot de passe d’accès APP" }, + "apiKey": { "label": "Clé d’accès API" }, + "webuiEnabled": { "label": "Activer WebUI" }, + "webuiKey": { "label": "Mot de passe d’accès WebUI" }, + "temporary": { "label": "Sessions temporaires" }, + "memory": { "label": "Mémoire conversationnelle" }, + "stream": { "label": "Streaming par défaut" }, + "thinking": { "label": "Sortie de raisonnement par défaut" }, + "autoChatModeFallback": { "label": "Repli du mode AUTO pour le chat" }, + "thinkingSummary": { "label": "Raisonnement condensé" }, + "dynamicStatsig": { "label": "Statsig dynamique" }, + "enableNsfw": { "label": "Autoriser la génération NSFW" }, + "showSearchSources": { "label": "Ajouter les sources au contenu", "desc": "Les sources de recherche sont toujours présentes dans le champ search_sources. Cette option contrôle si une section ## Sources est également ajoutée au contenu (pour la compatibilité avec les clients analysant le texte)." }, + "customInstruction": { "label": "Instruction globale supplémentaire" }, + "imageFormat": { "label": "Format de sortie image", "desc": "grok_url et grok_md renvoient directement l’adresse CDN native de Grok par défaut. Les modes local_* téléchargent d’abord les ressources sur le serveur puis les redistribuent via le proxy local. base64 renvoie une Data URI intégrée. Lorsque le proxy d’images Imagine Public est activé, les images imagine-public renvoyées par le WebSocket sont également servies via le proxy local." }, + "imaginePublicImageProxy": { "label": "Proxy d’images Imagine Public", "desc": "Lorsque cette option est activée, les images imagine-public renvoyées par le WebSocket sont téléchargées sur le serveur puis distribuées via le proxy local. Lorsqu’elle est désactivée, les images publiques sont renvoyées directement." }, + "videoFormat": { "label": "Format de sortie vidéo" }, + "refreshEnabled": { "label": "Activer l’actualisation du quota", "desc": "Lorsqu’il est activé, le système passe automatiquement en mode d’actualisation du quota. Lorsqu’il est désactivé, il passe automatiquement en mode de relance automatique.", "help": "Activé : mode d’actualisation du quota. Le scheduler synchronise périodiquement le quota réel et la sélection utilise un score.\nDésactivé : mode de relance automatique. Aucune sonde upstream active, sélection aléatoire et changement automatique de compte en cas d’erreur jusqu’à 5 relances.\nRecommandation : désactivez-le au-delà de 10 000 comptes pour éviter de déclencher des 429 upstream par les sondes actives." }, + "maxInflight": { "label": "Maximum en cours par compte", "desc": "Nombre maximal de requêtes simultanées par compte. Les comptes à cette limite sont ignorés par la sélection (partagé par les deux modes)." }, + "basicInterval": { "label": "Cycle Basic (s)", "desc": "Cycle partagé du pool Basic : utilisé pour l’actualisation en arrière-plan en mode quota et pour le refroidissement après 429 en mode random. Valeur par défaut : 86400s." }, + "superInterval": { "label": "Cycle Super (s)", "desc": "Cycle partagé du pool Super : utilisé pour l’actualisation en arrière-plan en mode quota et pour le refroidissement après 429 en mode random. Valeur par défaut : 7200s." }, + "heavyInterval": { "label": "Cycle Heavy (s)", "desc": "Cycle partagé du pool Heavy : utilisé pour l’actualisation en arrière-plan en mode quota et pour le refroidissement après 429 en mode random. Valeur par défaut : 7200s." }, + "usageConcurrency": { "label": "Concurrence d’actualisation", "desc": "Nombre maximal d’appels usage parallèles autorisés pendant l’actualisation du quota." }, + "onDemandMinInterval": { "label": "Intervalle d’actualisation à la demande (s)", "desc": "Fenêtre de limitation pour les actualisations déclenchées par les requêtes, par exemple après un 429. Les déclenchements répétés dans l’intervalle sont regroupés en une seule actualisation." }, + "imageCacheMaxMb": { "label": "Limite du cache image (MB)", "desc": "0 désactive la limite. S’applique uniquement aux fichiers multimédias enregistrés via le proxy local. Lorsque la limite est dépassée, les fichiers les plus anciens sont supprimés jusqu’à revenir à 60% de la limite." }, + "videoCacheMaxMb": { "label": "Limite du cache vidéo (MB)", "desc": "0 désactive la limite. S’applique uniquement aux fichiers multimédias enregistrés via le proxy local. Lorsque la limite est dépassée, les fichiers les plus anciens sont supprimés jusqu’à revenir à 60% de la limite." }, + "nsfwConcurrency": { "label": "Concurrence d’activation NSFW" }, + "refreshConcurrency": { "label": "Concurrence d’actualisation Usage" }, + "assetUploadConcurrency": { "label": "Concurrence d’envoi Asset" }, + "assetListConcurrency": { "label": "Concurrence de listage Asset" }, + "assetDeleteConcurrency": { "label": "Concurrence de suppression Asset" }, + "proxyMode": { "label": "Mode proxy" }, + "proxyUrl": { "label": "URL du proxy principal" }, + "resourceProxyUrl": { "label": "URL du proxy de ressources" }, + "proxyPool": { "label": "Pool de proxys principal" }, + "resourceProxyPool": { "label": "Pool de proxys de ressources" }, + "skipSslVerify": { "label": "Ignorer la vérification SSL" }, + "clearanceMode": { "label": "Mode Clearance" }, + "browserFingerprint": { "label": "Empreinte navigateur" }, + "userAgent": { "label": "User-Agent" }, + "cfCookies": { "label": "Cookies Cloudflare" }, + "flaresolverrUrl": { "label": "URL FlareSolverr" }, + "challengeTimeout": { "label": "Délai du challenge (s)" }, + "refreshInterval": { "label": "Intervalle d’actualisation (s)" }, + "maxRetries": { "label": "Limite de reprise de compte" }, + "retryCodes": { "label": "Codes d’état de reprise" }, + "resetSessionCodes": { "label": "Codes d’état de réinitialisation de session" }, + "chatTimeout": { "label": "Délai d’attente chat (s)" }, + "imageTimeout": { "label": "Délai d’attente image (s)" }, + "videoTimeout": { "label": "Délai d’attente vidéo (s)" }, + "voiceTimeout": { "label": "Délai d’attente voix (s)" }, + "nsfwTimeout": { "label": "Délai d’attente NSFW (s)" }, + "assetUploadTimeout": { "label": "Délai d’envoi Asset (s)" }, + "assetDownloadTimeout": { "label": "Délai de téléchargement Asset (s)" }, + "assetListTimeout": { "label": "Délai de listage Asset (s)" }, + "assetDeleteTimeout": { "label": "Délai de suppression Asset (s)" }, + "streamTimeout": { "label": "Délai d’inactivité du streaming (s)" }, + "interRoundWait": { "label": "Attente inter-cycle (s)" }, + "fileLogLevel": { "label": "Niveau de journal fichier", "desc": "Niveau minimum écrit dans les fichiers de journal, configurable indépendamment de la console. Par défaut : INFO." }, + "logMaxFiles": { "label": "Rétention des journaux (jours)", "desc": "Nombre maximum de fichiers de journal quotidiens conservés lors de la rotation. Par défaut : 7." } + } + } + }, + "cache": { + "pageTitle": "Grok2API - Gestion du Cache", + "pageHeading": "Gestion du Cache", + "pageSubtitle": "Consultez et gérez les fichiers de cache locaux, les limites de stockage et les actifs en ligne des comptes.", + "sectionOverview": "Vue d’ensemble", + "statImageCount": "Fichiers de cache image", + "statImageSize": "Taille du cache image", + "statVideoCount": "Fichiers de cache vidéo", + "statVideoSize": "Taille du cache vidéo", + "usageSummaryUnlimited": "Utilisé {used} · Illimité", + "usageSummaryLimited": "Utilisé {used} / {limit} · {percent}", + "sectionDetails": "Détails", + "tabLocal": "Cache local", + "tabLocalImage": "Images locales", + "tabLocalVideo": "Vidéos locales", + "tabOnline": "Actifs en ligne", + "typeImage": "Images", + "typeVideo": "Vidéos", + "typeImageNoun": "image", + "typeVideoNoun": "vidéo", + "clearCurrent": "Vider le cache courant", + "deleteSelected": "Supprimer la sélection", + "clearSelected": "Nettoyer la sélection", + "colFileName": "Nom du fichier", + "colSize": "Taille", + "colModified": "Dernière modification", + "colActions": "Actions", + "colToken": "Token", + "colFileCount": "Fichiers", + "onlineAssetLead": "Actifs en ligne", + "onlineAssetDesc": "sont les images et pièces jointes stockées sur la plateforme Grok. Le nettoyage n’affecte que les fichiers distants et ne supprime pas le cache local.", + "loadAssets": "Charger l’inventaire des actifs", + "clearAll": "Tout supprimer", + "cancel": "Annuler", + "assetSummaryIdle": "Charger les actifs en ligne depuis la droite", + "assetSummary": "{accounts} comptes · {files} fichiers", + "pageIndicator": "Page {current} / {total}", + "pageSizeOption": "{n} / page", + "fileCount": "{n} fichiers", + "emptyLocal": "Aucun fichier en cache trouvé", + "emptyAssetsIdle": "Cliquez sur le bouton en haut à droite pour charger les actifs en ligne", + "emptyAccounts": "Aucune donnée de compte disponible", + "actionView": "Voir", + "actionDelete": "Supprimer", + "actionClear": "Nettoyer", + "loadFailed": "Échec du chargement : {message}", + "clearLocalConfirm": "Supprimer tous les fichiers de cache local de type {type} ?", + "clearLocalDone": "{count} fichier(s) {type} supprimé(s)", + "clearFailed": "Le nettoyage a échoué : {message}", + "deleted": "Supprimé", + "deleteSelectedConfirm": "Supprimer les {n} fichiers sélectionnés ?", + "deleteSelectedDone": "{count} fichier(s) supprimé(s)", + "deleteFailed": "La suppression a échoué : {message}", + "viewUnavailable": "Aperçu indisponible pour ce fichier", + "loading": "Chargement...", + "refreshList": "Actualiser la liste", + "expand": "Développer", + "collapse": "Réduire", + "clearTokenConfirm": "Supprimer tous les actifs en ligne pour {token} ?", + "clearTokenDone": "{count} fichier(s) supprimé(s)", + "clearSelectedConfirm": "Supprimer les actifs en ligne des {n} comptes sélectionnés ?", + "clearAllConfirm": "Supprimer les actifs en ligne de l’ensemble des {n} comptes ? Cette action est irréversible.", + "clearingAssets": "Nettoyage des actifs en ligne...", + "clearAllDone": "Nettoyage terminé : {ok} réussites, {fail} échecs", + "cancelled": "Annulé", + "clearFailedPlain": "Le nettoyage a échoué", + "connectionInterrupted": "Connexion interrompue", + "startFailed": "Échec du démarrage : {message}", + "cancelInProgress": "Annulation demandée. Veuillez patienter jusqu’à la fin du lot en cours.", + "na": "—" + } +} diff --git a/app/statics/i18n/ja.json b/app/statics/i18n/ja.json new file mode 100644 index 0000000000000000000000000000000000000000..4820e0afa7ed6f141da36abeb1dca2ae86fd4efc --- /dev/null +++ b/app/statics/i18n/ja.json @@ -0,0 +1,519 @@ +{ + "common": { + "invalidKey": "無効なキーです", + "connectionFailed": "接続に失敗しました" + }, + "login": { + "adminPageTitle": "Grok2API - 管理", + "adminTitle": "管理パネル", + "adminSubtitle": "続行するには管理者パスワードを入力してください", + "adminPlaceholder": "管理者パスワード", + "continue": "続行", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "アクセスキーを入力してください", + "webuiPlaceholder": "アクセスキー", + "enter": "入る", + "goToAdmin": "管理パネルへ" + }, + "webui": { + "header": { + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "チャット", + "newChat": "新しいチャット", + "toggleSidebar": "サイドバーを切り替え", + "upload": "ファイルをアップロード", + "noSessions": "まだチャットはありません", + "untitled": "新しいチャット", + "rename": "名前を変更", + "delete": "削除", + "edit": "編集", + "copy": "コピー", + "regenerate": "再生成", + "like": "高評価", + "dislike": "低評価", + "reasoning": "思考", + "save": "保存", + "cancel": "キャンセル", + "confirm": "確認", + "copySuccess": "コピーしました", + "renamePrompt": "チャット名を変更", + "deleteConfirm": "このチャットを削除しますか?", + "modelLabel": "モデル", + "emptyTitle": "Grok Chat", + "empty": "メッセージを送信して新しい会話を始めてください。", + "promptPlaceholder": "メッセージを入力してください。Enter で送信、Shift+Enter で改行します。", + "editPlaceholder": "このメッセージを編集", + "stop": "停止", + "send": "送信", + "statusReady": "準備完了", + "statusConnecting": "接続中...", + "statusThinking": "思考中...", + "statusGenerating": "生成中...", + "statusDone": "完了", + "statusStopped": "停止済み", + "statusFailed": "失敗", + "statusInitFailed": "初期化に失敗しました", + "errors": { + "enterPrompt": "メッセージを入力してください", + "imageRequired": "画像編集には少なくとも 1 枚の参照画像が必要です", + "imageOnly": "画像編集では画像ファイルのみアップロードできます", + "videoImageOnly": "動画生成では参照として画像のみアップロードできます", + "imageProxyRequired": "画像を読み込めませんでした。APP ベース URL を設定し、画像の返却形式を local_url、local_md、または base64 に変更してください。", + "videoProxyRequired": "動画の読み込みで 403 が返されました。管理ページで APP ベース URL を設定し、動画の返却形式をローカルプロキシモード(local_url または local_html)に変更してから再試行してください。", + "requestFailed": "リクエストに失敗しました", + "initFailed": "チャットページの初期化に失敗しました" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "voiceLabel": "音声", + "personalityLabel": "性格", + "speedLabel": "速度", + "start": "開始", + "pause": "一時停止", + "mute": "ミュート", + "unmute": "ミュート解除", + "newSession": "新しいセッション", + "statusIdle": "未接続", + "statusConnecting": "接続中", + "statusLive": "会話中", + "statusMuted": "ミュート中", + "statusPaused": "一時停止中", + "statusError": "失敗", + "idleText": "クリックして許可すると、ChatKit の音声セッションを通じて Grok Voice に接続できます。", + "connectingText": "Grok Voice セッションを要求し、LiveKit に接続しています...", + "liveText": "接続されました。これで Grok と直接会話できます。", + "outputMutedText": "スピーカーはミュートされていますが、会話は続けられます。", + "pausedText": "セッションは一時停止中です。開始を押すと現在の音声セッションを再開します。", + "errorText": "接続を確立できませんでした。マイク権限を確認して再試行してください。", + "endedText": "音声セッションは終了しました。いつでも再開できます。", + "livekitLoadFailed": "LiveKit SDK の読み込みに失敗しました", + "invalidToken": "音声トークンの応答が無効です" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "qualitySpeed": "速度", + "qualityQuality": "品質", + "modeRounds": "ラウンド", + "modeCycles": "サイクル", + "promptPlaceholder": "生成したい画像を説明してください。Enter で生成、Shift+Enter で改行します。", + "generate": "生成", + "stop": "停止", + "openImage": "画像を開く", + "statusReady": "準備完了", + "statusConnecting": "接続中...", + "statusGenerating": "生成中", + "statusCompleted": "完了", + "statusStopped": "停止済み", + "statusFailed": "失敗", + "statusSuccess": "生成成功", + "statusPartialFailure": "一部失敗", + "statusBatchFailed": "生成失敗", + "emptyTitle": "プロンプトから始めましょう", + "emptyText": "プロンプトを入力すると、画像がここに順番に表示されます。", + "roundLabel": "ラウンド {n}", + "batchFiltered": "フィルタ済み", + "errors": { + "enterPrompt": "プロンプトを入力してください", + "requestFailed": "リクエストに失敗しました", + "initFailed": "Masonry ページの初期化に失敗しました" + } + } + }, + "header": { + "account": "アカウント管理", + "config": "構成管理", + "cache": "キャッシュ管理", + "languageLabel": "言語", + "logout": "ログアウト", + "versionDialogTitle": "バージョン", + "versionCurrent": "現在", + "versionLatest": "最新", + "versionPublishedAt": "公開日", + "versionUpToDate": "すでに最新バージョンです。", + "versionUpdateAvailable": "新しいバージョンがあります。", + "versionChecking": "更新を確認しています...", + "versionRefresh": "更新を確認", + "versionUnavailable": "更新の確認に失敗しました。", + "versionNotesEmpty": "リリースノートはありません。", + "versionOpenRelease": "リリースを開く", + "versionClose": "閉じる" + }, + "account": { + "pageTitle": "Grok2API - アカウント", + "pageHeading": "アカウント管理", + "pageSubtitle": "Grok2API で使用する xAI アカウントプール、クォータ状況、実行状態を管理します。", + "actionImport": "アカウントをインポート", + "actionAdd": "アカウントを追加", + "actionImportShort": "インポート", + "actionAddShort": "追加", + "sectionOverview": "概要", + "sectionTable": "アカウント一覧", + "statTotal": "総アカウント数", + "statActive": "有効", + "statCooling": "レート制限中", + "statInvalid": "異常", + "statDisabled": "無効化", + "statCalls": "総呼び出し数", + "statSuccessTotal": "成功総数", + "statAuto": "Auto 残高", + "statFast": "Fast 残高", + "statExpert": "Expert 残高", + "statHeavy": "Heavy 残高", + "filterStatusLabel": "状態", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "タイプ", + "filterStatusAll": "すべて", + "filterStatusActive": "有効", + "filterStatusCooling": "レート制限中", + "filterStatusInvalid": "異常", + "filterStatusDisabled": "無効化", + "filterNsfwAll": "すべて", + "filterNsfwEnabled": "オン", + "filterNsfwDisabled": "オフ", + "filterTypeAll": "すべて", + "filter": "絞り込み", + "export": "データをエクスポート", + "batchNsfw": "NSFW を有効化", + "batchNsfwDisable": "NSFW を無効化", + "rowActionNotSupported": "現在の状態ではこの操作はサポートされていません", + "batchRefresh": "選択項目を更新", + "batchDisable": "選択項目を無効化", + "batchRestore": "選択項目を復元", + "batchDelete": "選択項目を削除", + "colToken": "トークン", + "colType": "アカウント種別", + "colStatus": "実行状態", + "colQuota": "クォータ", + "colSuccess": "成功", + "colFail": "失敗", + "colRate": "成功率", + "colLastUsed": "最終使用", + "colActions": "操作", + "actionCopy": "コピー", + "actionRefresh": "クォータを更新", + "actionDisable": "アカウントを無効化", + "actionRestore": "アカウントを復元", + "actionEdit": "編集", + "actionDelete": "削除", + "empty": "アカウントがありません。右上の「アカウントをインポート」または「アカウントを追加」を使用してください。", + "pageInfo": "合計 {n} 件", + "pageIndicator": "{current} / {total} ページ", + "pageSizeOption": "{n} / ページ", + "addTitle": "アカウントを追加", + "addHint": "1 行につき 1 トークンを入力してください。既存トークンは自動的にスキップされます。", + "addPlaceholder": "トークンを貼り付けてください(1 行につき 1 件)...", + "importTitle": "アカウントをインポート", + "importHintDefault": ".txt(1 行につき 1 トークン)および .json({pool:[tokens]})形式に対応しています。", + "importHintJson": "JSON にはアカウント種別情報が含まれているため、追加選択は不要です。", + "importHintTxt": "1 行につき 1 トークンを入力してください。インポートしたトークンは選択したアカウント種別へ追加されます。", + "labelType": "タイプ", + "labelFile": "ファイル", + "editTitle": "アカウントを編集", + "editTokenPlaceholder": "更新後のトークンを入力", + "exportTitle": "アカウントをエクスポート", + "exportCountPrefix": "", + "exportCountSuffix": " トークン", + "exportJson": "JSON 形式(完全なエクスポート)", + "exportTxt": "TXT 形式(トークンのみ)", + "confirmTitle": "操作の確認", + "cancel": "キャンセル", + "confirm": "確認", + "save": "変更を保存", + "noFile": "ファイルが選択されていません", + "copied": "コピーしました", + "copyFailed": "コピーに失敗しました", + "loadFailed": "読み込みに失敗しました", + "notFound": "アカウントが見つかりません", + "enterToken": "トークンを入力してください", + "selectFile": "ファイルを選択してください", + "readFileFailed": "ファイルの読み取りに失敗しました", + "jsonInvalid": "JSON 形式が不正です", + "jsonShapeInvalid": "JSON 構造が不正です。{pool:[tokens]} を想定しています。", + "jsonEmpty": "JSON ファイルにインポート可能なトークンがありません", + "fileEmpty": "ファイルにインポート可能なトークンがありません", + "adding": "{n} 件のアカウントを追加しています…", + "addDone": "アカウントを追加しました", + "addFailed": "アカウントの追加に失敗しました", + "importing": "{n} 件のアカウントをインポートしています…", + "importDone": "インポートが完了しました", + "importJsonDone": "インポート完了: {n} 件を処理しました", + "importFailed": "インポートに失敗しました", + "saving": "変更を保存しています…", + "editDone": "変更を保存しました", + "editFailed": "変更の保存に失敗しました", + "saveResult": "{prefix}: {count} 件のアカウントを追加しました", + "saveResultSkipped": "{prefix}: {count} 件を追加、{skipped} 件は既存のためスキップしました", + "exportEmpty": "エクスポート可能なアカウントがありません", + "deleteConfirmTitle": "削除の確認", + "deleteConfirmOne": "{token} を削除しますか?
この操作は元に戻せません。", + "deleteConfirmMany": "{n} 件のアカウントを削除しますか?
この操作は元に戻せません。", + "deleting": "{n} 件のアカウントを削除しています…", + "deleteDone": "{n} 件を削除しました", + "deleteFailed": "削除に失敗しました", + "refreshing": "{n} 件のアカウントのクォータ情報を更新しています…", + "refreshDone": "更新完了: 成功 {ok} 件、失敗 {fail} 件", + "refreshFailed": "更新に失敗しました", + "disableConfirmTitle": "アカウントを無効化", + "disableConfirmBody": "{token} を無効化しますか?
無効化すると、このアカウントはリクエスト割り当てに参加しません。", + "disablingOne": "アカウントを無効化しています…", + "disableDone": "アカウントを無効化しました", + "restoreConfirmTitle": "アカウントを復元", + "restoreConfirmBody": "{token} を復元しますか?
復元後、このアカウントは再びリクエスト割り当てに参加します。", + "restoringOne": "アカウントを復元しています…", + "restoreDone": "アカウントを復元しました", + "batchDisableConfirmTitle": "アカウントを一括無効化", + "batchDisableConfirmBody": "選択した {n} 件のアカウントを無効化しますか?
無効化されたアカウントはリクエスト割り当てに参加せず、後で復元できます。", + "disablingMany": "{n} 件のアカウントを無効化しています…", + "disableManyDone": "無効化完了: 成功 {ok} 件、失敗 {fail} 件", + "batchRestoreConfirmTitle": "アカウントを一括復元", + "batchRestoreConfirmBody": "選択した {n} 件のアカウントを復元しますか?
復元後、これらのアカウントは再びリクエスト割り当てに参加します。", + "restoringMany": "{n} 件のアカウントを復元しています…", + "restoreManyDone": "復元完了: 成功 {ok} 件、失敗 {fail} 件", + "nsfwConfirmTitle": "NSFW を有効化", + "nsfwConfirmBody": "選択した {n} 件のアカウントで NSFW を有効にしますか?", + "nsfwEnablingOne": "NSFW を有効化しています…", + "nsfwEnabling": "{n} 件のアカウントで NSFW を有効化しています…", + "nsfwDone": "NSFW 更新完了: 成功 {ok} 件、失敗 {fail} 件", + "nsfwDisablingOne": "NSFW を無効化しています…", + "nsfwDisableDone": "NSFW 無効化完了: 成功 {ok} 件、失敗 {fail} 件", + "operationFailed": "操作に失敗しました", + "unknown": "不明", + "na": "—", + "pool": { + "autoRecommended": "自動判定(推奨)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" + }, + "status": { + "active": "有効", + "cooling": "レート制限中", + "disabled": "無効化", + "expired": "期限切れ", + "invalid": "異常" + } + }, + "config": { + "pageTitle": "Grok2API - 構成管理", + "pageHeading": "構成管理", + "pageSubtitle": "Grok2API のランタイム設定とサービス既定動作を管理します。", + "resetShort": "リセット", + "saveShort": "保存", + "resetChanges": "変更をリセット", + "saveChanges": "変更を保存", + "unsavedDefault": "未保存の変更があります", + "unsavedSingle": "未保存の変更が 1 件あります", + "unsavedMultiple": "未保存の変更が {n} 件あります", + "discardShort": "元に戻す", + "saveBarShort": "保存", + "discardChanges": "変更を破棄", + "randomize": "値を生成", + "loadFailed": "構成の読み込みに失敗しました: {message}", + "saving": "変更を保存しています...", + "saveSuccess": "変更を保存しました", + "saveFailed": "変更の保存に失敗しました: {message}", + "resetSuccess": "未保存の変更を破棄しました", + "disabledTip": { + "appUrlRequired": "先に APP Base URL を設定してください" + }, + "schema": { + "tabs": { + "system": "システム", + "features": "機能", + "schedule": "スケジュール", + "proxy": "ネットワーク", + "cache": "キャッシュ保存", + "image": "画像処理" + }, + "groups": { + "baseAccess": "アクセス制御", + "features": "基本機能", + "mediaFormat": "メディア出力", + "refreshSchedule": "クォータ更新", + "selection": "選択同時実行数", + "batchConcurrency": "一括処理の並列数", + "egressProxy": "送信プロキシ", + "clearance": "Cloudflare Clearance", + "retry": "再試行ポリシー", + "timeouts": "リクエストタイムアウト", + "imageProtocol": "NSFW と画像ストリーミング", + "logging": "ログ設定", + "localMediaCache": "ローカルメディアキャッシュ" + }, + "options": { + "imageFormat": { + "grokUrl": "URL(Grok ネイティブ)", + "localUrl": "URL(ローカルプロキシ)", + "grokMarkdown": "Markdown(Grok ネイティブ)", + "localMarkdown": "Markdown(ローカルプロキシ)", + "base64": "Base64(埋め込み)" + }, + "videoFormat": { + "grokUrl": "URL(Grok ネイティブ)", + "localUrl": "URL(ローカルプロキシ)", + "grokHtml": "HTML(Grok ネイティブ)", + "localHtml": "HTML(ローカルプロキシ)" + }, + "proxyMode": { + "direct": "直接接続", + "singleProxy": "固定プロキシ", + "proxyPool": "プロキシプール" + }, + "clearanceMode": { + "none": "無効", + "manual": "手動", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { "label": "APP ベース URL" }, + "appKey": { "label": "APP アクセスパスワード" }, + "apiKey": { "label": "API アクセスキー" }, + "webuiEnabled": { "label": "WebUI を有効化" }, + "webuiKey": { "label": "WebUI アクセスパスワード" }, + "temporary": { "label": "一時セッション" }, + "memory": { "label": "会話メモリ" }, + "stream": { "label": "デフォルトのストリーミング" }, + "thinking": { "label": "デフォルトの推論出力" }, + "autoChatModeFallback": { "label": "AUTO チャットモードのフォールバック" }, + "thinkingSummary": { "label": "思考要約出力" }, + "dynamicStatsig": { "label": "動的 Statsig" }, + "enableNsfw": { "label": "NSFW 生成を許可" }, + "showSearchSources": { "label": "コンテンツにソースを追加", "desc": "検索ソースは常に search_sources フィールドに出力されます。このオプションは、テキスト解析クライアントとの互換性のために ## Sources セクションをコンテンツに追加するかどうかを制御します。" }, + "customInstruction": { "label": "グローバル補助指示" }, + "imageFormat": { "label": "画像出力形式", "desc": "grok_url と grok_md は既定では Grok CDN のネイティブ URL を直接返します。local_* モードでは、先にサーバーへダウンロードしてからローカルプロキシ経由で再配信します。base64 は埋め込み Data URI を返します。Imagine Public 画像プロキシを有効にすると、WebSocket が返す imagine-public 画像もローカルプロキシ経由になります。" }, + "imaginePublicImageProxy": { "label": "Imagine Public 画像プロキシ", "desc": "有効にすると、WebSocket が返す imagine-public 画像をサーバーにダウンロードし、ローカルプロキシ経由で配信します。無効の場合、公開画像はそのまま返します。" }, + "videoFormat": { "label": "動画出力形式" }, + "refreshEnabled": { "label": "クォータ更新を有効化", "desc": "オンにすると自動的にクォータ更新モードへ切り替わり、オフにすると自動的に自動再試行モードへ切り替わります。", "help": "オン:クォータ更新モード。scheduler が実クォータを定期同期し、スコアでアカウントを選択します。\nオフ:自動再試行モード。upstream を能動的に確認せず、ランダム選択し、エラー時は最大 5 回まで別アカウントへ自動切替します。\n推奨:1 万件以上のアカウントではオフにして、能動確認による upstream 429 を避けてください。" }, + "maxInflight": { "label": "アカウントごとの同時実行上限", "desc": "1 アカウントで同時に処理中にできるリクエスト数の上限です。上限に達したアカウントは選択時にスキップされます(両モード共通)。" }, + "basicInterval": { "label": "Basic 周期(秒)", "desc": "Basic プールの共通周期です。quota モードではバックグラウンド更新に、random モードでは 429 クールダウンに使われます。既定値は 86400s です。" }, + "superInterval": { "label": "Super 周期(秒)", "desc": "Super プールの共通周期です。quota モードではバックグラウンド更新に、random モードでは 429 クールダウンに使われます。既定値は 7200s です。" }, + "heavyInterval": { "label": "Heavy 周期(秒)", "desc": "Heavy プールの共通周期です。quota モードではバックグラウンド更新に、random モードでは 429 クールダウンに使われます。既定値は 7200s です。" }, + "usageConcurrency": { "label": "更新並列数", "desc": "クォータ更新中に許可する usage 呼び出しの最大並列数です。" }, + "onDemandMinInterval": { "label": "オンデマンド更新間隔(秒)", "desc": "429 処理など、リクエスト経路から発生する更新のスロットル間隔です。この間隔内の重複トリガーは 1 回の更新にまとめられます。" }, + "imageCacheMaxMb": { "label": "画像キャッシュ上限(MB)", "desc": "0 は無制限です。ローカルプロキシで保存されたメディアにのみ適用され、上限を超えると最も古いファイルから削除し、使用量を上限の 60% まで一気に戻します。" }, + "videoCacheMaxMb": { "label": "動画キャッシュ上限(MB)", "desc": "0 は無制限です。ローカルプロキシで保存されたメディアにのみ適用され、上限を超えると最も古いファイルから削除し、使用量を上限の 60% まで一気に戻します。" }, + "nsfwConcurrency": { "label": "NSFW 有効化の並列数" }, + "refreshConcurrency": { "label": "Usage 更新の並列数" }, + "assetUploadConcurrency": { "label": "Asset アップロード並列数" }, + "assetListConcurrency": { "label": "Asset 一覧取得並列数" }, + "assetDeleteConcurrency": { "label": "Asset 削除並列数" }, + "proxyMode": { "label": "プロキシモード" }, + "proxyUrl": { "label": "プライマリプロキシ URL" }, + "resourceProxyUrl": { "label": "リソースプロキシ URL" }, + "proxyPool": { "label": "プライマリプロキシプール" }, + "resourceProxyPool": { "label": "リソースプロキシプール" }, + "skipSslVerify": { "label": "SSL 検証をスキップ" }, + "clearanceMode": { "label": "Clearance モード" }, + "browserFingerprint": { "label": "ブラウザフィンガープリント" }, + "userAgent": { "label": "User-Agent" }, + "cfCookies": { "label": "Cloudflare Cookies" }, + "flaresolverrUrl": { "label": "FlareSolverr URL" }, + "challengeTimeout": { "label": "チャレンジタイムアウト(秒)" }, + "refreshInterval": { "label": "更新間隔(秒)" }, + "maxRetries": { "label": "アカウント再試行上限" }, + "retryCodes": { "label": "再試行対象のステータスコード" }, + "resetSessionCodes": { "label": "セッション再構築対象のステータスコード" }, + "chatTimeout": { "label": "チャットリクエストタイムアウト(秒)" }, + "imageTimeout": { "label": "画像リクエストタイムアウト(秒)" }, + "videoTimeout": { "label": "動画リクエストタイムアウト(秒)" }, + "voiceTimeout": { "label": "音声リクエストタイムアウト(秒)" }, + "nsfwTimeout": { "label": "NSFW 処理タイムアウト(秒)" }, + "assetUploadTimeout": { "label": "Asset アップロードタイムアウト(秒)" }, + "assetDownloadTimeout": { "label": "Asset ダウンロードタイムアウト(秒)" }, + "assetListTimeout": { "label": "Asset 一覧タイムアウト(秒)" }, + "assetDeleteTimeout": { "label": "Asset 削除タイムアウト(秒)" }, + "streamTimeout": { "label": "ストリーミング待機タイムアウト(秒)" }, + "interRoundWait": { "label": "ラウンド間待機時間(秒)" }, + "fileLogLevel": { "label": "ファイルログレベル", "desc": "ログファイルに書き込む最低レベル。コンソールとは独立して設定できます。デフォルト: INFO。" }, + "logMaxFiles": { "label": "ログ保持日数", "desc": "日次ローテーション時に保持するログファイルの最大数。デフォルト: 7。" } + } + } + }, + "cache": { + "pageTitle": "Grok2API - キャッシュ管理", + "pageHeading": "キャッシュ管理", + "pageSubtitle": "ローカルキャッシュファイル、容量上限、オンラインアセットを確認・管理します。", + "sectionOverview": "概要", + "statImageCount": "画像キャッシュ数", + "statImageSize": "画像キャッシュ容量", + "statVideoCount": "動画キャッシュ数", + "statVideoSize": "動画キャッシュ容量", + "usageSummaryUnlimited": "使用量 {used} · 無制限", + "usageSummaryLimited": "使用量 {used} / {limit} · {percent}", + "sectionDetails": "詳細", + "tabLocal": "ローカルキャッシュ", + "tabLocalImage": "ローカル画像", + "tabLocalVideo": "ローカル動画", + "tabOnline": "オンラインアセット", + "typeImage": "画像", + "typeVideo": "動画", + "typeImageNoun": "画像", + "typeVideoNoun": "動画", + "clearCurrent": "現在のキャッシュを消去", + "deleteSelected": "選択項目を削除", + "clearSelected": "選択項目を消去", + "colFileName": "ファイル名", + "colSize": "サイズ", + "colModified": "更新日時", + "colActions": "操作", + "colToken": "トークン", + "colFileCount": "ファイル数", + "onlineAssetLead": "オンラインアセット", + "onlineAssetDesc": "は Grok プラットフォーム側に保存された画像と添付ファイルです。クリーンアップはリモートファイルのみに影響し、ローカルキャッシュは削除しません。", + "loadAssets": "アセット一覧を読み込む", + "clearAll": "すべて消去", + "cancel": "キャンセル", + "assetSummaryIdle": "右側からオンラインアセットを取得", + "assetSummary": "{accounts} アカウント · {files} ファイル", + "pageIndicator": "{current} / {total} ページ", + "pageSizeOption": "{n} / ページ", + "fileCount": "{n} ファイル", + "emptyLocal": "キャッシュファイルはありません", + "emptyAssetsIdle": "右上のボタンからオンラインアセット一覧を取得してください", + "emptyAccounts": "アカウントデータがありません", + "actionView": "表示", + "actionDelete": "削除", + "actionClear": "消去", + "loadFailed": "読み込みに失敗しました: {message}", + "clearLocalConfirm": "ローカルの{type}キャッシュをすべて消去しますか?", + "clearLocalDone": "{count} 件の{type}ファイルを削除しました", + "clearFailed": "消去に失敗しました: {message}", + "deleted": "削除しました", + "deleteSelectedConfirm": "選択した {n} 件のファイルを削除しますか?", + "deleteSelectedDone": "{count} 件のファイルを削除しました", + "deleteFailed": "削除に失敗しました: {message}", + "viewUnavailable": "このファイルは表示できません", + "loading": "読み込み中...", + "refreshList": "一覧を更新", + "expand": "展開", + "collapse": "折りたたむ", + "clearTokenConfirm": "{token} のオンラインアセットをすべて削除しますか?", + "clearTokenDone": "{count} 件のファイルを削除しました", + "clearSelectedConfirm": "選択した {n} 件のアカウントのオンラインアセットを削除しますか?", + "clearAllConfirm": "{n} 件のアカウントのオンラインアセットをすべて削除しますか?この操作は元に戻せません。", + "clearingAssets": "オンラインアセットを削除しています...", + "clearAllDone": "クリーンアップ完了: 成功 {ok} 件、失敗 {fail} 件", + "cancelled": "キャンセルしました", + "clearFailedPlain": "クリーンアップに失敗しました", + "connectionInterrupted": "接続が中断されました", + "startFailed": "開始に失敗しました: {message}", + "cancelInProgress": "キャンセルを要求しました。現在のバッチ完了までお待ちください。", + "na": "—" + } +} diff --git a/app/statics/i18n/zh.json b/app/statics/i18n/zh.json new file mode 100644 index 0000000000000000000000000000000000000000..35562e666234027ee439e882bdd078edd858da4f --- /dev/null +++ b/app/statics/i18n/zh.json @@ -0,0 +1,708 @@ +{ + "common": { + "invalidKey": "密钥无效", + "connectionFailed": "连接失败" + }, + "login": { + "adminPageTitle": "Grok2API - Admin", + "adminTitle": "管理后台", + "adminSubtitle": "请输入后台密码以继续", + "adminPlaceholder": "后台密码", + "continue": "继续", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "请输入访问密钥", + "webuiPlaceholder": "访问密钥", + "enter": "进入", + "goToAdmin": "进入管理后台" + }, + "header": { + "account": "账户管理", + "config": "配置管理", + "cache": "缓存管理", + "languageLabel": "语言", + "logout": "退出登录", + "versionDialogTitle": "版本信息", + "versionCurrent": "当前版本", + "versionLatest": "最新版本", + "versionPublishedAt": "发布时间", + "versionUpToDate": "当前已经是最新版本。", + "versionUpdateAvailable": "发现新版本可用。", + "versionChecking": "正在检查更新...", + "versionRefresh": "检查更新", + "versionUnavailable": "查询更新失败。", + "versionNotesEmpty": "暂无更新说明。", + "versionOpenRelease": "发布详情", + "versionClose": "关闭" + }, + "webui": { + "header": { + "chat": "聊天", + "masonry": "瀑布流", + "chatkit": "ChatKit" + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "会话", + "newChat": "新建聊天", + "toggleSidebar": "折叠侧边栏", + "upload": "上传文件", + "noSessions": "暂无会话", + "untitled": "新建聊天", + "rename": "改名", + "delete": "删除", + "edit": "编辑", + "copy": "复制", + "regenerate": "重新生成", + "like": "点赞", + "dislike": "点踩", + "reasoning": "思考过程", + "save": "保存", + "cancel": "取消", + "confirm": "确认", + "copySuccess": "已复制", + "renamePrompt": "修改会话名称", + "deleteConfirm": "确定删除这个会话吗?", + "modelLabel": "模型", + "emptyTitle": "Grok Chat", + "empty": "输入一条消息开始新的会话。", + "promptPlaceholder": "输入你的问题,Enter 发送,Shift+Enter 换行", + "editPlaceholder": "编辑这条消息", + "stop": "停止", + "send": "发送", + "statusReady": "就绪", + "statusConnecting": "正在连接…", + "statusThinking": "思考中…", + "statusGenerating": "生成中…", + "statusDone": "完成", + "statusStopped": "已停止", + "statusFailed": "失败", + "statusInitFailed": "初始化失败", + "errors": { + "enterPrompt": "请输入内容", + "imageRequired": "图像编辑至少需要上传一张参考图", + "imageOnly": "图像编辑只支持上传图片", + "videoImageOnly": "视频生成只支持上传图片作为参考图", + "imageProxyRequired": "图片加载失败。请先设置 APP 访问地址,并将图片返回格式改为 local_url、local_md 或 base64。", + "videoProxyRequired": "视频加载 403,请前往管理页面设置 APP 访问地址后,将频返回格式改为本地代理( local_url 或 local_html)模式后重试。", + "requestFailed": "请求失败", + "initFailed": "聊天页面初始化失败" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "voiceLabel": "声音", + "personalityLabel": "个性", + "instructionLabel": "提示", + "speedLabel": "语速", + "start": "开始", + "pause": "暂停", + "mute": "静音", + "unmute": "取消静音", + "newSession": "新会话", + "statusIdle": "未连接", + "statusConnecting": "正在连接", + "statusLive": "语音中", + "statusMuted": "已静音", + "statusPaused": "已暂停", + "statusError": "连接失败", + "idleText": "点击并授权,通过 ChatKit 语音会话连接 Grok Voice。", + "connectingText": "正在向 Grok Voice 申请会话并连接 LiveKit…", + "liveText": "连接已建立,现在可以直接开口和 Grok 对话。", + "outputMutedText": "扬声器已静音,你仍然可以继续说话。", + "pausedText": "会话已暂停,点击开始即可继续当前语音会话。", + "errorText": "连接没有建立成功,请检查麦克风权限后重试。", + "endedText": "语音会话已结束,可以重新开始。", + "livekitLoadFailed": "LiveKit SDK 加载失败", + "invalidToken": "语音 token 返回无效" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "qualitySpeed": "速度", + "qualityQuality": "质量", + "modeRounds": "轮次", + "modeCycles": "循环", + "promptPlaceholder": "描述你想生成的画面,Enter 生成,Shift+Enter 换行", + "generate": "生成", + "stop": "停止", + "openImage": "打开图片", + "statusReady": "就绪", + "statusConnecting": "连接中…", + "statusGenerating": "正在生成", + "statusCompleted": "完成", + "statusStopped": "已停止", + "statusFailed": "失败", + "statusSuccess": "生成成功", + "statusPartialFailure": "部分失败", + "statusBatchFailed": "生成失败", + "emptyTitle": "从一句提示词开始", + "emptyText": "输入提示词后,图片会按顺序显示在这里。", + "roundLabel": "第 {n} 轮", + "batchFiltered": "已过滤", + "errors": { + "enterPrompt": "请输入提示词", + "requestFailed": "请求失败", + "initFailed": "瀑布流页面初始化失败" + } + } + }, + "account": { + "pageTitle": "Grok2API - 账户管理", + "pageHeading": "账户管理", + "pageSubtitle": "统一管理 Grok2API 的 xAI 账户池、额度与运行状态。", + "actionImport": "导入账户", + "actionAdd": "新增账户", + "actionImportShort": "导入", + "actionAddShort": "新增", + "sectionOverview": "概览", + "sectionTable": "账户列表", + "statTotal": "账户总数", + "statActive": "正常账户", + "statCooling": "限流账户", + "statInvalid": "异常账户", + "statDisabled": "禁用账户", + "statCalls": "调用总数", + "statSuccessTotal": "成功总数", + "statAuto": "Auto 余额", + "statFast": "Fast 余额", + "statExpert": "Expert 余额", + "statHeavy": "Heavy 余额", + "filterStatusLabel": "状态", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "类型", + "filterStatusAll": "全部", + "filterStatusActive": "正常", + "filterStatusCooling": "限流", + "filterStatusInvalid": "异常", + "filterStatusDisabled": "禁用", + "filterNsfwAll": "全部", + "filterNsfwEnabled": "开启", + "filterNsfwDisabled": "关闭", + "filterTypeAll": "全部", + "filter": "筛选", + "export": "导出数据", + "batchNsfw": "开启 NSFW", + "batchNsfwDisable": "关闭 NSFW", + "rowActionNotSupported": "当前状态不支持此操作", + "batchRefresh": "刷新选中", + "batchDisable": "禁用选中", + "batchRestore": "恢复选中", + "batchDelete": "删除选中", + "colToken": "Token", + "colType": "账户类型", + "colStatus": "运行状态", + "colQuota": "额度信息", + "colSuccess": "成功", + "colFail": "失败", + "colRate": "成功率", + "colLastUsed": "最近使用", + "colActions": "操作", + "actionCopy": "复制", + "actionRefresh": "刷新额度", + "actionDisable": "禁用账号", + "actionRestore": "恢复账号", + "actionEdit": "编辑", + "actionDelete": "删除", + "empty": "暂无账户,请使用右上角的“导入账户”或“新增账户”。", + "pageInfo": "共 {n} 条", + "pageIndicator": "第 {current} / {total} 页", + "pageSizeOption": "{n} / 页", + "addTitle": "新增账户", + "addHint": "每行一个 Token;已存在的 Token 将自动跳过。", + "addPlaceholder": "粘贴 Token,每行一个...", + "importTitle": "导入账户", + "importHintDefault": "支持 .txt(每行一个 Token)与 .json({pool:[tokens]})两种格式。", + "importHintJson": "JSON 文件已包含账户类型信息,无需额外选择。", + "importHintTxt": "每行一个 Token,导入后将追加到所选账户类型。", + "labelType": "类型", + "labelFile": "文件", + "editTitle": "编辑账户", + "editTokenPlaceholder": "请输入新的 Token", + "exportTitle": "导出账户", + "exportCountPrefix": "共 ", + "exportCountSuffix": " 个 Token", + "exportJson": "JSON 格式(完整导出)", + "exportTxt": "TXT 格式(仅导出 Token)", + "confirmTitle": "确认操作", + "cancel": "取消", + "confirm": "确认", + "save": "保存更改", + "noFile": "未选择文件", + "copied": "已复制", + "copyFailed": "复制失败", + "loadFailed": "加载失败", + "notFound": "未找到该账户", + "enterToken": "请输入 Token", + "selectFile": "请选择文件", + "readFileFailed": "读取文件失败", + "jsonInvalid": "JSON 格式错误", + "jsonShapeInvalid": "JSON 结构无效,应为 {pool:[tokens]}。", + "jsonEmpty": "JSON 文件中没有可导入的 Token", + "fileEmpty": "文件中没有可导入的 Token", + "adding": "正在添加 {n} 个账户…", + "addDone": "新增完成", + "addFailed": "新增失败", + "importing": "正在导入 {n} 个账户…", + "importDone": "导入完成", + "importJsonDone": "导入完成,共 {n} 个", + "importFailed": "导入失败", + "saving": "正在保存修改…", + "editDone": "保存完成", + "editFailed": "保存失败", + "saveResult": "{prefix},新增 {count} 个账户", + "saveResultSkipped": "{prefix},新增 {count} 个,跳过已存在 {skipped} 个", + "exportEmpty": "当前没有可导出的账户", + "deleteConfirmTitle": "确认删除", + "deleteConfirmOne": "确认删除 {token}?
此操作不可撤销。", + "deleteConfirmMany": "确认删除 {n} 个账户?
此操作不可撤销。", + "deleting": "正在删除 {n} 个账户…", + "deleteDone": "已删除 {n} 个", + "deleteFailed": "删除失败", + "refreshing": "正在刷新 {n} 个账户的额度信息…", + "refreshDone": "刷新完成:成功 {ok} 个,失败 {fail} 个", + "refreshFailed": "刷新失败", + "disableConfirmTitle": "禁用账号", + "disableConfirmBody": "确认禁用 {token}?
禁用后该账号不会参与请求分配。", + "disablingOne": "正在禁用账号…", + "disableDone": "账号已禁用", + "restoreConfirmTitle": "恢复账号", + "restoreConfirmBody": "确认恢复 {token}?
恢复后该账号将重新参与请求分配。", + "restoringOne": "正在恢复账号…", + "restoreDone": "账号已恢复", + "batchDisableConfirmTitle": "批量禁用账号", + "batchDisableConfirmBody": "确认禁用选中的 {n} 个账户?
禁用后这些账号不会参与请求分配,但可随时恢复。", + "disablingMany": "正在禁用 {n} 个账户…", + "disableManyDone": "禁用完成:成功 {ok} 个,失败 {fail} 个", + "batchRestoreConfirmTitle": "批量恢复账号", + "batchRestoreConfirmBody": "确认恢复选中的 {n} 个账户?
恢复后这些账号将重新参与请求分配。", + "restoringMany": "正在恢复 {n} 个账户…", + "restoreManyDone": "恢复完成:成功 {ok} 个,失败 {fail} 个", + "nsfwConfirmTitle": "启用 NSFW", + "nsfwConfirmBody": "确认为选中的 {n} 个账户启用 NSFW?", + "nsfwEnablingOne": "正在启用 NSFW…", + "nsfwEnabling": "正在为 {n} 个账户启用 NSFW…", + "nsfwDone": "NSFW 设置完成:成功 {ok} 个,失败 {fail} 个", + "nsfwDisablingOne": "正在关闭 NSFW…", + "nsfwDisableDone": "NSFW 关闭完成:成功 {ok} 个,失败 {fail} 个", + "operationFailed": "操作失败", + "autoNsfwOnImport": "导入后自动开启 NSFW", + "autoNsfwHint": "需要额外时间检测账户状态", + "unknown": "未知", + "na": "—", + "pool": { + "autoRecommended": "自动检测(推荐)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" + }, + "status": { + "active": "正常", + "cooling": "限流", + "disabled": "禁用", + "expired": "过期", + "invalid": "异常" + }, + "autoNsfwOnImport": "导入后自动开启 NSFW", + "autoNsfwHint": "需要额外时间检测账户状态" + }, + "config": { + "pageTitle": "Grok2API - 配置管理", + "pageHeading": "配置管理", + "pageSubtitle": "管理 Grok2API 系统运行时参数与服务默认行为。", + "resetShort": "重置", + "saveShort": "保存", + "resetChanges": "重置更改", + "saveChanges": "保存更改", + "unsavedDefault": "存在未保存的更改", + "unsavedSingle": "存在 1 项未保存的更改", + "unsavedMultiple": "存在 {n} 项未保存的更改", + "discardShort": "撤销", + "saveBarShort": "保存", + "discardChanges": "放弃更改", + "randomize": "随机生成", + "loadFailed": "配置加载失败:{message}", + "saving": "正在保存更改…", + "saveSuccess": "更改已保存", + "saveFailed": "保存更改失败:{message}", + "resetSuccess": "未保存的更改已撤销", + "disabledTip": { + "appUrlRequired": "请先填写 APP 访问地址" + }, + "schema": { + "tabs": { + "system": "系统配置", + "features": "应用功能", + "schedule": "任务调度", + "proxy": "网络代理", + "cache": "缓存存储", + "image": "图像能力" + }, + "groups": { + "baseAccess": "基础访问控制", + "features": "基本功能设置", + "mediaFormat": "媒体返回格式", + "refreshSchedule": "配额刷新调度", + "selection": "选号并发限制", + "batchConcurrency": "批量操作并发", + "egressProxy": "出站代理设置", + "clearance": "Cloudflare Clearance", + "retry": "重试策略", + "timeouts": "请求超时设置", + "imageProtocol": "NSFW 与图像协议", + "logging": "日志配置", + "localMediaCache": "本地媒体缓存" + }, + "options": { + "imageFormat": { + "grokUrl": "URL(Grok 原生)", + "localUrl": "URL(本地代理)", + "grokMarkdown": "Markdown(Grok 原生)", + "localMarkdown": "Markdown(本地代理)", + "base64": "Base64(内嵌)" + }, + "videoFormat": { + "grokUrl": "URL(Grok 原生)", + "localUrl": "URL(本地代理)", + "grokHtml": "HTML(Grok 原生)", + "localHtml": "HTML(本地代理)" + }, + "proxyMode": { + "direct": "直连", + "singleProxy": "代理(固定)", + "proxyPool": "代理(轮转)" + }, + "clearanceMode": { + "none": "关闭", + "manual": "手动", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { + "label": "APP 访问地址", + "desc": "应用对外提供服务的根 URL,格式如 https://your-domain.com。本地代理模式必须配置。" + }, + "appKey": { + "label": "APP 访问密码", + "desc": "管理后台鉴权密码。修改后已有 Session 将立即失效,需重新登录。" + }, + "apiKey": { + "label": "API 调用密钥", + "desc": "OpenAI 兼容 API 的鉴权密钥。多个值请使用英文逗号分隔;留空则禁用鉴权。" + }, + "webuiEnabled": { + "label": "启用 WebUI", + "desc": "开放 WebUI 功能入口。关闭后相关路由将返回 404。" + }, + "webuiKey": { + "label": "WebUI 访问密码", + "desc": "WebUI 的访问鉴权密码。配置后访问时必须提供。" + }, + "temporary": { + "label": "临时会话", + "desc": "启用后请求不会写入 Grok 会话历史,等同于无痕对话。" + }, + "memory": { + "label": "开启会话记忆", + "desc": "启用 Grok Memory,允许模型跨会话记忆用户偏好与上下文。" + }, + "stream": { + "label": "默认流式输出", + "desc": "请求未显式指定 stream 参数时所采用的默认值。" + }, + "thinking": { + "label": "默认思考输出", + "desc": "请求未显式指定 thinking 参数时所采用的默认值。启用后将在 reasoning_content 字段返回思考过程。" + }, + "autoChatModeFallback": { + "label": "AUTO 聊天模式回退", + "desc": "AUTO 聊天模型在 auto 额度不可用时,自动尝试 fast 和 expert 聊天额度窗口。" + }, + "thinkingSummary": { + "label": "思考精简输出", + "desc": "启用后将思考过程提炼为结构化摘要。关闭时输出完整的原始推理过程,支持多 Agent 模型的协作详情与工具调用展示。" + }, + "dynamicStatsig": { + "label": "动态 Statsig", + "desc": "为每次请求动态生成 Statsig 设备指纹,以降低风控拦截概率。" + }, + "enableNsfw": { + "label": "允许 NSFW 生成", + "desc": "允许图像生成接口绕过 NSFW 内容过滤。" + }, + "showSearchSources": { + "label": "正文追加信源", + "desc": "搜索信源始终以 search_sources 字段输出。此选项控制是否同时在正文末尾追加 ## Sources 段落(兼容文本解析客户端)。" + }, + "customInstruction": { + "label": "全局附加指令", + "desc": "为每次请求注入统一的 system 消息,用于约束模型行为或固定角色设定。" + }, + "imageFormat": { + "label": "图片返回格式", + "desc": "grok_url / grok_md 默认直接返回 Grok CDN 地址;local_* 模式会先下载到服务端,再通过本地 URL 代理分发;base64 会以内嵌 Data URI 返回。开启 Imagine Public 图片代理后,WebSocket 返回的 imagine-public 图片也会本地代理。" + }, + "imaginePublicImageProxy": { + "label": "Imagine Public 图片代理", + "desc": "开启后将 WebSocket 返回的 imagine-public 图片下载到服务端,再通过本地 URL 代理分发;关闭时保持公开图片直返。" + }, + "videoFormat": { + "label": "视频返回格式", + "desc": "local_* 模式会先将视频下载至服务端,再通过本地 URL 代理分发;请确保已配置 APP 访问地址,并评估出站带宽消耗。" + }, + "refreshEnabled": { + "label": "启用配额刷新", + "desc": "开启后自动进入配额刷新模式,关闭后自动进入自动重试模式。", + "help": "开启:配额刷新模式,scheduler 周期同步真实配额,选号按评分。\n关闭:自动重试模式,不主动探测 upstream,选号随机,出错自动换号重试最多 5 次。\n建议:万级以上账号关闭,避免主动探测触发 upstream 429。" + }, + "maxInflight": { + "label": "单号并发上限", + "desc": "单个账号同时在执行的请求上限,超过则选号路径跳过该号(两种模式共用)。" + }, + "basicInterval": { + "label": "Basic 周期(秒)", + "desc": "basic 号池共用周期:quota 模式下用于后台刷新,random 模式下用于 429 冷却。默认 86400s。" + }, + "superInterval": { + "label": "Super 周期(秒)", + "desc": "super 号池共用周期:quota 模式下用于后台刷新,random 模式下用于 429 冷却。默认 7200s。" + }, + "heavyInterval": { + "label": "Heavy 周期(秒)", + "desc": "heavy 号池共用周期:quota 模式下用于后台刷新,random 模式下用于 429 冷却。默认 7200s。" + }, + "usageConcurrency": { + "label": "刷新并发数", + "desc": "并发调用 usage 接口刷新额度时允许的最大并行数。" + }, + "onDemandMinInterval": { + "label": "按需刷新间隔(秒)", + "desc": "请求链路触发刷新(例如收到 429)时的节流间隔。N 秒内重复触发只执行一次,避免批量打爆配额接口。" + }, + "imageCacheMaxMb": { + "label": "图片缓存上限(MB)", + "desc": "0 表示不限制。仅对本地代理落盘生效;超限后按最旧文件优先清理,并一次性回落到上限的 60%。" + }, + "videoCacheMaxMb": { + "label": "视频缓存上限(MB)", + "desc": "0 表示不限制。仅对本地代理落盘生效;超限后按最旧文件优先清理,并一次性回落到上限的 60%。" + }, + "nsfwConcurrency": { + "label": "开启 NSFW 并发数", + "desc": "批量开启 NSFW 时的 token 级并发数;每个 token 需经历三步网络请求。" + }, + "refreshConcurrency": { + "label": "刷新 Usage 并发数", + "desc": "批量刷新账户额度时的 token 级并发数。" + }, + "assetUploadConcurrency": { + "label": "上传 Asset 并发数", + "desc": "API 接收文件附件后触发的 Asset 上传任务,全局最大并发数,跨所有请求共享。" + }, + "assetListConcurrency": { + "label": "查询 Asset 并发数", + "desc": "list_assets 接口的全局最大并发数,跨所有请求共享。" + }, + "assetDeleteConcurrency": { + "label": "删除 Asset 并发数", + "desc": "delete_asset 接口的全局最大并发数,同时作为管理后台批量清理的 token 级默认并发值。" + }, + "proxyMode": { + "label": "代理模式", + "desc": "控制出站流量代理策略。direct 为直连;single_proxy 使用固定代理;proxy_pool 在代理池中轮转。" + }, + "proxyUrl": { + "label": "基础代理 URL", + "desc": "API 流量的出站代理地址,支持 http、https、socks5 协议。" + }, + "resourceProxyUrl": { + "label": "资源代理 URL", + "desc": "图片、视频等媒体资源下载的专用代理地址;留空时回落至基础代理。" + }, + "proxyPool": { + "label": "基础代理池", + "desc": "API 流量代理池,每行一个代理 URL,请求时轮转使用。" + }, + "resourceProxyPool": { + "label": "资源代理池", + "desc": "媒体资源下载专用代理池,每行一个代理 URL;留空时回落至基础代理池。" + }, + "skipSslVerify": { + "label": "跳过 SSL 校验", + "desc": "跳过代理服务器 TLS 证书校验,仅在使用自签名证书的代理时启用。" + }, + "clearanceMode": { + "label": "Clearance 校准", + "desc": "控制 Cloudflare Clearance 的获取方式。" + }, + "browserFingerprint": { + "label": "浏览器指纹", + "desc": "curl_cffi 浏览器指纹标识,需与 Cloudflare 期望的 JA3 指纹匹配,例如 chrome136。" + }, + "userAgent": { + "label": "User-Agent", + "desc": "请求头中的 User-Agent,需与 Cloudflare 校验 Cookie 时所使用的浏览器保持一致。" + }, + "cfCookies": { + "label": "Cloudflare Cookies", + "desc": "Cloudflare 下发的完整 Cookie 字符串,应包含 cf_clearance 等字段。" + }, + "flaresolverrUrl": { + "label": "FlareSolverr URL", + "desc": "FlareSolverr 实例的 HTTP 服务地址。" + }, + "challengeTimeout": { + "label": "挑战超时(秒)", + "desc": "FlareSolverr 完成 Cloudflare 挑战允许的最长等待时长。" + }, + "refreshInterval": { + "label": "刷新间隔(秒)", + "desc": "Clearance Cookie 预热刷新任务的调度间隔。" + }, + "maxRetries": { + "label": "应用层重试上限", + "desc": "请求失败后的应用层最大重试次数;0 表示不重试。适用于 chat.completions 与 responses 端点。" + }, + "retryCodes": { + "label": "应用层重试触发状态码", + "desc": "收到指定 HTTP 状态码时触发应用层重试,多个值请使用英文逗号分隔,例如 429,503。" + }, + "resetSessionCodes": { + "label": "传输层会话重建状态码", + "desc": "收到指定 HTTP 状态码时自动重建传输层代理会话(Transport Session),多个值请使用英文逗号分隔。" + }, + "chatTimeout": { + "label": "对话请求超时(秒)", + "desc": "对话与图像编辑请求的 HTTP 连接超时时间。" + }, + "imageTimeout": { + "label": "图像请求超时(秒)", + "desc": "图像生成 WebSocket 请求的总超时时间。" + }, + "videoTimeout": { + "label": "视频请求超时(秒)", + "desc": "视频生成请求的统一超时时间。" + }, + "voiceTimeout": { + "label": "语音请求超时(秒)", + "desc": "语音请求的统一超时时间。" + }, + "nsfwTimeout": { + "label": "NSFW 处理超时(秒)", + "desc": "set_birth_date 与 enable_nsfw 接口调用的超时时间。" + }, + "assetUploadTimeout": { + "label": "资产上传超时(秒)", + "desc": "Asset 上传接口的超时时间。" + }, + "assetDownloadTimeout": { + "label": "资产下载超时(秒)", + "desc": "Asset 下载接口的超时时间。" + }, + "assetListTimeout": { + "label": "资产查询超时(秒)", + "desc": "Asset 查询接口的超时时间。" + }, + "assetDeleteTimeout": { + "label": "资产删除超时(秒)", + "desc": "Asset 删除接口的超时时间。" + }, + "streamTimeout": { + "label": "流式空闲超时(秒)", + "desc": "流式接收图像数据时,连续空闲允许的最长等待时长。" + }, + "interRoundWait": { + "label": "轮次间等待(秒)", + "desc": "每轮出图完成后,用于探测服务端是否仍保持连接的等待时长;若超时未收到 CLOSE,则复用现有连接继续下一轮。" + }, + "fileLogLevel": { + "label": "文件日志等级", + "desc": "日志文件写入的最低等级,可独立于控制台配置。默认 INFO。" + }, + "logMaxFiles": { + "label": "日志保留天数", + "desc": "按天轮转时最多保留的日志文件数量。默认 7。" + } + } + } + }, + "cache": { + "pageTitle": "Grok2API - 缓存管理", + "pageHeading": "缓存管理", + "pageSubtitle": "查看并管理本地缓存文件、容量上限与账户在线资产。", + "sectionOverview": "缓存概览", + "statImageCount": "图片缓存数量", + "statImageSize": "图片缓存大小", + "statVideoCount": "视频缓存数量", + "statVideoSize": "视频缓存大小", + "usageSummaryUnlimited": "已用 {used} · 未限制", + "usageSummaryLimited": "已用 {used} / {limit} · {percent}", + "sectionDetails": "缓存明细", + "tabLocal": "本地缓存", + "tabLocalImage": "本地图片", + "tabLocalVideo": "本地视频", + "tabOnline": "在线资产", + "typeImage": "图片", + "typeVideo": "视频", + "typeImageNoun": "图片", + "typeVideoNoun": "视频", + "clearCurrent": "清空当前缓存", + "deleteSelected": "删除选中", + "clearSelected": "清理选中", + "colFileName": "文件名", + "colSize": "大小", + "colModified": "修改时间", + "colActions": "操作", + "colToken": "Token", + "colFileCount": "文件数", + "onlineAssetLead": "在线资产", + "onlineAssetDesc": "指账户在 Grok 平台侧保存的图片与附件。清理仅影响远端文件,不会删除本地缓存。", + "loadAssets": "加载资产列表", + "clearAll": "清理全部", + "cancel": "取消", + "assetSummaryIdle": "点击右侧获取在线资产", + "assetSummary": "共 {accounts} 个账户 · {files} 个文件", + "pageIndicator": "第 {current} / {total} 页", + "pageSizeOption": "{n} / 页", + "fileCount": "共 {n} 个文件", + "emptyLocal": "暂无缓存文件", + "emptyAssetsIdle": "点击右上角获取在线资产列表", + "emptyAccounts": "暂无账户数据", + "actionView": "查看", + "actionDelete": "删除", + "actionClear": "清理", + "loadFailed": "加载失败:{message}", + "clearLocalConfirm": "确定要清空所有本地{type}缓存吗?", + "clearLocalDone": "已清除 {count} 个{type}文件", + "clearFailed": "清理失败:{message}", + "deleted": "已删除", + "deleteSelectedConfirm": "确定要删除选中的 {n} 个文件吗?", + "deleteSelectedDone": "已删除 {count} 个文件", + "deleteFailed": "删除失败:{message}", + "viewUnavailable": "当前文件暂不支持查看", + "loading": "加载中…", + "refreshList": "刷新列表", + "expand": "展开", + "collapse": "收起", + "clearTokenConfirm": "确定要清理 {token} 的全部在线资产吗?", + "clearTokenDone": "已删除 {count} 个文件", + "clearSelectedConfirm": "确定要清理选中的 {n} 个账户在线资产吗?", + "clearAllConfirm": "确定要清理全部 {n} 个账户的在线资产吗?此操作不可撤销。", + "clearingAssets": "正在清理在线资产…", + "clearAllDone": "清理完成:成功 {ok},失败 {fail}", + "cancelled": "已取消", + "clearFailedPlain": "清理失败", + "connectionInterrupted": "连接中断", + "startFailed": "启动失败:{message}", + "cancelInProgress": "已暂停,请耐心等待本批次完成…", + "na": "—" + } +} \ No newline at end of file diff --git a/app/statics/js/admin-header.js b/app/statics/js/admin-header.js new file mode 100644 index 0000000000000000000000000000000000000000..1827f57d5cd58151ffc11464b7ca31d437d88aca --- /dev/null +++ b/app/statics/js/admin-header.js @@ -0,0 +1,636 @@ +window.renderAdminHeader = async function renderAdminHeader() { + const mount = document.getElementById('admin-header'); + if (!mount || mount.children.length) return; + const scriptVersion = (() => { + try { + const script = document.querySelector('script[src*="/static/js/admin-header.js"]'); + if (!script) return 'v1'; + return new URL(script.src, window.location.href).searchParams.get('v') || 'v1'; + } catch { + return 'v1'; + } + })(); + const HEADER_HTML_CACHE_KEY = `grok2api.admin_header_html.${scriptVersion}`; + const META_VERSION_CACHE_KEY = `grok2api.meta_version.${scriptVersion}`; + let appVersion = ''; + let updateInfo = null; + let updateStatus = 'idle'; + let updatePromise = null; + + const readSessionCache = (key) => { + try { + return sessionStorage.getItem(key) || ''; + } catch { + return ''; + } + }; + + const writeSessionCache = (key, value) => { + if (!value) return; + try { + sessionStorage.setItem(key, value); + } catch {} + }; + + const languageCodes = { + zh: 'CN', + en: 'EN', + ja: 'JA', + es: 'ES', + de: 'DE', + fr: 'FR', + }; + + const initLanguageMenu = () => { + const menu = mount.querySelector('#hd-lang-menu'); + const trigger = mount.querySelector('#hd-lang-trigger'); + const code = mount.querySelector('#hd-lang-code'); + const options = Array.from(mount.querySelectorAll('.admin-lang-option')); + if (!menu || !trigger || !code || !options.length) return; + + const close = () => { + menu.classList.remove('open'); + trigger.setAttribute('aria-expanded', 'false'); + }; + + const sync = () => { + const current = window.I18n?.getLang?.() || localStorage.getItem('grok2api_lang') || 'zh'; + code.textContent = languageCodes[current] || current.toUpperCase(); + options.forEach((option) => { + option.classList.toggle('active', option.dataset.lang === current); + }); + }; + + trigger.addEventListener('click', (event) => { + event.stopPropagation(); + const open = !menu.classList.contains('open'); + menu.classList.toggle('open', open); + trigger.setAttribute('aria-expanded', open ? 'true' : 'false'); + }); + + options.forEach((option) => { + option.addEventListener('click', () => { + const lang = option.dataset.lang; + if (!lang) return; + close(); + if (window.I18n?.setLang) { + I18n.setLang(lang); + } else { + localStorage.setItem('grok2api_lang', lang); + location.reload(); + } + }); + }); + + document.addEventListener('click', (event) => { + const target = event.target; + if (!(target instanceof Node) || !menu.contains(target)) close(); + }); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') close(); + }); + + sync(); + return sync; + }; + + const applyHeaderI18n = () => { + if (window.I18n?.apply) I18n.apply(mount); + const trigger = mount.querySelector('#hd-lang-trigger'); + if (trigger) { + const label = window.t ? t('header.languageLabel') : 'Language'; + trigger.title = label; + trigger.setAttribute('aria-label', label); + } + const logout = mount.querySelector('#hd-logout'); + if (logout) { + const label = window.t ? t('header.logout') : 'Logout'; + logout.title = label; + logout.setAttribute('aria-label', label); + } + }; + + const loadVersion = async () => { + const cachedVersion = window.__grok2apiMetaVersion || readSessionCache(META_VERSION_CACHE_KEY); + if (cachedVersion) { + appVersion = String(cachedVersion).trim(); + window.__grok2apiMetaVersion = appVersion; + return; + } + try { + const res = await fetch('/meta'); + if (!res.ok) throw new Error('meta unavailable'); + const data = await res.json(); + appVersion = String(data?.version || '').trim(); + window.__grok2apiMetaVersion = appVersion; + writeSessionCache(META_VERSION_CACHE_KEY, appVersion); + } catch { + appVersion = ''; + } + }; + + const refreshUpdate = async (force = false) => { + if (updatePromise) return updatePromise; + if (force) updateInfo = null; + updateStatus = 'loading'; + updatePromise = (async () => { + try { + const path = force ? '/meta/update?force=true' : '/meta/update'; + const res = await fetch(path, { cache: 'no-store' }); + if (!res.ok) throw new Error('update unavailable'); + const data = await res.json(); + updateInfo = data && typeof data === 'object' ? data : null; + updateStatus = 'ready'; + } catch { + updateInfo = null; + updateStatus = 'error'; + } + })().finally(() => { + updatePromise = null; + }); + return updatePromise; + }; + + const text = (key, fallback, params) => { + if (typeof window.t !== 'function') return fallback; + const value = t(key, params); + return value === key ? fallback : value; + }; + + const formatDateTime = (value) => { + if (!value) return '-'; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return String(value); + return date.toLocaleString(); + }; + + const escapeHtml = (value) => String(value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + + const sanitizeUrl = (value) => { + try { + const url = new URL(value, window.location.origin); + return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? url.href : ''; + } catch { + return ''; + } + }; + + const sanitizeRenderedHtml = (html) => { + const template = document.createElement('template'); + template.innerHTML = html; + const blockedTags = new Set(['script', 'style', 'iframe', 'object', 'embed', 'link', 'meta']); + + const walk = (node) => { + if (node.nodeType !== Node.ELEMENT_NODE) return; + const el = node; + const tag = el.tagName.toLowerCase(); + + if (blockedTags.has(tag)) { + el.remove(); + return; + } + + Array.from(el.attributes).forEach((attr) => { + const name = attr.name.toLowerCase(); + const value = attr.value || ''; + if (name.startsWith('on')) { + el.removeAttribute(attr.name); + return; + } + if ((name === 'href' || name === 'src') && !sanitizeUrl(value)) { + el.removeAttribute(attr.name); + return; + } + if (name === 'target') { + el.setAttribute('target', '_blank'); + } + }); + + Array.from(el.children).forEach((child) => walk(child)); + }; + + Array.from(template.content.children).forEach((child) => walk(child)); + return template.innerHTML; + }; + + const renderInlineMarkdown = (source) => { + let html = escapeHtml(source); + html = html.replace(/`([^`]+)`/g, (_, code) => `${code}`); + html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, label, href) => { + const safeHref = sanitizeUrl(href.trim()); + const safeLabel = escapeHtml(label.trim() || href.trim()); + return safeHref + ? `${safeLabel}` + : safeLabel; + }); + html = html.replace(/(^|[\s(>])((https?:\/\/|mailto:)[^\s<]+)/g, (_, prefix, rawUrl) => { + const safeHref = sanitizeUrl(rawUrl.trim()); + if (!safeHref) return `${prefix}${rawUrl}`; + return `${prefix}${escapeHtml(rawUrl)}`; + }); + html = html.replace(/\*\*([^*]+)\*\*/g, '$1'); + html = html.replace(/(^|[^\*])\*([^*]+)\*/g, '$1$2'); + return html; + }; + + const renderMarkdown = (source) => { + const lines = String(source || '').replace(/\r\n?/g, '\n').split('\n'); + const html = []; + const paragraph = []; + let listType = ''; + let listItems = []; + let inCodeBlock = false; + let codeLines = []; + let quoteLines = []; + + const flushParagraph = () => { + if (!paragraph.length) return; + html.push(`

${renderInlineMarkdown(paragraph.map((line) => line.trim()).join(' '))}

`); + paragraph.length = 0; + }; + + const flushList = () => { + if (!listItems.length) return; + html.push(`<${listType}>${listItems.map((item) => `
  • ${renderInlineMarkdown(item)}
  • `).join('')}`); + listItems = []; + listType = ''; + }; + + const flushCodeBlock = () => { + if (!inCodeBlock) return; + html.push(`
    ${escapeHtml(codeLines.join('\n'))}
    `); + inCodeBlock = false; + codeLines = []; + }; + + const flushQuote = () => { + if (!quoteLines.length) return; + html.push(`
    ${renderInlineMarkdown(quoteLines.map((line) => line.trim()).join(' '))}
    `); + quoteLines = []; + }; + + for (const line of lines) { + if (line.startsWith('```')) { + flushParagraph(); + flushList(); + flushQuote(); + if (inCodeBlock) { + flushCodeBlock(); + } else { + inCodeBlock = true; + codeLines = []; + } + continue; + } + + if (inCodeBlock) { + codeLines.push(line); + continue; + } + + const trimmed = line.trim(); + const headingMatch = trimmed.match(/^(#{1,6})\s+(.*)$/); + const unorderedMatch = trimmed.match(/^[-*+]\s+(.*)$/); + const orderedMatch = trimmed.match(/^\d+\.\s+(.*)$/); + const quoteMatch = trimmed.match(/^>\s?(.*)$/); + + if (!trimmed) { + flushParagraph(); + flushList(); + flushQuote(); + continue; + } + + if (headingMatch) { + flushParagraph(); + flushList(); + flushQuote(); + const level = headingMatch[1].length; + html.push(`${renderInlineMarkdown(headingMatch[2])}`); + continue; + } + + if (unorderedMatch || orderedMatch) { + flushParagraph(); + flushQuote(); + const nextType = unorderedMatch ? 'ul' : 'ol'; + const itemText = unorderedMatch ? unorderedMatch[1] : orderedMatch[1]; + if (listType && listType !== nextType) flushList(); + listType = nextType; + listItems.push(itemText); + continue; + } + + flushList(); + + if (quoteMatch) { + flushParagraph(); + quoteLines.push(quoteMatch[1]); + continue; + } + + flushQuote(); + + if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { + flushParagraph(); + flushQuote(); + html.push('
    '); + continue; + } + + paragraph.push(line); + } + + flushParagraph(); + flushList(); + flushQuote(); + flushCodeBlock(); + return html.join('') || '

    '; + }; + + const renderReleaseNotes = (source) => { + if (!source.trim()) return `

    ${escapeHtml(text('header.versionNotesEmpty', 'No release notes available.'))}

    `; + if (window.marked && typeof window.marked.parse === 'function') { + return sanitizeRenderedHtml(window.marked.parse(source, { + async: false, + breaks: false, + gfm: true, + })); + } + return renderMarkdown(source); + }; + + const ensureVersionModal = () => { + let overlay = document.getElementById('admin-version-modal'); + if (overlay) return overlay; + + overlay = document.createElement('div'); + overlay.id = 'admin-version-modal'; + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + + `; + document.body.appendChild(overlay); + + const close = () => { + overlay.classList.remove('open'); + overlay.setAttribute('aria-hidden', 'true'); + }; + + overlay.addEventListener('click', (event) => { + if (event.target === overlay) close(); + }); + + overlay.querySelector('#admin-version-modal-close')?.addEventListener('click', close); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && overlay.classList.contains('open')) close(); + }); + + return overlay; + }; + + const renderVersionModal = (overlay = ensureVersionModal()) => { + const title = overlay.querySelector('#admin-version-modal-title'); + const badge = overlay.querySelector('#admin-version-modal-badge'); + const status = overlay.querySelector('#admin-version-modal-status'); + const currentLabel = overlay.querySelector('#admin-version-modal-current-label'); + const currentValue = overlay.querySelector('#admin-version-modal-current'); + const latestLabel = overlay.querySelector('#admin-version-modal-latest-label'); + const latestValue = overlay.querySelector('#admin-version-modal-latest'); + const publishedLabel = overlay.querySelector('#admin-version-modal-published-label'); + const publishedValue = overlay.querySelector('#admin-version-modal-published'); + const notes = overlay.querySelector('#admin-version-modal-notes'); + const link = overlay.querySelector('#admin-version-modal-link'); + const refresh = overlay.querySelector('#admin-version-modal-refresh'); + const close = overlay.querySelector('#admin-version-modal-close'); + const latestVersion = String(updateInfo?.latest_version || appVersion || '').trim(); + const currentVersion = String(appVersion || updateInfo?.current_version || '').trim(); + const releaseUrl = String(updateInfo?.release_url || '').trim(); + const releaseNotes = String(updateInfo?.release_notes || '').trim(); + + if (title) title.textContent = text('header.versionDialogTitle', 'Version'); + if (currentLabel) currentLabel.textContent = `${text('header.versionCurrent', 'Current')}:`; + if (currentValue) currentValue.textContent = currentVersion ? `v${currentVersion}` : '-'; + if (latestLabel) latestLabel.textContent = `${text('header.versionLatest', 'Latest')}:`; + if (latestValue) latestValue.textContent = latestVersion ? `v${latestVersion}` : '-'; + if (publishedLabel) publishedLabel.textContent = `${text('header.versionPublishedAt', 'Published')}:`; + if (publishedValue) publishedValue.textContent = formatDateTime(updateInfo?.published_at); + + if (badge) { + badge.hidden = true; + badge.textContent = ''; + badge.className = 'admin-version-modal-badge'; + } + + if (status) { + status.textContent = ''; + status.className = 'admin-version-modal-status is-hidden'; + } + + if (badge) { + if (updateStatus === 'loading') { + badge.hidden = false; + badge.textContent = text('header.versionChecking', 'Checking for updates...'); + badge.className = 'admin-version-modal-badge is-muted'; + } else if (updateStatus === 'error' || !updateInfo || updateInfo.status === 'error') { + badge.hidden = false; + badge.textContent = text('header.versionUnavailable', 'Unable to check for updates right now.'); + badge.className = 'admin-version-modal-badge is-muted'; + } else if (updateInfo.update_available) { + badge.hidden = false; + badge.textContent = text('header.versionUpdateAvailable', 'A new version is available.'); + badge.className = 'admin-version-modal-badge is-update'; + } else { + badge.hidden = false; + badge.textContent = text('header.versionUpToDate', 'You are already on the latest version.'); + badge.className = 'admin-version-modal-badge is-current'; + } + } + + if (notes) { + if (updateStatus === 'loading' || updateStatus === 'error' || !updateInfo || updateInfo.status === 'error') { + notes.hidden = true; + notes.innerHTML = ''; + } else { + notes.hidden = false; + notes.innerHTML = renderReleaseNotes(releaseNotes); + } + } + + if (link instanceof HTMLAnchorElement) { + if (releaseUrl) { + link.hidden = false; + link.style.display = 'inline-flex'; + link.href = releaseUrl; + link.textContent = text('header.versionOpenRelease', 'Open Release'); + } else { + link.hidden = true; + link.style.display = 'none'; + link.removeAttribute('href'); + link.textContent = ''; + } + } + + if (refresh instanceof HTMLButtonElement) { + refresh.textContent = text('header.versionRefresh', 'Check Now'); + refresh.disabled = updateStatus === 'loading'; + } + + if (close instanceof HTMLButtonElement) { + close.textContent = text('header.versionClose', 'Close'); + } + + overlay.classList.add('open'); + overlay.setAttribute('aria-hidden', 'false'); + }; + + const openVersionModal = async () => { + const overlay = ensureVersionModal(); + updateStatus = 'loading'; + renderVersionModal(overlay); + try { + await refreshUpdate(false); + } finally { + applyVersion(); + if (overlay.classList.contains('open')) { + renderVersionModal(overlay); + } + } + }; + + const applyVersion = () => { + // 版本信息入口已禁用 + const node = mount.querySelector('#hd-version'); + node?.remove(); + }; + + await loadVersion(); + + try { + const cachedHtml = window.__grok2apiAdminHeaderHtml || readSessionCache(HEADER_HTML_CACHE_KEY); + if (cachedHtml) { + mount.innerHTML = cachedHtml; + } else { + const res = await fetch('/static/admin/header.html'); + if (!res.ok) throw new Error('header unavailable'); + const html = await res.text(); + mount.innerHTML = html; + window.__grok2apiAdminHeaderHtml = html; + writeSessionCache(HEADER_HTML_CACHE_KEY, html); + } + } catch { + mount.innerHTML = ` +
    +
    + + +
    +
    + + +
    + +
    +
    +
    `; + } + + const active = mount.dataset.active || location.pathname; + mount.querySelectorAll('[data-nav]').forEach((link) => { + link.classList.toggle('active', link.dataset.nav === active); + }); + + const syncLanguageMenu = initLanguageMenu(); + applyHeaderI18n(); + applyVersion(); + syncLanguageMenu?.(); + + const versionModal = ensureVersionModal(); + versionModal.querySelector('#admin-version-modal-refresh')?.addEventListener('click', async () => { + renderVersionModal(versionModal); + try { + await refreshUpdate(true); + } finally { + applyVersion(); + if (versionModal.classList.contains('open')) { + renderVersionModal(versionModal); + } + } + }); +}; diff --git a/app/statics/js/auth.js b/app/statics/js/auth.js new file mode 100644 index 0000000000000000000000000000000000000000..38bf9c029b14a2db35d0792c4397fd147d97e258 --- /dev/null +++ b/app/statics/js/auth.js @@ -0,0 +1,52 @@ +/* Grok2API — Auth module */ +const ADMIN_API = '/admin/api'; +const WEBUI_API = '/webui/api'; + +const _ENC = new TextEncoder(), _DEC = new TextDecoder(); +const _SECRET = 'grok2api-admin-key'; +const _XOR_P = 'enc:xor:', _AES_P = 'enc:v1:'; + +function _toB64(b) { let s=''; b.forEach(v=>s+=String.fromCharCode(v)); return btoa(s); } +function _fromB64(s) { const d=atob(s), a=new Uint8Array(d.length); for(let i=0;i{ const s=localStorage.getItem(k)||''; if(!s)return''; try{return await _decrypt(s)}catch{localStorage.removeItem(k);return''} }, + set: async(v)=>{ if(!v){localStorage.removeItem(k);return} localStorage.setItem(k,await _encrypt(v)||'') }, + clear: ()=>localStorage.removeItem(k), + }; +} + +const adminKey = _keyStore('grok2api_admin_key'); +const webuiKey = _keyStore('grok2api_webui_key'); + +async function verifyKey(url, key) { + return (await fetch(url, { headers: key ? { Authorization: `Bearer ${key}` } : {} })).ok; +} + +function adminLogout() { adminKey.clear(); webuiKey.clear(); location.href='/admin/login'; } +function webuiLogout() { webuiKey.clear(); location.href='/webui/login'; } diff --git a/app/statics/js/footer.js b/app/statics/js/footer.js new file mode 100644 index 0000000000000000000000000000000000000000..934033a84e812df7974fc20b59fb89a3c3925f78 --- /dev/null +++ b/app/statics/js/footer.js @@ -0,0 +1,60 @@ +window.renderSiteFooter = async function renderSiteFooter() { + if (document.querySelector('.site-footer')) return; + + let version = ''; + try { + const res = await fetch('/meta', { cache: 'no-store' }); + if (res.ok) { + const data = await res.json(); + version = String(data?.version || '').trim(); + } + } catch {} + + const footer = document.createElement('div'); + footer.className = 'site-footer'; + footer.setAttribute('aria-hidden', 'true'); + + const link = (text, href) => { + const node = document.createElement('a'); + node.href = href; + node.target = '_blank'; + node.rel = 'noopener'; + node.textContent = text; + return node; + }; + + const sep = () => { + const node = document.createElement('span'); + node.textContent = '·'; + return node; + }; + + const brand = link('Grok2API', 'https://github.com/jiujiu532/grok2api'); + footer.appendChild(brand); + + footer.appendChild(sep()); + + const author = link('@Chenyme', 'https://blog.cheny.me/'); + footer.appendChild(author); + + footer.appendChild(sep()); + + const author2 = link('@jiu', 'https://github.com/jiujiu532'); + footer.appendChild(author2); + + document.body.appendChild(footer); +}; + +const _bootSiteFooter = () => { + if (typeof window.renderSiteFooter === 'function') { + void window.renderSiteFooter(); + } +}; + +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', _bootSiteFooter, { once: true }); +} else { + _bootSiteFooter(); +} + +window.addEventListener('pageshow', _bootSiteFooter); diff --git a/app/statics/js/i18n.js b/app/statics/js/i18n.js new file mode 100644 index 0000000000000000000000000000000000000000..a8b614f51cd47b21ad96d5b9f81d66f751f57dae --- /dev/null +++ b/app/statics/js/i18n.js @@ -0,0 +1,100 @@ +/* Grok2API — i18n */ +(function(){ + var KEY='grok2api_lang', + LANGS={ + zh:{label:'简体中文', html:'zh-CN'}, + en:{label:'English', html:'en'}, + ja:{label:'日本語', html:'ja'}, + es:{label:'Español', html:'es'}, + de:{label:'Deutsch', html:'de'}, + fr:{label:'Français', html:'fr'} + }, + LANG_CODES=Object.keys(LANGS), + lang='zh', + data={}, + ready=false, + queue=[]; + + function normalize(l){ + if(!l) return ''; + l=String(l).toLowerCase(); + if(LANGS[l]) return l; + l=l.split('-')[0]; + return LANGS[l]?l:''; + } + + function detect(){ + try{ var s=normalize(localStorage.getItem(KEY)); if(s) return s; }catch(e){} + var p; try{p=new URLSearchParams(location.search).get('lang')}catch(e){} + p=normalize(p); + if(p){try{localStorage.setItem(KEY,p)}catch(e){} return p;} + var b=normalize(navigator.language||''); + return b||'zh'; + } + + function get(o,k){ + if(typeof k!=='string' || !k) return; + for(var p=k.split('.'),i=0;i/g,'>'); +} + +function showToast(message, type = 'success') { + const tone = type === 'error' ? 'error' : (type === 'info' ? 'info' : 'success'); + const icon = tone === 'success' + ? '' + : tone === 'error' + ? '' + : ''; + const el = document.createElement('div'); + el.className = `toast toast-${tone}`; + el.innerHTML = `
    ${icon}
    ${_esc(message)}
    `; + _toastContainer().appendChild(el); + setTimeout(() => { + el.classList.add('out'); + el.addEventListener('animationend', () => el.remove(), { once: true }); + }, 3000); +} + +/** + * Show a persistent progress toast that stays open until finish() is called. + * + * @param {string} label Initial label text shown inside the toast. + * @returns {{ update(done, total): void, finish(msg, type?): void, dismiss(): void }} + * + * Usage: + * const p = showProgressToast('正在刷新 Usage…'); + * p.update(10, 50); // update progress bar and counter + * p.finish('完成:50 个', 'success'); // switch to result state, auto-dismiss + */ +function showProgressToast(label) { + const SPIN = ''; + + const el = document.createElement('div'); + el.className = 'toast toast-info'; + el.innerHTML = ` +
    ${SPIN}
    +
    +
    ${_esc(label)}
    +
    +
    + `; + _toastContainer().appendChild(el); + + const iconEl = el.querySelector('.toast-icon'); + const labelEl = el.querySelector('.toast-progress-label'); + const fill = el.querySelector('.toast-progress-fill'); + const countEl = el.querySelector('.toast-progress-count'); + + function _dismiss() { + el.classList.add('out'); + el.addEventListener('animationend', () => el.remove(), { once: true }); + } + + return { + update(done, total) { + const pct = total > 0 ? Math.min(100, Math.round(done / total * 100)) : 0; + fill.style.width = pct + '%'; + countEl.textContent = total > 0 ? `${done} / ${total}` : `${done}`; + }, + finish(msg, type = 'success') { + const tone = type === 'error' ? 'error' : 'success'; + const icon = tone === 'success' + ? '' + : ''; + el.className = `toast toast-${tone}`; + iconEl.innerHTML = icon; + fill.style.width = '100%'; + labelEl.textContent = msg; + countEl.textContent = ''; + setTimeout(_dismiss, 3000); + }, + dismiss: _dismiss, + }; +} diff --git a/app/statics/js/webui-header.js b/app/statics/js/webui-header.js new file mode 100644 index 0000000000000000000000000000000000000000..570ff826e28e10c57a449960cf7e35e3fd15d681 --- /dev/null +++ b/app/statics/js/webui-header.js @@ -0,0 +1,224 @@ +window.renderWebuiHeader = async function renderWebuiHeader() { + const mount = document.getElementById('webui-header'); + if (!mount || mount.children.length) return; + const scriptVersion = (() => { + try { + const script = document.querySelector('script[src*="/static/js/webui-header.js"]'); + if (!script) return 'v1'; + return new URL(script.src, window.location.href).searchParams.get('v') || 'v1'; + } catch { + return 'v1'; + } + })(); + const HEADER_HTML_CACHE_KEY = `grok2api.webui_header_html.${scriptVersion}`; + const META_VERSION_CACHE_KEY = `grok2api.meta_version.${scriptVersion}`; + let appVersion = ''; + + const readSessionCache = (key) => { + try { + return sessionStorage.getItem(key) || ''; + } catch { + return ''; + } + }; + + const writeSessionCache = (key, value) => { + if (!value) return; + try { + sessionStorage.setItem(key, value); + } catch {} + }; + + const languageCodes = { + zh: 'CN', + en: 'EN', + ja: 'JA', + es: 'ES', + de: 'DE', + fr: 'FR', + }; + + const initLanguageMenu = () => { + const menu = mount.querySelector('#hd-lang-menu'); + const trigger = mount.querySelector('#hd-lang-trigger'); + const code = mount.querySelector('#hd-lang-code'); + const options = Array.from(mount.querySelectorAll('.admin-lang-option')); + if (!menu || !trigger || !code || !options.length) return; + + const close = () => { + menu.classList.remove('open'); + trigger.setAttribute('aria-expanded', 'false'); + }; + + const sync = () => { + const current = window.I18n?.getLang?.() || localStorage.getItem('grok2api_lang') || 'zh'; + code.textContent = languageCodes[current] || current.toUpperCase(); + options.forEach((option) => { + option.classList.toggle('active', option.dataset.lang === current); + }); + }; + + trigger.addEventListener('click', (event) => { + event.stopPropagation(); + const open = !menu.classList.contains('open'); + menu.classList.toggle('open', open); + trigger.setAttribute('aria-expanded', open ? 'true' : 'false'); + }); + + options.forEach((option) => { + option.addEventListener('click', () => { + const lang = option.dataset.lang; + if (!lang) return; + close(); + if (window.I18n?.setLang) { + I18n.setLang(lang); + } else { + localStorage.setItem('grok2api_lang', lang); + location.reload(); + } + }); + }); + + document.addEventListener('click', (event) => { + const target = event.target; + if (!(target instanceof Node) || !menu.contains(target)) close(); + }); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') close(); + }); + + sync(); + return sync; + }; + + const applyHeaderI18n = () => { + if (window.I18n?.apply) I18n.apply(mount); + const trigger = mount.querySelector('#hd-lang-trigger'); + if (trigger) { + const label = window.t ? t('header.languageLabel') : 'Language'; + trigger.title = label; + trigger.setAttribute('aria-label', label); + } + const logout = mount.querySelector('#hd-logout'); + if (logout) { + const hidden = mount.dataset.hideLogout === 'true'; + logout.hidden = hidden; + if (!hidden) { + const label = window.t ? t('header.logout') : 'Logout'; + logout.title = label; + logout.setAttribute('aria-label', label); + } + } + }; + + const loadVersion = async () => { + const cachedVersion = window.__grok2apiMetaVersion || readSessionCache(META_VERSION_CACHE_KEY); + if (cachedVersion) { + appVersion = String(cachedVersion).trim(); + window.__grok2apiMetaVersion = appVersion; + return; + } + try { + const res = await fetch('/meta'); + if (!res.ok) throw new Error('meta unavailable'); + const data = await res.json(); + appVersion = String(data?.version || '').trim(); + window.__grok2apiMetaVersion = appVersion; + writeSessionCache(META_VERSION_CACHE_KEY, appVersion); + } catch { + appVersion = ''; + } + }; + + const applyVersion = () => { + // 版本号显示已禁用 + const node = mount.querySelector('#hd-version'); + node?.remove(); + }; + + await loadVersion(); + + try { + const cachedHtml = window.__grok2apiWebuiHeaderHtml || readSessionCache(HEADER_HTML_CACHE_KEY); + if (cachedHtml) { + mount.innerHTML = cachedHtml; + } else { + const res = await fetch('/static/webui/header.html'); + if (!res.ok) throw new Error('header unavailable'); + const html = await res.text(); + mount.innerHTML = html; + window.__grok2apiWebuiHeaderHtml = html; + writeSessionCache(HEADER_HTML_CACHE_KEY, html); + } + } catch { + mount.innerHTML = ` +
    +
    + + +
    +
    + + +
    + +
    +
    +
    `; + } + + const active = mount.dataset.active || location.pathname; + mount.querySelectorAll('[data-nav]').forEach((link) => { + link.classList.toggle('active', link.dataset.nav === active); + }); + + const syncLanguageMenu = initLanguageMenu(); + applyHeaderI18n(); + applyVersion(); + syncLanguageMenu?.(); +}; diff --git a/app/statics/js/webui/chat.js b/app/statics/js/webui/chat.js new file mode 100644 index 0000000000000000000000000000000000000000..ff3481f17a8078a1138db9bf91a4ad2c72116a50 --- /dev/null +++ b/app/statics/js/webui/chat.js @@ -0,0 +1,1706 @@ +(() => { + const VERIFY_ENDPOINT = '/webui/api/verify'; + const MODELS_ENDPOINT = '/webui/api/models'; + const CHAT_ENDPOINT = '/webui/api/chat/completions'; + const PREFERRED_MODEL = 'grok-4.20-0309-non-reasoning'; + const STORE_KEY = 'grok2api_webui_chat_sessions_v1'; + const SIDEBAR_STORE_KEY = 'grok2api_webui_sidebar_collapsed_v1'; + + const chatLayout = document.getElementById('chatLayout'); + const modelSelect = document.getElementById('modelSelect'); + const systemInput = document.getElementById('systemInput'); + const thread = document.getElementById('thread'); + const emptyState = document.getElementById('emptyState'); + const statusEl = document.getElementById('status'); + const promptInput = document.getElementById('promptInput'); + const sendBtn = document.getElementById('sendBtn'); + const newChatBtn = document.getElementById('newChatBtn'); + const sidebarToggleBtn = document.getElementById('sidebarToggleBtn'); + const sessionList = document.getElementById('sessionList'); + const uploadBtn = document.getElementById('uploadBtn'); + const fileInput = document.getElementById('fileInput'); + const uploadMeta = document.getElementById('uploadMeta'); + const sessionModal = document.getElementById('sessionModal'); + const sessionModalTitle = document.getElementById('sessionModalTitle'); + const sessionModalDesc = document.getElementById('sessionModalDesc'); + const sessionModalInputWrap = document.getElementById('sessionModalInputWrap'); + const sessionModalInput = document.getElementById('sessionModalInput'); + const sessionModalCancel = document.getElementById('sessionModalCancel'); + const sessionModalConfirm = document.getElementById('sessionModalConfirm'); + + let sessions = []; + let currentSessionId = ''; + let messages = []; + let abortController = null; + let sending = false; + let pendingFiles = []; + let modalResolver = null; + let sidebarCollapsed = false; + let availableModels = []; + let activeEdit = null; + const PROMPT_MIN_HEIGHT = 36; + const PROMPT_MAX_HEIGHT = 108; + let pendingThreadScrollFrame = 0; + let sessionListRenderSignature = ''; + + function text(key, fallback, params) { + if (typeof window.t !== 'function') return fallback; + const value = t(key, params); + return value === key ? fallback : value; + } + + function toast(message, type = 'info') { + if (typeof showToast === 'function') showToast(message, type); + } + + function formatModelOptionLabel(modelId, fallbackName) { + const normalized = String(modelId || '').trim().toLowerCase(); + if (!normalized) return fallbackName || ''; + + return normalized + .split('-') + .filter(Boolean) + .map((part) => part ? part.charAt(0).toUpperCase() + part.slice(1) : part) + .join(' '); + } + + function currentSystemPrompt() { + return systemInput ? (systemInput.value || '').trim() : ''; + } + + function escapeHtml(value) { + return String(value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + function hasVisibleReasoning(value) { + return typeof value === 'string' && value.trim().length > 0; + } + + function hasMessageContent(value) { + const textValue = typeof value === 'string' ? value : extractTextContent(value); + return Boolean((textValue || '').trim()); + } + + function sanitizeUrl(value) { + try { + const url = new URL(value, window.location.origin); + return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? url.href : ''; + } catch { + return ''; + } + } + + function sanitizeRenderedHtml(html) { + const template = document.createElement('template'); + template.innerHTML = html; + + const blockedTags = new Set(['script', 'style', 'iframe', 'object', 'embed', 'link', 'meta']); + + function walk(node) { + if (node.nodeType !== Node.ELEMENT_NODE) return; + const el = node; + const tag = el.tagName.toLowerCase(); + + if (blockedTags.has(tag)) { + el.remove(); + return; + } + + Array.from(el.attributes).forEach((attr) => { + const name = attr.name.toLowerCase(); + const value = attr.value || ''; + if (name.startsWith('on')) { + el.removeAttribute(attr.name); + return; + } + if ((name === 'href' || name === 'src') && !sanitizeUrl(value)) { + el.removeAttribute(attr.name); + return; + } + if (name === 'target') { + el.setAttribute('target', '_blank'); + } + }); + + Array.from(el.children).forEach((child) => walk(child)); + } + + Array.from(template.content.children).forEach((child) => walk(child)); + return template.innerHTML; + } + + function renderInlineMarkdown(source) { + let html = escapeHtml(source); + html = html.replace(/`([^`]+)`/g, (_, code) => `${code}`); + html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, label, href) => { + const safeHref = sanitizeUrl(href.trim()); + const safeLabel = label.trim() || href.trim(); + return safeHref + ? `${safeLabel}` + : safeLabel; + }); + html = html.replace(/\*\*([^*]+)\*\*/g, '$1'); + html = html.replace(/(^|[^\*])\*([^*]+)\*/g, '$1$2'); + return html; + } + + function renderMarkdown(source) { + const lines = String(source || '').replace(/\r\n?/g, '\n').split('\n'); + const html = []; + const paragraph = []; + let listType = ''; + let listItems = []; + let inCodeBlock = false; + let codeLines = []; + + function flushParagraph() { + if (!paragraph.length) return; + html.push(`

    ${paragraph.map((line) => renderInlineMarkdown(line)).join('
    ')}

    `); + paragraph.length = 0; + } + + function flushList() { + if (!listItems.length) return; + html.push(`<${listType}>${listItems.map((item) => `
  • ${renderInlineMarkdown(item)}
  • `).join('')}`); + listItems = []; + listType = ''; + } + + function flushCodeBlock() { + if (!inCodeBlock) return; + html.push(`
    ${escapeHtml(codeLines.join('\n'))}
    `); + inCodeBlock = false; + codeLines = []; + } + + for (const line of lines) { + if (line.startsWith('```')) { + flushParagraph(); + flushList(); + if (inCodeBlock) { + flushCodeBlock(); + } else { + inCodeBlock = true; + codeLines = []; + } + continue; + } + + if (inCodeBlock) { + codeLines.push(line); + continue; + } + + const trimmed = line.trim(); + const headingMatch = trimmed.match(/^(#{1,6})\s+(.*)$/); + const unorderedMatch = trimmed.match(/^[-*+]\s+(.*)$/); + const orderedMatch = trimmed.match(/^\d+\.\s+(.*)$/); + const quoteMatch = trimmed.match(/^>\s?(.*)$/); + + if (!trimmed) { + flushParagraph(); + flushList(); + continue; + } + + if (headingMatch) { + flushParagraph(); + flushList(); + const level = headingMatch[1].length; + html.push(`${renderInlineMarkdown(headingMatch[2])}`); + continue; + } + + if (unorderedMatch || orderedMatch) { + flushParagraph(); + const nextType = unorderedMatch ? 'ul' : 'ol'; + const itemText = unorderedMatch ? unorderedMatch[1] : orderedMatch[1]; + if (listType && listType !== nextType) flushList(); + listType = nextType; + listItems.push(itemText); + continue; + } + + flushList(); + + if (quoteMatch) { + flushParagraph(); + html.push(`
    ${renderInlineMarkdown(quoteMatch[1])}
    `); + continue; + } + + paragraph.push(line); + } + + flushParagraph(); + flushList(); + flushCodeBlock(); + return html.join('') || '

    '; + } + + function _extractMath(source) { + const placeholders = []; + // Display math: $$...$$ (must come before inline to avoid double-match) + let out = source.replace(/\$\$([\s\S]+?)\$\$/g, (_, tex) => { + const i = placeholders.length; + placeholders.push({ tex, display: true }); + return `\x02MATH${i}\x03`; + }); + // Inline math: $...$ (single-line only, no space at edges to avoid false positives) + out = out.replace(/\$([^\n$]+?)\$/g, (_, tex) => { + const i = placeholders.length; + placeholders.push({ tex, display: false }); + return `\x02MATH${i}\x03`; + }); + return { out, placeholders }; + } + + function renderRichMarkdown(source) { + if (window.marked && typeof window.marked.parse === 'function') { + let toRender = normalizeMediaContent(source); + let placeholders = []; + + if (window.katex) { + const extracted = _extractMath(toRender); + toRender = extracted.out; + placeholders = extracted.placeholders; + } + + let rendered = window.marked.parse(toRender, { + async: false, + breaks: true, + gfm: true, + }); + + if (window.katex && placeholders.length) { + rendered = rendered.replace(/\x02MATH(\d+)\x03/g, (_, idx) => { + const { tex, display } = placeholders[parseInt(idx, 10)]; + try { + return window.katex.renderToString(tex, { displayMode: display, throwOnError: false }); + } catch (_e) { + return escapeHtml(display ? `$$${tex}$$` : `$${tex}$`); + } + }); + } + + return sanitizeRenderedHtml(rendered); + } + return renderMarkdown(source); + } + + function isImageUrl(value) { + const normalized = String(value || '').trim().toLowerCase(); + return normalized.includes('/v1/files/image') + || /\.(png|jpe?g|gif|webp|bmp|svg)(\?|#|$)/.test(normalized) + || normalized.startsWith('data:image/'); + } + + function isVideoUrl(value) { + const normalized = String(value || '').trim().toLowerCase(); + return normalized.includes('/v1/files/video') + || /\.(mp4|webm|mov|m4v|ogg)(\?|#|$)/.test(normalized); + } + + function normalizeMediaContent(source) { + const input = String(source || '').replace(/\[video\]\(([^)]+)\)/gi, '$1'); + return input.replace(/^(https?:\/\/\S+|\/v1\/files\/(?:image|video)\?id=\S+|data:image\/[^\s]+)$/gm, (match) => { + const url = match.trim(); + if (isImageUrl(url)) return `![image](${url})`; + if (isVideoUrl(url)) return ``; + return match; + }); + } + + function isNativeGrokMediaUrl(value) { + try { + const url = new URL(value, window.location.origin); + return /(^|\.)grok\.com$/i.test(url.hostname); + } catch { + return false; + } + } + + function showMediaProxyHint(media, type) { + if (!media || media.nextElementSibling?.classList?.contains('msg-media-error')) return; + const hint = document.createElement('div'); + hint.className = 'msg-media-error'; + if (type === 'image') { + hint.textContent = text( + 'webui.chat.errors.imageProxyRequired', + 'Image failed to load. Set APP Base URL and change image output format to local_url, local_md, or base64.' + ); + } else { + hint.textContent = text( + 'webui.chat.errors.videoProxyRequired', + 'Video loading returned 403. Go to the admin page, set the APP Base URL, then change the video output format to local proxy mode (local_url or local_html) and retry.' + ); + } + media.insertAdjacentElement('afterend', hint); + } + + function clearMediaProxyHint(media) { + const hint = media && media.nextElementSibling; + if (hint?.classList?.contains('msg-media-error')) hint.remove(); + } + + function enhanceMediaElements(card) { + card.querySelectorAll('video').forEach((video) => { + if (video.dataset.proxyHintBound === '1') return; + video.dataset.proxyHintBound = '1'; + const onVideoError = () => showMediaProxyHint(video, 'video'); + video.addEventListener('error', onVideoError); + video.querySelectorAll('source').forEach((source) => { + source.addEventListener('error', onVideoError); + }); + video.addEventListener('loadedmetadata', () => clearMediaProxyHint(video)); + if (video.error) showMediaProxyHint(video, 'video'); + }); + + card.querySelectorAll('img').forEach((img) => { + if (img.dataset.proxyHintBound === '1') return; + img.dataset.proxyHintBound = '1'; + img.addEventListener('error', () => { + if (isNativeGrokMediaUrl(img.currentSrc || img.src)) showMediaProxyHint(img, 'image'); + }); + img.addEventListener('load', () => clearMediaProxyHint(img)); + if (img.complete && img.naturalWidth === 0 && isNativeGrokMediaUrl(img.currentSrc || img.src)) { + showMediaProxyHint(img, 'image'); + } + }); + } + + function extractTextContent(content) { + if (typeof content === 'string') return content; + if (!Array.isArray(content)) return ''; + return content + .filter((block) => block && block.type === 'text' && typeof block.text === 'string' && block.text.trim()) + .map((block) => block.text.trim()) + .join('\n'); + } + + function extractImageUrls(content) { + if (!Array.isArray(content)) return []; + return content.flatMap((block) => { + if (!block || block.type !== 'image_url') return []; + const image = block.image_url; + if (typeof image === 'string' && image.trim()) return [image.trim()]; + if (image && typeof image.url === 'string' && image.url.trim()) return [image.url.trim()]; + return []; + }); + } + + function extractFileItems(content) { + if (!Array.isArray(content)) return []; + return content.flatMap((block) => { + if (!block || typeof block !== 'object') return []; + if (block.type === 'input_audio') { + const audio = block.input_audio || {}; + const filename = String(audio.filename || '').trim(); + return [{ kind: 'audio', name: filename || 'audio' }]; + } + if (block.type === 'file') { + const file = block.file || {}; + const filename = String(file.filename || '').trim(); + return [{ kind: 'file', name: filename || 'file' }]; + } + return []; + }); + } + + function dataUrlMime(value) { + const match = String(value || '').match(/^data:([^;,]+)[;,]/i); + return match ? match[1].toLowerCase() : 'application/octet-stream'; + } + + function fallbackNameForMime(mime) { + if (mime.startsWith('image/')) return `image.${mime.split('/')[1] || 'png'}`; + if (mime.startsWith('audio/')) return `audio.${mime.split('/')[1] || 'wav'}`; + return `file.${mime.split('/')[1] || 'bin'}`; + } + + function extractEditablePendingFiles(content) { + if (!Array.isArray(content)) return []; + return content.flatMap((block) => { + if (!block || typeof block !== 'object') return []; + if (block.type === 'image_url') { + const image = block.image_url; + const url = typeof image === 'string' ? image : image && typeof image.url === 'string' ? image.url : ''; + if (!url || !url.startsWith('data:')) return []; + const mime = dataUrlMime(url); + return [{ + name: fallbackNameForMime(mime), + type: mime, + size: 0, + dataUrl: url, + }]; + } + if (block.type === 'input_audio') { + const audio = block.input_audio || {}; + const data = String(audio.data || '').trim(); + if (!data) return []; + const mime = dataUrlMime(data); + return [{ + name: String(audio.filename || '').trim() || fallbackNameForMime(mime), + type: mime, + size: 0, + dataUrl: data, + }]; + } + if (block.type === 'file') { + const file = block.file || {}; + const data = String(file.file_data || '').trim(); + if (!data) return []; + const mime = dataUrlMime(data); + return [{ + name: String(file.filename || '').trim() || fallbackNameForMime(mime), + type: mime, + size: 0, + dataUrl: data, + }]; + } + return []; + }); + } + + async function copyToClipboard(value) { + const textValue = String(value || ''); + if (!textValue) return; + if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { + await navigator.clipboard.writeText(textValue); + return; + } + const textarea = document.createElement('textarea'); + textarea.value = textValue; + textarea.setAttribute('readonly', ''); + textarea.style.position = 'fixed'; + textarea.style.opacity = '0'; + document.body.appendChild(textarea); + textarea.select(); + document.execCommand('copy'); + textarea.remove(); + } + + function beginEditMessage(messageIndex, content) { + activeEdit = { + messageIndex, + text: extractTextContent(content) || (typeof content === 'string' ? content : ''), + files: extractEditablePendingFiles(content), + }; + renderThread(); + } + + function summarizeMessageContent(content) { + const textContent = extractTextContent(content).trim(); + const imageCount = extractImageUrls(content).length; + const fileCount = extractFileItems(content).length; + const parts = []; + if (textContent) parts.push(textContent); + if (imageCount) parts.push(`[${imageCount} image${imageCount > 1 ? 's' : ''}]`); + if (fileCount) parts.push(`[${fileCount} file${fileCount > 1 ? 's' : ''}]`); + return parts.join('\n\n'); + } + + function renderMessageContent(card, role, content) { + if (Array.isArray(content)) { + const textContent = extractTextContent(content); + const imageUrls = extractImageUrls(content); + const fileItems = extractFileItems(content); + if (role === 'assistant') { + const parts = []; + if (textContent.trim()) parts.push(renderRichMarkdown(textContent)); + if (imageUrls.length) { + parts.push(imageUrls.map((url) => ( + `
    image
    ` + )).join('')); + } + card.innerHTML = parts.join('') || '

    '; + enhanceMediaElements(card); + return; + } + + const body = document.createElement('div'); + body.className = 'msg-user-parts'; + if (textContent.trim()) { + const textNode = document.createElement('div'); + textNode.className = 'msg-user-text'; + textNode.textContent = textContent; + body.appendChild(textNode); + } + if (imageUrls.length) { + const gallery = document.createElement('div'); + gallery.className = 'msg-user-gallery'; + imageUrls.forEach((url) => { + const img = document.createElement('img'); + img.src = url; + img.alt = 'image'; + img.loading = 'lazy'; + gallery.appendChild(img); + }); + body.appendChild(gallery); + } + if (fileItems.length) { + const attachments = document.createElement('div'); + attachments.className = 'msg-user-files'; + fileItems.forEach((item) => { + const chip = document.createElement('div'); + chip.className = 'msg-user-file'; + chip.textContent = item.name; + attachments.appendChild(chip); + }); + body.appendChild(attachments); + } + card.replaceChildren(body); + return; + } + + if (role === 'assistant') { + card.innerHTML = renderRichMarkdown(content); + enhanceMediaElements(card); + return; + } + card.textContent = content; + } + + function renderAssistantWaiting(card) { + card.innerHTML = ''; + } + + function parseSseEvent(chunk) { + let event = 'message'; + const dataLines = []; + for (const line of chunk.split('\n')) { + if (line.startsWith('event:')) { + event = line.slice(6).trim() || 'message'; + continue; + } + if (line.startsWith('data:')) { + dataLines.push(line.slice(5).trimStart()); + } + } + return { event, data: dataLines.join('\n') }; + } + + function loadStore() { + try { + const raw = localStorage.getItem(STORE_KEY); + if (!raw) return { sessions: [], currentSessionId: '' }; + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) return { sessions: parsed, currentSessionId: parsed[0] && parsed[0].id || '' }; + return { + sessions: Array.isArray(parsed && parsed.sessions) ? parsed.sessions : [], + currentSessionId: parsed && parsed.currentSessionId ? String(parsed.currentSessionId) : '', + }; + } catch { + return { sessions: [], currentSessionId: '' }; + } + } + + function persistStore() { + const serializedSessions = sessions.map((session) => ({ + ...session, + messages: Array.isArray(session.messages) + ? session.messages.map((message) => ({ + ...message, + content: Array.isArray(message.content) + ? summarizeMessageContent(message.content) + : message.content, + })) + : [], + })); + localStorage.setItem(STORE_KEY, JSON.stringify({ sessions: serializedSessions, currentSessionId })); + } + + function applySidebarState() { + if (!chatLayout || !sidebarToggleBtn) return; + chatLayout.classList.toggle('sidebar-collapsed', sidebarCollapsed); + sidebarToggleBtn.setAttribute('aria-expanded', String(!sidebarCollapsed)); + } + + function loadSidebarState() { + try { + sidebarCollapsed = localStorage.getItem(SIDEBAR_STORE_KEY) === 'true'; + } catch { + sidebarCollapsed = false; + } + applySidebarState(); + } + + function toggleSidebar() { + sidebarCollapsed = !sidebarCollapsed; + applySidebarState(); + try { + localStorage.setItem(SIDEBAR_STORE_KEY, String(sidebarCollapsed)); + } catch {} + } + + function createSessionTitle(messagesList) { + const firstUser = messagesList.find((item) => { + if (!item || item.role !== 'user') return false; + return Boolean(extractTextContent(item.content).trim()); + }); + if (!firstUser) return text('webui.chat.untitled', 'New Chat'); + const trimmed = extractTextContent(firstUser.content).trim().replace(/\s+/g, ' '); + return trimmed.length > 24 ? `${trimmed.slice(0, 24)}...` : trimmed; + } + + function createSession() { + return { + id: `chat_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, + title: text('webui.chat.untitled', 'New Chat'), + titleLocked: false, + model: modelSelect.value || PREFERRED_MODEL, + system: '', + messages: [], + updatedAt: Date.now(), + }; + } + + function normalizeSession(item) { + return { + id: item && item.id ? String(item.id) : `chat_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, + title: item && item.title ? String(item.title) : text('webui.chat.untitled', 'New Chat'), + titleLocked: Boolean(item && item.titleLocked), + model: item && item.model ? String(item.model) : PREFERRED_MODEL, + system: item && item.system ? String(item.system) : '', + messages: Array.isArray(item && item.messages) + ? item.messages + .filter((entry) => { + if (!entry || typeof entry.role !== 'string') return false; + if (!['user', 'assistant', 'error'].includes(entry.role)) return false; + return typeof entry.content === 'string' || Array.isArray(entry.content); + }) + .map((entry) => ({ + ...entry, + reasoning_content: entry && entry.role === 'assistant' && hasVisibleReasoning(entry.reasoning_content) + ? entry.reasoning_content + : '', + createdAt: Number(entry && entry.createdAt) || Date.now(), + feedback: entry && typeof entry.feedback === 'string' ? entry.feedback : '', + })) + : [], + updatedAt: Number(item && item.updatedAt) || Date.now(), + }; + } + + function setAssistantFeedback(messageIndex, feedback) { + const session = getCurrentSession(); + const message = session && session.messages && session.messages[messageIndex]; + if (!session || !message || message.role !== 'assistant') return; + message.feedback = message.feedback === feedback ? '' : feedback; + session.updatedAt = Date.now(); + persistStore(); + renderThread(); + } + + function regenerateAssistantAt(messageIndex) { + const session = getCurrentSession(); + if (!session || sending || messageIndex < 0) return; + + let userIndex = -1; + for (let index = messageIndex - 1; index >= 0; index -= 1) { + if (messages[index] && messages[index].role === 'user') { + userIndex = index; + break; + } + } + if (userIndex < 0) return; + + const userContent = messages[userIndex].content; + promptInput.value = extractTextContent(userContent) || (typeof userContent === 'string' ? userContent : ''); + pendingFiles = extractEditablePendingFiles(userContent); + messages = messages.slice(0, userIndex); + session.messages = messages; + session.updatedAt = Date.now(); + activeEdit = null; + renderUploadMeta(); + renderSessionList(); + renderThread(); + resizePromptInput(); + void sendMessage(); + } + + function getCurrentSession() { + return sessions.find((item) => item.id === currentSessionId) || null; + } + + function moveSessionToTop(session) { + sessions = [session, ...sessions.filter((item) => item.id !== session.id)]; + } + + async function getAuthHeaders() { + const key = await webuiKey.get(); + return key ? { Authorization: `Bearer ${key}` } : {}; + } + + async function ensureAccess() { + const stored = await webuiKey.get(); + if (stored && await verifyKey(VERIFY_ENDPOINT, stored)) return true; + if (stored) webuiKey.clear(); + if (await verifyKey(VERIFY_ENDPOINT, '')) return true; + location.href = '/webui/login'; + return false; + } + + function setStatus(textValue) { + if (statusEl) statusEl.textContent = textValue; + } + + function resizePromptInput() { + if (!promptInput) return; + promptInput.style.height = `${PROMPT_MIN_HEIGHT}px`; + const nextHeight = Math.min(Math.max(promptInput.scrollHeight, PROMPT_MIN_HEIGHT), PROMPT_MAX_HEIGHT); + promptInput.style.height = `${nextHeight}px`; + promptInput.style.overflowY = promptInput.scrollHeight > PROMPT_MAX_HEIGHT ? 'auto' : 'hidden'; + } + + function renderSendButton() { + if (!sendBtn) return; + const label = sending + ? text('webui.chat.stop', 'Stop') + : text('webui.chat.send', 'Send'); + sendBtn.removeAttribute('data-i18n'); + sendBtn.setAttribute('aria-label', label); + sendBtn.setAttribute('title', label); + sendBtn.innerHTML = sending + ? '' + : ''; + } + + function setSending(next) { + sending = next; + promptInput.disabled = next; + modelSelect.disabled = next; + if (systemInput) systemInput.disabled = next; + renderSendButton(); + } + + function scrollThread() { + if (pendingThreadScrollFrame) return; + pendingThreadScrollFrame = window.requestAnimationFrame(() => { + pendingThreadScrollFrame = 0; + thread.scrollTop = thread.scrollHeight; + }); + } + + function hideEmpty() { + if (emptyState) emptyState.style.display = 'none'; + } + + function showEmpty() { + if (emptyState) emptyState.style.display = ''; + } + + function renderUploadMeta() { + if (!uploadMeta) return; + if (!pendingFiles.length) { + uploadMeta.hidden = true; + uploadMeta.replaceChildren(); + return; + } + + const row = document.createElement('div'); + row.className = 'webui-upload-meta-row'; + + pendingFiles.forEach((file, index) => { + const chip = document.createElement('div'); + chip.className = 'webui-upload-meta-chip'; + chip.title = file.name || 'file'; + const chars = Array.from(String(file.name || 'file')); + + const label = document.createElement('span'); + label.className = 'webui-upload-meta-chip-label'; + label.textContent = chars.length > 5 ? `${chars.slice(0, 5).join('')}...` : (file.name || 'file'); + chip.appendChild(label); + + const removeBtn = document.createElement('button'); + removeBtn.type = 'button'; + removeBtn.className = 'webui-upload-meta-chip-remove'; + removeBtn.setAttribute('aria-label', `删除 ${file.name || 'file'}`); + removeBtn.setAttribute('title', `删除 ${file.name || 'file'}`); + removeBtn.innerHTML = ''; + removeBtn.addEventListener('click', () => { + pendingFiles = pendingFiles.filter((_, itemIndex) => itemIndex !== index); + if (fileInput && !pendingFiles.length) fileInput.value = ''; + renderUploadMeta(); + }); + chip.appendChild(removeBtn); + + row.appendChild(chip); + }); + + uploadMeta.hidden = false; + uploadMeta.replaceChildren(row); + } + + function currentModelCapability() { + const selected = modelSelect && modelSelect.value + ? availableModels.find((item) => item && item.id === modelSelect.value) + : null; + return selected && selected.capability ? selected.capability : 'chat'; + } + + async function fileToDataUrl(file) { + return await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result || '')); + reader.onerror = () => reject(reader.error || new Error('file read failed')); + reader.readAsDataURL(file); + }); + } + + async function preparePendingFiles(fileList) { + const files = Array.from(fileList || []); + const prepared = []; + + for (const file of files) { + if (!file) continue; + prepared.push({ + name: file.name || 'file', + type: file.type || 'application/octet-stream', + size: Number(file.size) || 0, + dataUrl: await fileToDataUrl(file), + }); + } + + return prepared; + } + + function buildUserMessage(prompt, capability) { + const textBlock = prompt ? [{ type: 'text', text: prompt }] : []; + const imageFiles = pendingFiles.filter((file) => (file.type || '').startsWith('image/')); + const audioFiles = pendingFiles.filter((file) => (file.type || '').startsWith('audio/')); + const otherFiles = pendingFiles.filter((file) => { + const mime = file.type || ''; + return !mime.startsWith('image/') && !mime.startsWith('audio/'); + }); + + const imageBlocks = imageFiles.map((file) => ({ + type: 'image_url', + image_url: { url: file.dataUrl }, + })); + const audioBlocks = audioFiles.map((file) => ({ + type: 'input_audio', + input_audio: { + data: file.dataUrl, + filename: file.name, + }, + })); + const fileBlocks = otherFiles.map((file) => ({ + type: 'file', + file: { + file_data: file.dataUrl, + filename: file.name, + }, + })); + + if (capability === 'image') { + if (pendingFiles.length) { + throw new Error(text( + 'webui.chat.errors.imageUploadsNotSupported', + 'Image generation does not accept uploaded references here. Use chat, image edit, or video with a reference image.', + )); + } + return { role: 'user', content: prompt }; + } + if (capability === 'image_edit') { + if (!imageBlocks.length) { + throw new Error(text('webui.chat.errors.imageRequired', 'Image edit requires at least one reference image')); + } + if (audioBlocks.length || fileBlocks.length) { + throw new Error(text('webui.chat.errors.imageOnly', 'Image edit only supports image uploads')); + } + return { role: 'user', content: [...textBlock, ...imageBlocks] }; + } + if (capability === 'video') { + if (audioBlocks.length || fileBlocks.length) { + throw new Error(text('webui.chat.errors.videoImageOnly', 'Video generation only supports image reference uploads')); + } + return imageBlocks.length + ? { role: 'user', content: [...textBlock, imageBlocks[0]] } + : { role: 'user', content: prompt }; + } + if (imageBlocks.length || audioBlocks.length || fileBlocks.length) { + return { role: 'user', content: [...textBlock, ...imageBlocks, ...audioBlocks, ...fileBlocks] }; + } + return { role: 'user', content: prompt }; + } + + function closeSessionModal(result) { + if (!sessionModal) return; + sessionModal.classList.remove('open'); + sessionModal.setAttribute('aria-hidden', 'true'); + const resolver = modalResolver; + modalResolver = null; + if (resolver) resolver(result); + } + + function openSessionModal({ title, description = '', confirmLabel, cancelLabel, inputValue = '', withInput = false }) { + if (!sessionModal) return Promise.resolve(null); + sessionModalTitle.textContent = title; + sessionModalDesc.textContent = description; + sessionModalInputWrap.hidden = !withInput; + sessionModalInput.value = withInput ? inputValue : ''; + sessionModalCancel.textContent = cancelLabel || text('webui.chat.cancel', 'Cancel'); + sessionModalConfirm.textContent = confirmLabel || text('webui.chat.confirm', 'Confirm'); + sessionModal.classList.add('open'); + sessionModal.setAttribute('aria-hidden', 'false'); + if (withInput) { + setTimeout(() => { + sessionModalInput.focus(); + sessionModalInput.select(); + }, 0); + } + return new Promise((resolve) => { + modalResolver = resolve; + }); + } + + function editMessageAt(messageIndex, content) { + const session = getCurrentSession(); + if (!session || messageIndex < 0) return; + if (sending) stopMessage(); + + promptInput.value = activeEdit ? activeEdit.text : (extractTextContent(content) || (typeof content === 'string' ? content : '')); + pendingFiles = activeEdit ? activeEdit.files.slice() : extractEditablePendingFiles(content); + messages = messages.slice(0, messageIndex); + session.messages = messages; + session.model = modelSelect.value || PREFERRED_MODEL; + session.system = currentSystemPrompt(); + if (!session.titleLocked) session.title = createSessionTitle(session.messages); + session.updatedAt = Date.now(); + activeEdit = null; + moveSessionToTop(session); + renderUploadMeta(); + renderSessionList(); + renderThread(); + resizePromptInput(); + setStatus(text('webui.chat.statusReady', 'Ready')); + persistStore(); + promptInput.focus(); + } + + function createMessage(role, initialText = '', initialReasoning = '', messageIndex = -1) { + hideEmpty(); + const hasReasoning = role === 'assistant' && hasVisibleReasoning(initialReasoning); + const isAssistantWaiting = role === 'assistant' && messageIndex < 0 && !hasReasoning && !hasMessageContent(initialText); + + const wrap = document.createElement('div'); + wrap.className = `msg ${role}`; + + const reasoning = document.createElement('div'); + reasoning.className = 'msg-reasoning'; + reasoning.hidden = !hasReasoning; + + const reasoningToggle = document.createElement('button'); + reasoningToggle.type = 'button'; + reasoningToggle.className = 'msg-reasoning-toggle'; + reasoningToggle.setAttribute('aria-expanded', 'true'); + reasoningToggle.innerHTML = `${escapeHtml(text('webui.chat.reasoning', 'Reasoning'))}`; + + const reasoningBody = document.createElement('div'); + reasoningBody.className = 'msg-reasoning-body'; + reasoningBody.textContent = hasReasoning ? initialReasoning : ''; + + reasoningToggle.addEventListener('click', () => { + const collapsed = reasoning.classList.toggle('is-collapsed'); + reasoningToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true'); + }); + + reasoning.appendChild(reasoningToggle); + reasoning.appendChild(reasoningBody); + + const card = document.createElement('div'); + card.className = `msg-card msg-card-${role}`; + const isEditing = role === 'user' && activeEdit && activeEdit.messageIndex === messageIndex; + if (isEditing) { + card.classList.add('msg-card-editing'); + + const editor = document.createElement('textarea'); + editor.className = 'msg-edit-textarea'; + editor.value = activeEdit.text; + editor.placeholder = text('webui.chat.editPlaceholder', 'Edit message'); + editor.addEventListener('input', () => { + if (!activeEdit || activeEdit.messageIndex !== messageIndex) return; + activeEdit.text = editor.value; + editor.style.height = 'auto'; + editor.style.height = `${Math.max(editor.scrollHeight, 52)}px`; + }); + editor.style.height = 'auto'; + editor.style.height = `${Math.max(editor.scrollHeight, 52)}px`; + + const footer = document.createElement('div'); + footer.className = 'msg-edit-footer'; + + const cancelBtn = document.createElement('button'); + cancelBtn.type = 'button'; + cancelBtn.className = 'msg-edit-cancel'; + cancelBtn.textContent = text('webui.chat.cancel', 'Cancel'); + cancelBtn.addEventListener('click', () => { + activeEdit = null; + renderThread(); + }); + + const saveBtn = document.createElement('button'); + saveBtn.type = 'button'; + saveBtn.className = 'msg-edit-save'; + saveBtn.textContent = text('webui.chat.save', 'Save'); + saveBtn.addEventListener('click', () => { + editMessageAt(messageIndex, initialText); + }); + + footer.appendChild(cancelBtn); + footer.appendChild(saveBtn); + card.appendChild(editor); + card.appendChild(footer); + + setTimeout(() => { + editor.focus(); + editor.setSelectionRange(editor.value.length, editor.value.length); + }, 0); + } else if (isAssistantWaiting) { + renderAssistantWaiting(card); + } else { + renderMessageContent(card, role, initialText); + } + + const entry = { + wrap, + reasoning, + reasoningBody, + card, + text: initialText, + reasoningText: initialReasoning, + waiting: isAssistantWaiting, + messageIndex, + actions: null, + likeBtn: null, + dislikeBtn: null, + renderFrame: 0, + }; + + if (role === 'assistant') { + wrap.appendChild(reasoning); + } + wrap.appendChild(card); + + if (role === 'user') { + const actions = document.createElement('div'); + actions.className = 'msg-actions'; + + const editBtn = document.createElement('button'); + editBtn.type = 'button'; + editBtn.className = 'msg-action-btn'; + editBtn.setAttribute('aria-label', text('webui.chat.edit', 'Edit')); + editBtn.setAttribute('title', text('webui.chat.edit', 'Edit')); + editBtn.innerHTML = ''; + editBtn.addEventListener('click', () => { + beginEditMessage(messageIndex, initialText); + }); + + const copyBtn = document.createElement('button'); + copyBtn.type = 'button'; + copyBtn.className = 'msg-action-btn'; + copyBtn.setAttribute('aria-label', text('webui.chat.copy', 'Copy')); + copyBtn.setAttribute('title', text('webui.chat.copy', 'Copy')); + copyBtn.innerHTML = ''; + copyBtn.addEventListener('click', async () => { + try { + await copyToClipboard(extractTextContent(initialText) || (typeof initialText === 'string' ? initialText : '')); + toast(text('webui.chat.copySuccess', 'Copied'), 'info'); + } catch (error) { + toast(error.message || String(error), 'error'); + } + }); + + if (!isEditing) { + actions.appendChild(editBtn); + actions.appendChild(copyBtn); + wrap.appendChild(actions); + } + } + + if (role === 'assistant') { + const actions = document.createElement('div'); + actions.className = 'msg-actions msg-actions-assistant'; + actions.hidden = messageIndex < 0; + const message = messageIndex >= 0 ? messages[messageIndex] : null; + + const right = document.createElement('div'); + right.className = 'msg-action-group'; + + const regenBtn = document.createElement('button'); + regenBtn.type = 'button'; + regenBtn.className = 'msg-action-btn msg-action-btn-regen'; + regenBtn.setAttribute('aria-label', text('webui.chat.regenerate', 'Regenerate')); + regenBtn.setAttribute('title', text('webui.chat.regenerate', 'Regenerate')); + regenBtn.innerHTML = ''; + regenBtn.addEventListener('click', () => { + regenerateAssistantAt(entry.messageIndex); + }); + + const copyBtn = document.createElement('button'); + copyBtn.type = 'button'; + copyBtn.className = 'msg-action-btn'; + copyBtn.setAttribute('aria-label', text('webui.chat.copy', 'Copy')); + copyBtn.setAttribute('title', text('webui.chat.copy', 'Copy')); + copyBtn.innerHTML = ''; + copyBtn.addEventListener('click', async () => { + try { + await copyToClipboard(typeof entry.text === 'string' ? entry.text : extractTextContent(entry.text)); + toast(text('webui.chat.copySuccess', 'Copied'), 'info'); + } catch (error) { + toast(error.message || String(error), 'error'); + } + }); + + const likeBtn = document.createElement('button'); + likeBtn.type = 'button'; + likeBtn.className = `msg-action-btn${message && message.feedback === 'up' ? ' active' : ''}`; + likeBtn.setAttribute('aria-label', text('webui.chat.like', 'Like')); + likeBtn.setAttribute('title', text('webui.chat.like', 'Like')); + likeBtn.innerHTML = ''; + likeBtn.addEventListener('click', () => { + setAssistantFeedback(entry.messageIndex, 'up'); + }); + + const dislikeBtn = document.createElement('button'); + dislikeBtn.type = 'button'; + dislikeBtn.className = `msg-action-btn${message && message.feedback === 'down' ? ' active' : ''}`; + dislikeBtn.setAttribute('aria-label', text('webui.chat.dislike', 'Dislike')); + dislikeBtn.setAttribute('title', text('webui.chat.dislike', 'Dislike')); + dislikeBtn.innerHTML = ''; + dislikeBtn.addEventListener('click', () => { + setAssistantFeedback(entry.messageIndex, 'down'); + }); + + right.appendChild(regenBtn); + right.appendChild(copyBtn); + right.appendChild(likeBtn); + right.appendChild(dislikeBtn); + actions.appendChild(right); + wrap.appendChild(actions); + entry.actions = actions; + entry.likeBtn = likeBtn; + entry.dislikeBtn = dislikeBtn; + } + + thread.appendChild(wrap); + + syncAssistantActions(entry); + return entry; + } + + function syncAssistantActions(entry) { + if (!entry || !entry.actions) return; + entry.actions.hidden = entry.messageIndex < 0; + const message = entry.messageIndex >= 0 ? messages[entry.messageIndex] : null; + if (entry.likeBtn) entry.likeBtn.classList.toggle('active', Boolean(message && message.feedback === 'up')); + if (entry.dislikeBtn) entry.dislikeBtn.classList.toggle('active', Boolean(message && message.feedback === 'down')); + } + + function renderAssistantEntry(entry) { + if (!entry) return; + entry.renderFrame = 0; + if (entry.waiting) return; + if (hasMessageContent(entry.text)) { + renderMessageContent(entry.card, 'assistant', entry.text); + } else { + entry.card.innerHTML = ''; + } + const hasReasoning = hasVisibleReasoning(entry.reasoningText); + entry.reasoning.hidden = !hasReasoning; + entry.reasoningBody.textContent = hasReasoning ? entry.reasoningText : ''; + } + + function scheduleAssistantEntryRender(entry) { + if (!entry) return; + if (!entry.renderFrame) { + entry.renderFrame = window.requestAnimationFrame(() => { + renderAssistantEntry(entry); + scrollThread(); + }); + } else { + scrollThread(); + } + } + + function flushAssistantEntry(entry) { + if (!entry) return; + if (entry.renderFrame) { + window.cancelAnimationFrame(entry.renderFrame); + entry.renderFrame = 0; + } + renderAssistantEntry(entry); + } + + function finalizeAssistantEntry(entry, messageIndex) { + if (!entry) return; + entry.waiting = false; + flushAssistantEntry(entry); + entry.messageIndex = messageIndex; + syncAssistantActions(entry); + scrollThread(); + } + + function updateAssistant(entry, delta) { + if (entry.waiting) entry.waiting = false; + entry.text += delta; + scheduleAssistantEntryRender(entry); + } + + function updateReasoning(entry, delta) { + if (entry.waiting) entry.waiting = false; + entry.reasoningText += delta; + scheduleAssistantEntryRender(entry); + } + + function renderThread() { + thread.innerHTML = ''; + if (emptyState) thread.appendChild(emptyState); + if (!messages.length) { + showEmpty(); + return; + } + hideEmpty(); + messages.forEach((message, index) => { + createMessage( + message.role, + message.content, + message.role === 'assistant' ? (message.reasoning_content || '') : '', + index, + ); + }); + scrollThread(); + } + + function renderSessionList() { + if (!sessionList) return; + sessionList.dataset.empty = text('webui.chat.noSessions', 'No chats yet'); + const nextSignature = `${currentSessionId}|${sessions.map((session) => `${session.id}:${session.title || ''}`).join('|')}`; + if (nextSignature === sessionListRenderSignature) return; + sessionListRenderSignature = nextSignature; + const fragment = document.createDocumentFragment(); + + sessions.forEach((session) => { + const item = document.createElement('button'); + item.type = 'button'; + item.className = `webui-session-item${session.id === currentSessionId ? ' active' : ''}`; + + const title = document.createElement('div'); + title.className = 'webui-session-title'; + title.textContent = session.title || text('webui.chat.untitled', 'New Chat'); + const actions = document.createElement('div'); + actions.className = 'webui-session-actions'; + + const renameBtn = document.createElement('button'); + renameBtn.type = 'button'; + renameBtn.className = 'webui-session-action'; + renameBtn.title = text('webui.chat.rename', 'Rename'); + renameBtn.innerHTML = ''; + renameBtn.addEventListener('click', (event) => { + event.stopPropagation(); + renameSession(session.id); + }); + + const deleteBtn = document.createElement('button'); + deleteBtn.type = 'button'; + deleteBtn.className = 'webui-session-action'; + deleteBtn.title = text('webui.chat.delete', 'Delete'); + deleteBtn.innerHTML = ''; + deleteBtn.addEventListener('click', (event) => { + event.stopPropagation(); + deleteSession(session.id); + }); + + actions.appendChild(renameBtn); + actions.appendChild(deleteBtn); + + item.appendChild(title); + item.appendChild(actions); + item.addEventListener('click', () => switchSession(session.id)); + fragment.appendChild(item); + }); + sessionList.replaceChildren(fragment); + } + + function syncCurrentSession() { + const session = getCurrentSession(); + if (!session) return; + session.model = modelSelect.value || PREFERRED_MODEL; + session.system = currentSystemPrompt(); + if (!session.titleLocked) session.title = createSessionTitle(session.messages); + session.updatedAt = Date.now(); + moveSessionToTop(session); + persistStore(); + renderSessionList(); + } + + function switchSession(id) { + const session = sessions.find((item) => item.id === id); + if (!session) return; + currentSessionId = session.id; + messages = session.messages; + pendingFiles = []; + activeEdit = null; + if (modelSelect.options.length) { + modelSelect.value = Array.from(modelSelect.options).some((option) => option.value === session.model) + ? session.model + : (modelSelect.value || PREFERRED_MODEL); + } + renderUploadMeta(); + renderSessionList(); + renderThread(); + resizePromptInput(); + setStatus(text('webui.chat.statusReady', 'Ready')); + persistStore(); + } + + function startNewSession() { + const session = createSession(); + sessions.unshift(session); + currentSessionId = session.id; + messages = session.messages; + pendingFiles = []; + activeEdit = null; + renderUploadMeta(); + renderSessionList(); + renderThread(); + resizePromptInput(); + setStatus(text('webui.chat.statusReady', 'Ready')); + persistStore(); + promptInput.focus(); + } + + function renameSession(id) { + const session = sessions.find((item) => item.id === id); + if (!session) return; + openSessionModal({ + title: text('webui.chat.rename', 'Rename'), + description: text('webui.chat.renamePrompt', 'Rename session'), + confirmLabel: text('webui.chat.confirm', 'Confirm'), + cancelLabel: text('webui.chat.cancel', 'Cancel'), + inputValue: session.title || text('webui.chat.untitled', 'New Chat'), + withInput: true, + }).then((nextTitle) => { + if (typeof nextTitle !== 'string') return; + const trimmed = nextTitle.trim(); + if (!trimmed) return; + session.title = trimmed; + session.titleLocked = true; + session.updatedAt = Date.now(); + moveSessionToTop(session); + persistStore(); + renderSessionList(); + }); + } + + function deleteSession(id) { + const session = sessions.find((item) => item.id === id); + if (!session) return; + openSessionModal({ + title: text('webui.chat.delete', 'Delete'), + description: text('webui.chat.deleteConfirm', 'Delete this session?'), + confirmLabel: text('webui.chat.delete', 'Delete'), + cancelLabel: text('webui.chat.cancel', 'Cancel'), + }).then((confirmed) => { + if (!confirmed) return; + sessions = sessions.filter((item) => item.id !== id); + if (!sessions.length) { + startNewSession(); + return; + } + + const next = sessions[0]; + currentSessionId = next.id; + persistStore(); + switchSession(next.id); + }); + } + + function buildPayload() { + const outgoing = []; + const system = currentSystemPrompt(); + if (system) outgoing.push({ role: 'system', content: system }); + messages + .filter((message) => message && (message.role === 'user' || message.role === 'assistant')) + .forEach((message) => outgoing.push(message)); + return { + model: modelSelect.value || PREFERRED_MODEL, + messages: outgoing, + stream: true, + temperature: 0.8, + top_p: 0.95, + }; + } + + async function loadModels() { + const headers = await getAuthHeaders(); + const res = await fetch(MODELS_ENDPOINT, { headers, cache: 'no-store' }); + if (!res.ok) throw new Error(`models ${res.status}`); + + const data = await res.json(); + const items = Array.isArray(data && data.data) ? data.data : []; + availableModels = items.filter((item) => item && item.id); + const ids = items.map((item) => item && item.id).filter(Boolean); + + modelSelect.innerHTML = ''; + availableModels.forEach((item) => { + const opt = document.createElement('option'); + opt.value = item.id; + opt.textContent = formatModelOptionLabel(item.id, item.name || item.id); + modelSelect.appendChild(opt); + }); + modelSelect.value = ids.includes(PREFERRED_MODEL) ? PREFERRED_MODEL : (ids[0] || PREFERRED_MODEL); + } + + async function sendMessage() { + if (sending) return; + + const prompt = (promptInput.value || '').trim(); + const capability = currentModelCapability(); + if (!prompt) { + toast(text('webui.chat.errors.enterPrompt', 'Please enter a message'), 'error'); + return; + } + + const session = getCurrentSession(); + if (!session) return; + activeEdit = null; + + let userMessage; + try { + userMessage = buildUserMessage(prompt, capability); + } catch (error) { + toast(error.message || String(error), 'error'); + return; + } + + session.model = modelSelect.value || PREFERRED_MODEL; + session.system = currentSystemPrompt(); + messages.push(userMessage); + if (!session.titleLocked) session.title = createSessionTitle(messages); + session.updatedAt = Date.now(); + moveSessionToTop(session); + persistStore(); + renderSessionList(); + + messages[messages.length - 1].createdAt = Date.now(); + messages[messages.length - 1].feedback = ''; + const userEntry = createMessage('user', userMessage.content, '', messages.length - 1); + void userEntry; + const assistantCreatedAt = Date.now(); + const assistantEntry = createMessage('assistant', '', '', -1); + + promptInput.value = ''; + pendingFiles = []; + if (fileInput) fileInput.value = ''; + renderUploadMeta(); + resizePromptInput(); + abortController = new AbortController(); + setSending(true); + setStatus(text('webui.chat.statusConnecting', 'Connecting...')); + + try { + const headers = { + 'Content-Type': 'application/json', + ...(await getAuthHeaders()), + }; + const res = await fetch(CHAT_ENDPOINT, { + method: 'POST', + headers, + body: JSON.stringify(buildPayload()), + signal: abortController.signal, + }); + if (!res.ok) { + const detail = await res.text().catch(() => ''); + throw new Error(detail || `HTTP ${res.status}`); + } + + const reader = res.body.getReader(); + const decoder = new TextDecoder('utf-8'); + let buffer = ''; + + function handleStreamChunk(chunk) { + const messageEvent = parseSseEvent(chunk); + const payload = messageEvent.data.trim(); + if (!payload) return false; + if (payload === '[DONE]') { + const finalReasoning = hasVisibleReasoning(assistantEntry.reasoningText) ? assistantEntry.reasoningText : ''; + messages.push({ + role: 'assistant', + content: assistantEntry.text, + reasoning_content: finalReasoning, + createdAt: assistantCreatedAt, + feedback: '', + }); + syncCurrentSession(); + finalizeAssistantEntry(assistantEntry, messages.length - 1); + setStatus(text('webui.chat.statusDone', 'Completed')); + return true; + } + + let json; + try { + json = JSON.parse(payload); + } catch { + return false; + } + + if (messageEvent.event === 'error' || json.error) { + const errorMessage = json.error && json.error.message + ? json.error.message + : text('webui.chat.errors.requestFailed', 'Request failed'); + throw new Error(errorMessage); + } + + const choice = json && json.choices && json.choices[0]; + const delta = choice && choice.delta ? choice.delta : {}; + if (typeof delta.reasoning_content === 'string') { + updateReasoning(assistantEntry, delta.reasoning_content); + if (hasVisibleReasoning(assistantEntry.reasoningText)) { + setStatus(text('webui.chat.statusThinking', 'Thinking...')); + } + } + if (delta.content) { + updateAssistant(assistantEntry, delta.content); + setStatus(text('webui.chat.statusGenerating', 'Generating...')); + } + return false; + } + + while (true) { + const { value, done } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n'); + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() || ''; + + for (const chunk of chunks) { + if (handleStreamChunk(chunk)) return; + } + } + + if (buffer.trim() && handleStreamChunk(buffer)) return; + + const finalReasoning = hasVisibleReasoning(assistantEntry.reasoningText) ? assistantEntry.reasoningText : ''; + messages.push({ + role: 'assistant', + content: assistantEntry.text, + reasoning_content: finalReasoning, + createdAt: assistantCreatedAt, + feedback: '', + }); + syncCurrentSession(); + finalizeAssistantEntry(assistantEntry, messages.length - 1); + setStatus(text('webui.chat.statusDone', 'Completed')); + } catch (error) { + if (error && error.name === 'AbortError') { + setStatus(text('webui.chat.statusStopped', 'Stopped')); + } else { + messages.push({ + role: 'error', + content: `${text('webui.chat.errors.requestFailed', 'Request failed')}: ${error.message || error}`, + createdAt: Date.now(), + feedback: '', + }); + syncCurrentSession(); + renderThread(); + toast(text('webui.chat.errors.requestFailed', 'Request failed'), 'error'); + setStatus(text('webui.chat.statusFailed', 'Failed')); + } + } finally { + abortController = null; + setSending(false); + scrollThread(); + } + } + + function stopMessage() { + if (abortController) abortController.abort(); + } + + function restoreSessions() { + const stored = loadStore(); + sessions = stored.sessions.map(normalizeSession); + currentSessionId = stored.currentSessionId; + + if (!sessions.length) { + startNewSession(); + return; + } + + const existing = sessions.find((item) => item.id === currentSessionId) || sessions[0]; + switchSession(existing.id); + } + + async function boot() { + await renderWebuiHeader?.(); + await renderSiteFooter?.(); + if (window.I18n?.apply) I18n.apply(document); + renderSendButton(); + window.I18n?.onReady?.(renderSendButton); + if (!await ensureAccess()) return; + loadSidebarState(); + await loadModels(); + restoreSessions(); + resizePromptInput(); + promptInput.focus(); + } + + newChatBtn?.addEventListener('click', startNewSession); + sidebarToggleBtn.addEventListener('click', toggleSidebar); + sendBtn.addEventListener('click', () => { + if (sending) { + stopMessage(); + return; + } + sendMessage(); + }); + modelSelect.addEventListener('change', syncCurrentSession); + systemInput?.addEventListener('change', syncCurrentSession); + uploadBtn.addEventListener('click', () => fileInput.click()); + fileInput.addEventListener('change', async () => { + try { + pendingFiles = await preparePendingFiles(fileInput.files || []); + renderUploadMeta(); + } catch (error) { + pendingFiles = []; + if (fileInput) fileInput.value = ''; + renderUploadMeta(); + toast(error.message || String(error), 'error'); + } + }); + sessionModalCancel.addEventListener('click', () => closeSessionModal(false)); + sessionModalConfirm.addEventListener('click', () => { + const result = sessionModalInputWrap.hidden ? true : sessionModalInput.value; + closeSessionModal(result); + }); + sessionModal.addEventListener('click', (event) => { + if (event.target === sessionModal) closeSessionModal(false); + }); + sessionModalInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + event.preventDefault(); + closeSessionModal(sessionModalInput.value); + } + }); + promptInput.addEventListener('input', resizePromptInput); + promptInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault(); + sendMessage(); + } + }); + + boot().catch((error) => { + console.error('webui chat boot failed', error); + toast(text('webui.chat.errors.initFailed', 'Chat page initialization failed'), 'error'); + setStatus(text('webui.chat.statusInitFailed', 'Initialization failed')); + }); +})(); diff --git a/app/statics/js/webui/chatkit.js b/app/statics/js/webui/chatkit.js new file mode 100644 index 0000000000000000000000000000000000000000..0136826d1862b28a885d34364e405ea261d595c6 --- /dev/null +++ b/app/statics/js/webui/chatkit.js @@ -0,0 +1,501 @@ +(() => { + const VOICE_ENDPOINT = '/webui/api/voice/token'; + const voiceSelect = document.getElementById('voiceSelect'); + const personalitySelect = document.getElementById('personalitySelect'); + const speedSelect = document.getElementById('speedSelect'); + const instructionInput = document.getElementById('instructionInput'); + const startVoiceBtn = document.getElementById('startVoiceBtn'); + const muteVoiceBtn = document.getElementById('muteVoiceBtn'); + const newSessionBtn = document.getElementById('newSessionBtn'); + const connectionBadge = document.getElementById('connectionBadge'); + const connectionText = document.getElementById('connectionText'); + const voiceOrb = document.getElementById('voiceOrb'); + const audioRoot = document.getElementById('audioRoot'); + + let room = null; + let micEnabled = true; + let outputMuted = false; + let orbAudioContext = null; + const orbInputs = new Map(); + let orbFrame = 0; + let orbLevel = 0; + let orbBeat = 0; + let orbMotionPhase = 0; + const audioElements = new Set(); + let lastStatusState = ''; + let lastStatusLabel = ''; + let lastStatusDescription = ''; + + const controlIcon = { + start: '', + pause: '', + mute: '', + unmute: '', + newSession: '', + }; + + const text = (key, fallback) => { + if (typeof window.t !== 'function') return fallback; + const value = t(key); + return value === key ? fallback : value; + }; + + const setOrbLevel = (level) => { + orbLevel = Math.max(0, Math.min(1, level || 0)); + if (!voiceOrb) return; + voiceOrb.style.setProperty('--chatkit-level', orbLevel.toFixed(3)); + voiceOrb.classList.toggle('is-speaking', voiceOrb.classList.contains('is-live') && orbLevel > 0.045); + }; + + const setOrbBeat = (value) => { + orbBeat = Math.max(0, Math.min(1, value || 0)); + if (!voiceOrb) return; + voiceOrb.style.setProperty('--chatkit-beat', orbBeat.toFixed(3)); + }; + + const setOrbMotion = (level) => { + if (!voiceOrb) return; + const intensity = Math.max(0, Math.min(1, level || 0)); + const activeIntensity = intensity > 0.03 ? Math.max(intensity, 0.18) : 0; + const distance = activeIntensity * 11; + orbMotionPhase += 0.14 + activeIntensity * 0.18; + const drift = (speed, amplitude, offset = 0) => Math.sin(orbMotionPhase * speed + offset) * amplitude * distance; + + voiceOrb.style.setProperty('--chatkit-drift-a-x', `${drift(0.92, 0.95, 0.2).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-a-y', `${drift(1.08, 0.9, 1.1).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-b-x', `${drift(1.16, 0.82, 2.4).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-b-y', `${drift(0.98, 0.76, 0.7).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-c-x', `${drift(1.04, 1.02, 3.1).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-c-y', `${drift(1.22, 0.84, 1.8).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-d-x', `${drift(0.88, 0.78, 4.2).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-d-y', `${drift(1.14, 0.74, 2.7).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-e-x', `${drift(1.28, 0.62, 5.1).toFixed(2)}px`); + voiceOrb.style.setProperty('--chatkit-drift-e-y', `${drift(0.94, 0.58, 3.5).toFixed(2)}px`); + }; + + const disconnectOrbInput = (entry) => { + if (!entry) return; + if (entry.source) { + try { + entry.source.disconnect(); + } catch {} + } + }; + + const ensureOrbAudioContext = async () => { + const AudioContextCtor = window.AudioContext || window.webkitAudioContext; + if (!AudioContextCtor) return null; + if (!orbAudioContext) orbAudioContext = new AudioContextCtor(); + if (orbAudioContext.state === 'suspended') { + try { + await orbAudioContext.resume(); + } catch {} + } + return orbAudioContext; + }; + + const measureOrbInput = (analyser, data) => { + analyser.getByteTimeDomainData(data); + let sum = 0; + for (let index = 0; index < data.length; index += 1) { + const normalized = (data[index] - 128) / 128; + sum += normalized * normalized; + } + const rms = Math.sqrt(sum / data.length); + return Math.max(0, Math.min(1, (rms - 0.01) * 14)); + }; + + const stopOrbLoop = () => { + if (!orbFrame) return; + cancelAnimationFrame(orbFrame); + orbFrame = 0; + }; + + const stopOrbAnalysis = () => { + stopOrbLoop(); + orbInputs.forEach(disconnectOrbInput); + orbInputs.clear(); + setOrbLevel(0); + setOrbBeat(0); + }; + + const startOrbLoop = () => { + if (orbFrame) return; + const render = () => { + let strongest = 0; + let total = 0; + orbInputs.forEach((entry) => { + const level = measureOrbInput(entry.analyser, entry.data); + strongest = Math.max(strongest, level); + total += level; + }); + + const targetLevel = orbInputs.size + ? Math.max(strongest, Math.min(1, strongest * 0.86 + total * 0.12)) + : 0; + const smoothing = targetLevel > orbLevel ? 0.38 : 0.18; + const nextLevel = orbLevel + (targetLevel - orbLevel) * smoothing; + const normalizedLevel = nextLevel < 0.006 ? 0 : nextLevel; + const beatTarget = orbInputs.size ? Math.min(1, strongest * 1.35) : 0; + const beatSmoothing = beatTarget > orbBeat ? 0.58 : 0.14; + const nextBeat = orbBeat + (beatTarget - orbBeat) * beatSmoothing; + setOrbLevel(normalizedLevel); + setOrbBeat(nextBeat < 0.01 ? 0 : nextBeat); + setOrbMotion(normalizedLevel); + + if (!orbInputs.size && normalizedLevel < 0.006) { + orbFrame = 0; + return; + } + orbFrame = requestAnimationFrame(render); + }; + orbFrame = requestAnimationFrame(render); + }; + + const removeOrbInput = (key) => { + const entry = orbInputs.get(key); + if (!entry) return; + disconnectOrbInput(entry); + orbInputs.delete(key); + if (!orbInputs.size) stopOrbLoop(); + }; + + const removeOrbInputsByPrefix = (prefix) => { + Array.from(orbInputs.keys()).forEach((key) => { + if (key.startsWith(prefix)) removeOrbInput(key); + }); + }; + + const attachOrbStream = async (stream, key) => { + if (!(stream instanceof MediaStream) || !key || orbInputs.has(key)) return; + + const context = await ensureOrbAudioContext(); + if (!context) return; + + try { + const analyser = context.createAnalyser(); + analyser.fftSize = 256; + analyser.smoothingTimeConstant = 0.72; + const data = new Uint8Array(analyser.fftSize); + const source = context.createMediaStreamSource(stream); + source.connect(analyser); + orbInputs.set(key, { analyser, data, source }); + startOrbLoop(); + } catch {} + }; + + const getMediaStreamTrack = (trackOrPublication) => { + const candidate = trackOrPublication?.track || trackOrPublication; + const mediaTrack = candidate?.mediaStreamTrack + || candidate?.track?.mediaStreamTrack + || candidate?._mediaStreamTrack + || null; + if (!mediaTrack || mediaTrack.kind !== 'audio' || mediaTrack.readyState !== 'live') return null; + return mediaTrack; + }; + + const syncLocalMicAnalysis = async (currentRoom) => { + removeOrbInputsByPrefix('local:'); + if (!currentRoom || !micEnabled) return; + + const publications = currentRoom.localParticipant?.trackPublications; + if (!publications || typeof publications.values !== 'function') return; + + for (const publication of publications.values()) { + const mediaTrack = getMediaStreamTrack(publication); + if (!mediaTrack || mediaTrack.enabled === false) continue; + const stream = new MediaStream([mediaTrack]); + await attachOrbStream(stream, `local:${mediaTrack.id || 'mic'}`); + break; + } + }; + + const setStatus = (state, label, description) => { + if (connectionBadge && lastStatusLabel !== label) connectionBadge.textContent = label; + if (connectionBadge && lastStatusState !== state) connectionBadge.dataset.state = state; + if (connectionText && lastStatusDescription !== description) connectionText.textContent = description; + lastStatusState = state; + lastStatusLabel = label; + lastStatusDescription = description; + if (voiceOrb) { + if (!voiceOrb.classList.contains(state)) { + voiceOrb.classList.remove('is-idle', 'is-connecting', 'is-live', 'is-paused', 'is-output-muted', 'is-error'); + voiceOrb.classList.add(state); + } + if (state !== 'is-live') { + voiceOrb.classList.remove('is-speaking'); + setOrbLevel(0); + setOrbBeat(0); + } + } + }; + + const renderConnectedStatus = () => { + if (!room) { + setStatus( + 'is-idle', + text('webui.chatkit.statusIdle', '未连接'), + text('webui.chatkit.idleText', '点击并授权,通过 ChatKit 语音会话连接 Grok Voice。'), + ); + return; + } + + if (!micEnabled) { + setStatus( + 'is-paused', + text('webui.chatkit.statusPaused', '已暂停'), + text('webui.chatkit.pausedText', '会话已暂停,点击开始即可继续当前语音会话。'), + ); + return; + } + + if (outputMuted) { + setStatus( + 'is-output-muted', + text('webui.chatkit.statusMuted', '已静音'), + text('webui.chatkit.outputMutedText', '扬声器已静音,你仍然可以继续说话。'), + ); + return; + } + + setStatus( + 'is-live', + text('webui.chatkit.statusLive', '语音中'), + text('webui.chatkit.liveText', '连接已建立,现在可以直接开口和 Grok 对话。'), + ); + }; + + const setButtons = (connected) => { + if (startVoiceBtn) { + startVoiceBtn.disabled = false; + const label = connected && micEnabled + ? text('webui.chatkit.pause', '暂停') + : text('webui.chatkit.start', '开始'); + startVoiceBtn.innerHTML = connected && micEnabled ? controlIcon.pause : controlIcon.start; + startVoiceBtn.setAttribute('aria-label', label); + startVoiceBtn.setAttribute('title', label); + } + if (muteVoiceBtn) { + muteVoiceBtn.disabled = !connected; + const label = outputMuted + ? text('webui.chatkit.unmute', '取消静音') + : text('webui.chatkit.mute', '静音'); + muteVoiceBtn.innerHTML = outputMuted ? controlIcon.unmute : controlIcon.mute; + muteVoiceBtn.setAttribute('aria-label', label); + muteVoiceBtn.setAttribute('title', label); + } + if (newSessionBtn) { + newSessionBtn.disabled = !connected; + const label = text('webui.chatkit.newSession', '新会话'); + newSessionBtn.innerHTML = controlIcon.newSession; + newSessionBtn.setAttribute('aria-label', label); + newSessionBtn.setAttribute('title', label); + } + }; + + const detachAudio = () => { + stopOrbAnalysis(); + audioElements.forEach((node) => { + try { + node.pause(); + node.srcObject = null; + } catch {} + node.remove(); + }); + audioElements.clear(); + }; + + const getLiveKit = () => window.LiveKitClient || window.LivekitClient || null; + + const getAuthHeaders = async () => { + const key = await webuiKey.get(); + return key ? { Authorization: `Bearer ${key}` } : {}; + }; + + const addRemoteAudioTrack = (track) => { + if (!audioRoot || !track || track.kind !== 'audio') return; + const element = track.attach(); + element.autoplay = true; + element.playsInline = true; + element.muted = outputMuted; + audioRoot.appendChild(element); + audioElements.add(element); + const stream = element.srcObject instanceof MediaStream ? element.srcObject : null; + const streamId = stream?.id || stream?.getAudioTracks?.()[0]?.id || ''; + if (stream && streamId) { + void attachOrbStream(stream, `remote:${streamId}`); + } + }; + + const bindRoomEvents = (lk, currentRoom) => { + currentRoom.on(lk.RoomEvent.TrackSubscribed, (track) => { + addRemoteAudioTrack(track); + }); + + currentRoom.on(lk.RoomEvent.TrackUnsubscribed, (track) => { + try { + const elements = track.detach(); + elements.forEach((el) => { + let streamId = ''; + if (el instanceof HTMLMediaElement && el.srcObject instanceof MediaStream) { + streamId = el.srcObject.id || el.srcObject.getAudioTracks?.()[0]?.id || ''; + } + if (streamId) removeOrbInput(`remote:${streamId}`); + if (el instanceof HTMLAudioElement) audioElements.delete(el); + el.remove(); + }); + } catch {} + }); + + currentRoom.on(lk.RoomEvent.Disconnected, () => { + teardownSession(false); + }); + }; + + const teardownSession = async (manual) => { + const currentRoom = room; + room = null; + try { + if (currentRoom) await currentRoom.disconnect(); + } catch {} + detachAudio(); + micEnabled = true; + outputMuted = false; + setButtons(false); + renderConnectedStatus(); + if (manual && connectionText) { + connectionText.textContent = text('webui.chatkit.endedText', '语音会话已结束,可以重新开始。'); + } + }; + + const startSession = async () => { + const lk = getLiveKit(); + if (!lk || !lk.Room) { + showToast?.(text('webui.chatkit.livekitLoadFailed', 'LiveKit SDK 加载失败'), 'error'); + return; + } + + if (startVoiceBtn) startVoiceBtn.disabled = true; + void ensureOrbAudioContext(); + setStatus( + 'is-connecting', + text('webui.chatkit.statusConnecting', '正在连接'), + text('webui.chatkit.connectingText', '正在向 Grok Voice 申请会话并连接 LiveKit…'), + ); + + try { + const headers = await getAuthHeaders(); + headers['Content-Type'] = 'application/json'; + const res = await fetch(VOICE_ENDPOINT, { + method: 'POST', + headers, + cache: 'no-store', + body: JSON.stringify({ + voice: voiceSelect?.value || 'ara', + personality: personalitySelect?.value || 'assistant', + speed: Number(speedSelect?.value || 1), + instruction: instructionInput?.value?.trim() || '', + }), + }); + if (!res.ok) { + const detail = await res.text().catch(() => ''); + throw new Error(detail || `HTTP ${res.status}`); + } + + const payload = await res.json(); + if (!payload || !payload.token || !payload.url) { + throw new Error(text('webui.chatkit.invalidToken', 'Voice token response invalid')); + } + + const currentRoom = new lk.Room({ + adaptiveStream: true, + dynacast: true, + audioCaptureDefaults: { + autoGainControl: true, + echoCancellation: true, + noiseSuppression: true, + }, + }); + room = currentRoom; + bindRoomEvents(lk, currentRoom); + + await currentRoom.connect(payload.url, payload.token); + await currentRoom.localParticipant.setMicrophoneEnabled(true); + + micEnabled = true; + outputMuted = false; + setButtons(true); + renderConnectedStatus(); + void syncLocalMicAnalysis(currentRoom); + } catch (error) { + const message = error && error.message ? error.message : String(error); + showToast?.(message, 'error'); + setStatus( + 'is-error', + text('webui.chatkit.statusError', '连接失败'), + text('webui.chatkit.errorText', '连接没有建立成功,请检查麦克风权限后重试。'), + ); + await teardownSession(false); + } finally { + if (startVoiceBtn && !room) startVoiceBtn.disabled = false; + } + }; + + const togglePause = async () => { + if (!room) return; + micEnabled = !micEnabled; + await room.localParticipant.setMicrophoneEnabled(micEnabled); + setButtons(true); + renderConnectedStatus(); + void syncLocalMicAnalysis(room); + }; + + const toggleOutputMute = () => { + if (!room) return; + outputMuted = !outputMuted; + audioElements.forEach((node) => { + node.muted = outputMuted; + }); + setButtons(true); + renderConnectedStatus(); + }; + + const handlePrimaryAction = async () => { + if (!room) { + await startSession(); + return; + } + await togglePause(); + }; + + const startFreshSession = async () => { + if (!room) return; + await teardownSession(true); + await startSession(); + }; + + startVoiceBtn?.addEventListener('click', () => { + void handlePrimaryAction(); + }); + muteVoiceBtn?.addEventListener('click', toggleOutputMute); + newSessionBtn?.addEventListener('click', () => { + void startFreshSession(); + }); + + window.addEventListener('beforeunload', () => { + if (room) void room.disconnect(); + }); + + setButtons(false); + setStatus( + 'is-idle', + text('webui.chatkit.statusIdle', '未连接'), + text('webui.chatkit.idleText', '点击并授权,通过 ChatKit 语音会话连接 Grok Voice。'), + ); + if (typeof renderWebuiHeader === 'function') { + void renderWebuiHeader(); + } + if (typeof renderSiteFooter === 'function') { + void renderSiteFooter(); + } +})(); diff --git a/app/statics/js/webui/masonry.js b/app/statics/js/webui/masonry.js new file mode 100644 index 0000000000000000000000000000000000000000..c2275ab759d44b79eade69f90d65940ff500fcfd --- /dev/null +++ b/app/statics/js/webui/masonry.js @@ -0,0 +1,725 @@ +(() => { + const VERIFY_ENDPOINT = '/webui/api/verify'; + const IMAGINE_WS_ENDPOINT = '/webui/api/imagine/ws'; + const IMAGE_COUNT = 6; + const PROMPT_MIN_HEIGHT = 52; + const PROMPT_MAX_HEIGHT = 160; + const RECONNECT_DELAY_MS = 250; + + const promptInput = document.getElementById('promptInput'); + const sendBtn = document.getElementById('sendBtn'); + const feed = document.getElementById('masonryFeed'); + const emptyState = document.getElementById('masonryEmpty'); + const statusEl = document.getElementById('masonryStatus'); + const aspectRatioSelect = document.getElementById('aspectRatioSelect'); + const aspectRatioWrap = document.getElementById('aspectRatioWrap'); + const qualityToggle = document.getElementById('qualityToggle'); + const modeToggle = document.getElementById('modeToggle'); + + let activeSocket = null; + let sending = false; + let streamState = null; + let pendingGridSyncFrame = 0; + + function aspectRatioCss(value) { + const ratio = String(value || '').trim(); + if (!ratio.includes(':')) return '1 / 1'; + const [w, h] = ratio.split(':'); + const width = Number(w) || 1; + const height = Number(h) || 1; + return `${width} / ${height}`; + } + + function computeGridColumns(width) { + const viewport = window.innerWidth || width || 0; + const maxCols = viewport <= 768 ? 3 : 8; + const minTileWidth = viewport <= 768 ? 132 : 188; + const safeWidth = Math.max(width || 0, minTileWidth); + return Math.max(1, Math.min(maxCols, Math.floor(safeWidth / minTileWidth))); + } + + function syncBatchGrid(grid) { + if (!(grid instanceof HTMLElement)) return; + const columns = computeGridColumns(grid.clientWidth); + if (grid.dataset.columns === String(columns)) return; + grid.dataset.columns = String(columns); + grid.style.setProperty('--masonry-columns', String(columns)); + } + + function syncAllBatchGrids() { + feed?.querySelectorAll('.webui-masonry-grid').forEach((grid) => { + syncBatchGrid(grid); + }); + } + + function scheduleAllBatchGridsSync() { + if (pendingGridSyncFrame) return; + pendingGridSyncFrame = window.requestAnimationFrame(() => { + pendingGridSyncFrame = 0; + syncAllBatchGrids(); + }); + } + + function text(key, fallback, params) { + if (typeof window.t !== 'function') return fallback; + const value = t(key, params); + return value === key ? fallback : value; + } + + function toast(message, type = 'info') { + if (typeof showToast === 'function') showToast(message, type); + } + + function buildWebSocketUrl(path, params = {}) { + const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const url = new URL(path, `${protocol}//${window.location.host}`); + Object.entries(params).forEach(([key, value]) => { + if (value === null || value === undefined || value === '') return; + url.searchParams.set(key, String(value)); + }); + return url.toString(); + } + + function resizePromptInput() { + if (!promptInput) return; + promptInput.style.height = `${PROMPT_MIN_HEIGHT}px`; + const nextHeight = Math.min(Math.max(promptInput.scrollHeight, PROMPT_MIN_HEIGHT), PROMPT_MAX_HEIGHT); + promptInput.style.height = `${nextHeight}px`; + promptInput.style.overflowY = promptInput.scrollHeight > PROMPT_MAX_HEIGHT ? 'auto' : 'hidden'; + } + + function setEmptyState() { + if (!feed || !emptyState) return; + const hasBatch = feed.querySelector('.webui-masonry-batch') !== null; + emptyState.hidden = hasBatch; + emptyState.style.display = hasBatch ? 'none' : ''; + } + + function setStatus(message, state = 'idle') { + if (!statusEl) return; + statusEl.textContent = message; + statusEl.dataset.state = state; + } + + function renderSendButton(running) { + if (!sendBtn) return; + const label = running + ? text('webui.masonry.stop', '停止') + : text('webui.masonry.generate', '生成'); + const icon = running + ? '' + : ''; + sendBtn.innerHTML = icon; + sendBtn.setAttribute('aria-label', label); + sendBtn.setAttribute('title', label); + } + + function setSending(next) { + sending = next; + if (promptInput) promptInput.disabled = next; + if (aspectRatioSelect) aspectRatioSelect.disabled = next; + qualityToggle?.querySelectorAll('.webui-masonry-toggle-btn').forEach((button) => { + button.disabled = next; + }); + modeToggle?.querySelectorAll('.webui-masonry-toggle-btn').forEach((button) => { + button.disabled = next; + }); + renderSendButton(next); + } + + function formatRoundLabel(round) { + return text('webui.masonry.roundLabel', '第 {n} 轮', { n: round }); + } + + function formatQualityLabel(quality) { + return quality === 'quality' + ? text('webui.masonry.qualityQuality', 'Quality') + : text('webui.masonry.qualitySpeed', 'Speed'); + } + + function syncAspectRatioIndicator() { + const ratio = aspectRatioSelect?.value || '2:3'; + if (aspectRatioWrap) aspectRatioWrap.dataset.ratio = ratio; + } + + function readToggleValue(group, fallback) { + const active = group?.querySelector('.webui-masonry-toggle-btn.is-active'); + return active?.dataset.value || fallback; + } + + function setToggleValue(group, value) { + group?.querySelectorAll('.webui-masonry-toggle-btn').forEach((button) => { + const active = button.dataset.value === value; + button.classList.toggle('is-active', active); + button.setAttribute('aria-pressed', active ? 'true' : 'false'); + }); + } + + function createSlot(index) { + const tile = document.createElement('article'); + tile.className = 'webui-masonry-tile is-pending'; + + const badge = document.createElement('div'); + badge.className = 'webui-masonry-tile-badge'; + badge.textContent = String(index); + + const body = document.createElement('div'); + body.className = 'webui-masonry-tile-body'; + + const link = document.createElement('a'); + link.className = 'webui-masonry-tile-link'; + link.target = '_blank'; + link.rel = 'noopener'; + link.setAttribute('aria-label', text('webui.masonry.openImage', '打开图片')); + link.title = text('webui.masonry.openImage', '打开图片'); + + const img = document.createElement('img'); + img.alt = `image ${index}`; + img.loading = 'lazy'; + link.appendChild(img); + + const label = document.createElement('div'); + label.className = 'webui-masonry-tile-label'; + + const progressShell = document.createElement('div'); + progressShell.className = 'webui-masonry-tile-progress'; + + const progressValue = document.createElement('div'); + progressValue.className = 'webui-masonry-tile-progress-value'; + + const progressTrack = document.createElement('div'); + progressTrack.className = 'webui-masonry-tile-progress-track'; + + const progressFill = document.createElement('div'); + progressFill.className = 'webui-masonry-tile-progress-fill'; + progressTrack.appendChild(progressFill); + progressShell.appendChild(progressValue); + progressShell.appendChild(progressTrack); + + tile.appendChild(badge); + tile.appendChild(body); + + return { + index, + id: '', + url: '', + progress: 0, + moderated: false, + tile, + body, + link, + img, + label, + progressShell, + progressValue, + progressFill, + renderedState: '', + renderedProgress: -1, + renderedUrl: '', + }; + } + + function createBatch(prompt, aspectRatio, quality, round) { + const wrap = document.createElement('section'); + wrap.className = 'webui-masonry-batch'; + + const head = document.createElement('header'); + head.className = 'webui-masonry-batch-head'; + + const promptEl = document.createElement('div'); + promptEl.className = 'webui-masonry-batch-prompt'; + promptEl.textContent = prompt; + + const meta = document.createElement('div'); + meta.className = 'webui-masonry-batch-meta'; + + const ratio = document.createElement('span'); + ratio.className = 'webui-masonry-batch-chip is-param'; + ratio.textContent = aspectRatio; + + const qualityChip = document.createElement('span'); + qualityChip.className = 'webui-masonry-batch-chip is-param'; + qualityChip.textContent = formatQualityLabel(quality); + + const roundLabel = document.createElement('span'); + roundLabel.className = 'webui-masonry-batch-chip is-round'; + roundLabel.textContent = formatRoundLabel(round); + + const count = document.createElement('span'); + count.className = 'webui-masonry-batch-chip is-count'; + count.textContent = `0/${IMAGE_COUNT}`; + + const state = document.createElement('span'); + state.className = 'webui-masonry-batch-chip is-state'; + state.dataset.state = 'generating'; + state.textContent = text('webui.masonry.statusGenerating', '正在生成'); + + meta.appendChild(roundLabel); + meta.appendChild(ratio); + meta.appendChild(qualityChip); + meta.appendChild(count); + meta.appendChild(state); + + head.appendChild(promptEl); + head.appendChild(meta); + + const grid = document.createElement('div'); + grid.className = 'webui-masonry-grid'; + grid.style.setProperty('--tile-aspect', aspectRatioCss(aspectRatio)); + + const slots = Array.from({ length: IMAGE_COUNT }, (_, index) => createSlot(index + 1)); + slots.forEach((slot) => { + renderSlot(slot); + grid.appendChild(slot.tile); + }); + + wrap.appendChild(head); + wrap.appendChild(grid); + feed.prepend(wrap); + setEmptyState(); + syncBatchGrid(grid); + + return { + wrap, + count, + state, + slots, + round, + prompt, + aspectRatio, + quality, + completed: false, + failed: false, + finalized: false, + readyCount: 0, + filteredCount: 0, + }; + } + + function updateBatchMeta(batch) { + const completed = batch.readyCount; + const filtered = batch.filteredCount; + batch.count.textContent = `${completed}/${IMAGE_COUNT}`; + + if (!batch.finalized) { + batch.state.dataset.state = 'generating'; + batch.state.textContent = text('webui.masonry.statusGenerating', '正在生成'); + return; + } + + if (completed >= IMAGE_COUNT) { + batch.state.dataset.state = 'success'; + batch.state.textContent = text('webui.masonry.statusSuccess', '生成成功'); + return; + } + + if (completed > 0 || (completed === 0 && filtered > 0 && filtered < IMAGE_COUNT)) { + batch.state.dataset.state = 'partial'; + batch.state.textContent = text('webui.masonry.statusPartialFailure', '部分失败'); + return; + } + + batch.state.dataset.state = 'failed'; + batch.state.textContent = text('webui.masonry.statusBatchFailed', '生成失败'); + } + + function markBatchFailed(batch) { + if (!batch || batch.finalized) return; + batch.failed = true; + batch.finalized = true; + updateBatchMeta(batch); + } + + function markBatchStopped(batch) { + if (!batch || batch.finalized) return; + batch.finalized = true; + updateBatchMeta(batch); + } + + function renderSlot(slot) { + const nextState = slot.url ? 'ready' : (slot.moderated ? 'filtered' : 'pending'); + slot.tile.classList.toggle('is-pending', nextState === 'pending'); + slot.tile.classList.toggle('is-ready', nextState === 'ready'); + slot.tile.classList.toggle('is-filtered', nextState === 'filtered'); + + if (nextState === 'ready') { + if (slot.renderedUrl !== slot.url) { + slot.link.href = slot.url; + slot.img.src = slot.url; + slot.renderedUrl = slot.url; + } + if (slot.renderedState !== nextState) slot.body.replaceChildren(slot.link); + slot.renderedState = nextState; + return; + } + + slot.renderedUrl = ''; + if (nextState === 'filtered') { + slot.label.textContent = text('webui.masonry.batchFiltered', '已过滤'); + if (slot.renderedState !== nextState) slot.body.replaceChildren(slot.label); + slot.renderedState = nextState; + return; + } + + const progress = Math.max(0, Math.min(99, slot.progress || 0)); + if (slot.renderedProgress !== progress) { + slot.progressValue.textContent = `${progress}%`; + slot.progressFill.style.width = `${progress}%`; + slot.renderedProgress = progress; + } + if (slot.renderedState !== nextState) slot.body.replaceChildren(slot.progressShell); + slot.renderedState = nextState; + } + + function slotOutcome(slot) { + if (slot.url && !slot.moderated) return 'ready'; + if (slot.moderated) return 'filtered'; + return 'pending'; + } + + function updateBatchCounts(batch, previousOutcome, nextOutcome) { + if (previousOutcome === nextOutcome) return false; + if (previousOutcome === 'ready') batch.readyCount = Math.max(0, batch.readyCount - 1); + if (previousOutcome === 'filtered') batch.filteredCount = Math.max(0, batch.filteredCount - 1); + if (nextOutcome === 'ready') batch.readyCount += 1; + if (nextOutcome === 'filtered') batch.filteredCount += 1; + return true; + } + + function findSlot(batch, payload) { + const imageId = String(payload.image_id || '').trim(); + const order = Number(payload.order); + let slot = null; + + if (imageId) slot = batch.slots.find((item) => item.id === imageId) || null; + if (!slot && Number.isInteger(order) && order >= 0 && order < batch.slots.length) { + const orderedSlot = batch.slots[order] || null; + if (orderedSlot && !orderedSlot.url && !orderedSlot.moderated) { + slot = orderedSlot; + } + } + if (!slot) { + slot = batch.slots.find((item) => !item.url && !item.moderated) || null; + } + if (!slot) { + slot = batch.slots.find((item) => !item.id && !item.url && !item.moderated) || batch.slots[0]; + } + if (slot && imageId) slot.id = imageId; + return slot; + } + + function syncBatch(batch, payload) { + const slot = findSlot(batch, payload); + if (!slot) return; + const previousOutcome = slotOutcome(slot); + + if (payload.type === 'progress') { + slot.progress = Number(payload.progress) || slot.progress || 0; + } else if (payload.type === 'image') { + slot.progress = 100; + slot.url = String(payload.url || '').trim(); + slot.moderated = false; + } else if (payload.type === 'moderated') { + slot.progress = 100; + slot.url = ''; + slot.moderated = true; + } + + const nextOutcome = slotOutcome(slot); + const countsChanged = updateBatchCounts(batch, previousOutcome, nextOutcome); + renderSlot(slot); + if (countsChanged || payload.type !== 'progress') updateBatchMeta(batch); + } + + function createStreamState(prompt, aspectRatio, quality, mode) { + return { + prompt, + aspectRatio, + quality, + mode, + keepRunning: true, + userStopped: false, + failed: false, + batchIndex: 0, + currentRunId: '', + currentBatch: null, + nextBatchQueued: false, + }; + } + + async function ensureAccess() { + const stored = await webuiKey.get(); + if (stored && await verifyKey(VERIFY_ENDPOINT, stored)) return true; + if (stored) webuiKey.clear(); + if (await verifyKey(VERIFY_ENDPOINT, '')) return true; + location.href = '/webui/login'; + return false; + } + + async function connectSocket() { + if (!streamState?.keepRunning) return; + if (activeSocket && (activeSocket.readyState === WebSocket.OPEN || activeSocket.readyState === WebSocket.CONNECTING)) { + return; + } + + const token = await webuiKey.get(); + const wsUrl = buildWebSocketUrl(IMAGINE_WS_ENDPOINT, token ? { access_token: token } : {}); + const socket = new WebSocket(wsUrl); + activeSocket = socket; + + socket.addEventListener('open', () => { + if (activeSocket !== socket || !streamState?.keepRunning) return; + scheduleNextBatch(); + }); + + socket.addEventListener('message', (event) => { + const state = streamState; + if (!state) return; + + let payload; + try { + payload = JSON.parse(String(event.data || '{}')); + } catch { + return; + } + if (!payload || typeof payload !== 'object') return; + + if (payload.run_id && !state.currentRunId) state.currentRunId = String(payload.run_id); + if (state.currentRunId && payload.run_id && String(payload.run_id) !== state.currentRunId) return; + + const batch = state.currentBatch; + if (payload.type === 'status') { + if (payload.status === 'running') { + setStatus(`${text('webui.masonry.statusGenerating', '生成中…')} · ${formatRoundLabel(state.batchIndex)}`, 'running'); + } else if (payload.status === 'completed') { + if (batch) { + batch.completed = true; + batch.finalized = true; + updateBatchMeta(batch); + } + state.currentRunId = ''; + if (state.keepRunning && !state.userStopped && state.mode === 'continuous') { + scheduleNextBatch(); + } else { + state.keepRunning = false; + setStatus(text('webui.masonry.statusCompleted', '完成'), 'completed'); + try { + socket.close(1000, 'completed'); + } catch {} + } + } else if (payload.status === 'stopped') { + state.userStopped = true; + state.keepRunning = false; + markBatchStopped(batch); + setStatus(text('webui.masonry.statusStopped', '已停止'), 'stopped'); + } + return; + } + + if (!batch) return; + + if (payload.type === 'progress' || payload.type === 'image' || payload.type === 'moderated') { + syncBatch(batch, payload); + setStatus(`${text('webui.masonry.statusGenerating', '生成中…')} ${batch.readyCount}/${IMAGE_COUNT} · ${formatRoundLabel(batch.round)}`, 'running'); + return; + } + + if (payload.type === 'error') { + state.failed = true; + state.keepRunning = false; + markBatchFailed(batch); + setStatus(text('webui.masonry.statusFailed', '失败'), 'failed'); + toast(payload.message || text('webui.masonry.errors.requestFailed', '请求失败'), 'error'); + try { + socket.close(1011, 'error'); + } catch {} + } + }); + + socket.addEventListener('error', () => { + if (streamState?.keepRunning && !streamState.userStopped) { + setStatus(text('webui.masonry.statusConnecting', '连接中…'), 'connecting'); + } + }); + + socket.addEventListener('close', () => { + const state = streamState; + if (activeSocket === socket) activeSocket = null; + if (!state) { + setSending(false); + return; + } + + if (state.userStopped) { + markBatchStopped(state.currentBatch); + setSending(false); + streamState = null; + setStatus(text('webui.masonry.statusStopped', '已停止'), 'stopped'); + promptInput?.focus(); + return; + } + + if (state.failed) { + markBatchFailed(state.currentBatch); + setSending(false); + streamState = null; + setStatus(text('webui.masonry.statusFailed', '失败'), 'failed'); + promptInput?.focus(); + return; + } + + if (state.keepRunning) { + if (state.currentBatch && !state.currentBatch.completed) { + markBatchFailed(state.currentBatch); + } + setStatus(text('webui.masonry.statusConnecting', '连接中…'), 'connecting'); + window.setTimeout(() => { + if (streamState === state && state.keepRunning) { + void connectSocket(); + } + }, RECONNECT_DELAY_MS); + return; + } + + setSending(false); + streamState = null; + promptInput?.focus(); + }); + } + + function scheduleNextBatch() { + const state = streamState; + if (!state?.keepRunning || state.userStopped || state.failed || state.nextBatchQueued) return; + state.nextBatchQueued = true; + + window.setTimeout(() => { + const current = streamState; + if (current !== state) return; + state.nextBatchQueued = false; + if (!state.keepRunning || state.userStopped || state.failed) return; + if (!activeSocket || activeSocket.readyState !== WebSocket.OPEN) { + void connectSocket(); + return; + } + + state.batchIndex += 1; + state.currentRunId = ''; + state.currentBatch = createBatch(state.prompt, state.aspectRatio, state.quality, state.batchIndex); + setStatus(`${text('webui.masonry.statusGenerating', '生成中…')} · ${formatRoundLabel(state.batchIndex)}`, 'running'); + + try { + activeSocket.send(JSON.stringify({ + type: 'start', + prompt: state.prompt, + aspect_ratio: state.aspectRatio, + quality: state.quality, + count: IMAGE_COUNT, + })); + } catch { + void connectSocket(); + } + }, 0); + } + + function stopGeneration({ silent = false } = {}) { + if (streamState) { + streamState.keepRunning = false; + streamState.userStopped = true; + streamState.nextBatchQueued = false; + } + const socket = activeSocket; + if (socket) socket.__userStopped = true; + activeSocket = null; + if (socket) { + try { + socket.send(JSON.stringify({ type: 'stop' })); + } catch {} + try { + socket.close(1000, 'stopped'); + } catch {} + } + setSending(false); + setStatus(text('webui.masonry.statusStopped', '已停止'), 'stopped'); + markBatchStopped(streamState?.currentBatch); + streamState = null; + if (!silent) toast(text('webui.masonry.statusStopped', '已停止'), 'info'); + } + + async function startGeneration() { + if (sending) { + stopGeneration({ silent: true }); + return; + } + + const prompt = String(promptInput?.value || '').trim(); + if (!prompt) { + toast(text('webui.masonry.errors.enterPrompt', '请输入提示词'), 'error'); + return; + } + + const aspectRatio = aspectRatioSelect?.value || '2:3'; + const quality = readToggleValue(qualityToggle, 'speed') === 'quality' ? 'quality' : 'speed'; + const mode = readToggleValue(modeToggle, 'single') === 'continuous' ? 'continuous' : 'single'; + streamState = createStreamState(prompt, aspectRatio, quality, mode); + setSending(true); + setStatus(text('webui.masonry.statusConnecting', '连接中…'), 'connecting'); + promptInput.value = ''; + resizePromptInput(); + await connectSocket(); + } + + async function boot() { + await renderWebuiHeader?.(); + await renderSiteFooter?.(); + window.I18n?.apply?.(document); + if (!await ensureAccess()) return; + syncAspectRatioIndicator(); + setToggleValue(qualityToggle, 'speed'); + setToggleValue(modeToggle, 'single'); + setSending(false); + setEmptyState(); + setStatus(text('webui.masonry.statusReady', '就绪'), 'idle'); + resizePromptInput(); + promptInput?.focus(); + } + + sendBtn?.addEventListener('click', () => { + void startGeneration(); + }); + + qualityToggle?.addEventListener('click', (event) => { + const button = event.target instanceof Element ? event.target.closest('.webui-masonry-toggle-btn') : null; + if (!(button instanceof HTMLButtonElement) || button.disabled) return; + setToggleValue(qualityToggle, button.dataset.value || 'speed'); + }); + + modeToggle?.addEventListener('click', (event) => { + const button = event.target instanceof Element ? event.target.closest('.webui-masonry-toggle-btn') : null; + if (!(button instanceof HTMLButtonElement) || button.disabled) return; + setToggleValue(modeToggle, button.dataset.value || 'single'); + }); + + promptInput?.addEventListener('input', resizePromptInput); + aspectRatioSelect?.addEventListener('change', syncAspectRatioIndicator); + promptInput?.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault(); + void startGeneration(); + } + }); + + window.addEventListener('beforeunload', () => { + if (!activeSocket) return; + try { + activeSocket.close(1000, 'unload'); + } catch {} + activeSocket = null; + }); + window.addEventListener('resize', scheduleAllBatchGridsSync); + + boot().catch((error) => { + console.error('webui masonry boot failed', error); + toast(text('webui.masonry.errors.initFailed', '瀑布流页面初始化失败'), 'error'); + setStatus(text('webui.masonry.statusFailed', '失败'), 'failed'); + }); +})(); diff --git a/app/statics/webui/chat.html b/app/statics/webui/chat.html new file mode 100644 index 0000000000000000000000000000000000000000..5714e75db75bca69ad6a694db8c347d77e3974d8 --- /dev/null +++ b/app/statics/webui/chat.html @@ -0,0 +1,92 @@ + + + + + + Grok2API - WebChat + + + + + + + +
    +
    + + +
    +
    +
    +
    +
    +
    +
    Web Chat
    +
    输入一条消息开始新的会话。
    +
    +
    +
    +
    + +
    + +
    + + + +
    + + +
    +
    +
    +
    +
    +
    + + + + + + + + + + + + + diff --git a/app/statics/webui/chatkit.html b/app/statics/webui/chatkit.html new file mode 100644 index 0000000000000000000000000000000000000000..8d2cc577bf9f7f815a7d1acb2439918f8b7e3f9a --- /dev/null +++ b/app/statics/webui/chatkit.html @@ -0,0 +1,107 @@ + + + + + + Grok2API - ChatKit + + + + + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    未连接
    +
    + +
    +
    Grok Voice
    +
    点击并授权,通过 ChatKit 语音会话连接 Grok Voice。
    +
    + +
    + + + +
    + +
    +
    + +
    +
    + + + + +
    +
    +
    +
    +
    + + + + + + + + + diff --git a/app/statics/webui/header.html b/app/statics/webui/header.html new file mode 100644 index 0000000000000000000000000000000000000000..d75e1b204e5b99ec5954c32176e594aace01122b --- /dev/null +++ b/app/statics/webui/header.html @@ -0,0 +1,60 @@ +
    +
    + + +
    +
    + + +
    + +
    +
    +
    diff --git a/app/statics/webui/login.html b/app/statics/webui/login.html new file mode 100644 index 0000000000000000000000000000000000000000..228e238a995c89648b70a078d0dd29b66a8122cd --- /dev/null +++ b/app/statics/webui/login.html @@ -0,0 +1,57 @@ + + + + + + Grok2API - WebUI + + + + + + + + + + + + + + diff --git a/app/statics/webui/masonry.html b/app/statics/webui/masonry.html new file mode 100644 index 0000000000000000000000000000000000000000..4a8bdb962b03b06c4b04381b93d79de9e46ad14a --- /dev/null +++ b/app/statics/webui/masonry.html @@ -0,0 +1,80 @@ + + + + + + Grok2API - Masonry + + + + + + +
    + +
    +
    +
    +

    Masonry

    +
    + +
    +
    +
    +
    从一句提示词开始
    +
    每轮固定生成 6 张图,并持续出图直到你停止。
    +
    +
    +
    + +
    +
    + +
    +
    +
    + + +
    +
    + + +
    + +
    +
    + +
    +
    +
    +
    +
    +
    + + + + + + + + + diff --git a/config.defaults.toml b/config.defaults.toml new file mode 100644 index 0000000000000000000000000000000000000000..0ec60b1b64ea2db26e9f6ca0cc6f1a64633226eb --- /dev/null +++ b/config.defaults.toml @@ -0,0 +1,175 @@ +# ==================== 访问控制 ==================== +[app] +# 管理后台密码 +app_key = "grok2api" +# 应用访问地址 +app_url = "" +# API 调用密钥 +api_key = "" +# 启用 WebUI +webui_enabled = false +# WebUI 访问密码 +webui_key = "" + + +# ==================== 日志配置 ==================== +[logging] +# 写入文件等级 +file_level = "INFO" +# 日志文件最大保留数量(按天轮转) +max_files = 7 + + +# ==================== 应用功能 ==================== +[features] +# 是否启用临时对话 +temporary = true +# 是否启用会话记忆 +memory = false +# 是否启用流式响应 +stream = true +# 是否输出思考过程 +thinking = true +# 聊天类 AUTO 模型在 auto 额度耗尽时,是否自动降级到 fast/expert +auto_chat_mode_fallback = true +# 思考精简输出(false=完整原始推理过程,true=提炼结构化摘要) +thinking_summary = false +# 是否动态生成 Statsig 指纹 +dynamic_statsig = true +# 是否允许生成 NSFW 图片 +enable_nsfw = true +# 搜索信源始终以 search_sources 结构化字段输出(无需此开关)。 +# 此选项仅控制是否同时在响应正文末尾追加 ## Sources 纯文本段落(兼容文本解析客户端)。 +show_search_sources = false +# 全局附加指令 +custom_instruction = "" + +# 图片返回格式 +# grok_url — 直接返回 Grok CDN URL +# local_url — 下载后存本地,返回本地代理 URL +# grok_md — Markdown 内嵌 Grok CDN URL +# local_md — Markdown 内嵌本地代理 URL +# base64 — Markdown 内嵌 Base64 Data URI +image_format = "grok_url" +# Imagine WebSocket 返回的 imagine-public 图片默认直返;开启后下载到本地并返回本地代理 URL +imagine_public_image_proxy = false + +# 视频返回格式 +# grok_url — 直接返回 Grok CDN URL +# local_url — 下载后存本地,返回本地代理 URL +# grok_html — HTML