Compare commits
98
Commits
2eee87f5fa
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
feb055d4e6 | ||
|
|
ebbe64ce61 | ||
|
|
d3d6424aca | ||
|
|
69f0039256 | ||
|
|
cc2d7bec5a | ||
|
|
c1f8882e9a | ||
|
|
c176dd832b | ||
|
|
04cfbc4876 | ||
|
|
9eb1c01b7b | ||
|
|
61ddbb673e | ||
|
|
9b36374bfc | ||
|
|
1ed82f6d73 | ||
|
|
8320258ff0 | ||
|
|
b96d318e7a | ||
|
|
fd39929415 | ||
|
|
1cf94dae7b | ||
|
|
80bd551656 | ||
|
|
a9a200bf9c | ||
|
|
8e346161a6 | ||
|
|
f864dd33b5 | ||
|
|
fc176ae7bc | ||
|
|
49e69bf5ad | ||
|
|
2b15db905b | ||
|
|
f68aad743a | ||
|
|
018ba70d43 | ||
|
|
af2b9995c4 | ||
|
|
d2214bd355 | ||
|
|
fdeeee5066 | ||
|
|
e8a2d71d8e | ||
|
|
8e23a5ed1b | ||
|
|
6b3607c35f | ||
|
|
9ddd2fb16b | ||
|
|
3af915910c | ||
|
|
e1e7fc2566 | ||
|
|
2c53504ad4 | ||
|
|
19224f1993 | ||
|
|
1576162ecc | ||
|
|
7d0561da78 | ||
|
|
73aed4ff22 | ||
|
|
c2e1226836 | ||
|
|
db0a73031f | ||
|
|
f7a94d0116 | ||
|
|
b922b21b3f | ||
|
|
d53b296e43 | ||
|
|
8e4208c09a | ||
|
|
64982e95e1 | ||
|
|
48f19a0386 | ||
|
|
33d79194b8 | ||
|
|
69f7175424 | ||
|
|
8a773b8ab3 | ||
|
|
678b984b95 | ||
|
|
a92fc3c788 | ||
|
|
66f548586e | ||
|
|
733c8593d4 | ||
|
|
c62be67aa8 | ||
|
|
c0706d1846 | ||
|
|
4c04a5ed0e | ||
|
|
3993df5f4f | ||
|
|
15a1c13711 | ||
|
|
c68a76cb8c | ||
|
|
3b35b14a8a | ||
|
|
9e2fc8e40a | ||
|
|
9bca7b3a5a | ||
|
|
4dc41e04e7 | ||
|
|
f6c1ecc4af | ||
|
|
b858f09075 | ||
|
|
7ad3248cb0 | ||
|
|
3a118c23fb | ||
|
|
97a31f6e0c | ||
|
|
13d4fdc44e | ||
|
|
4d25cb64e1 | ||
|
|
540d1f583f | ||
|
|
6621133897 | ||
|
|
74f15a9e1e | ||
|
|
5081eea8b9 | ||
|
|
70c82d4ca7 | ||
|
|
68ddccba53 | ||
|
|
97ec0bbfba | ||
|
|
33d1238fb2 | ||
|
|
73dd2053e6 | ||
|
|
0bf607e35f | ||
|
|
55eb89ce0e | ||
|
|
aad3f28589 | ||
|
|
bad8b43b22 | ||
|
|
17a3282574 | ||
|
|
4507dc4b8e | ||
|
|
e4065d31c3 | ||
|
|
8bab67d31d | ||
|
|
c2f27e6e39 | ||
|
|
18cafe5354 | ||
|
|
6a5416532b | ||
|
|
15a2e6eb9e | ||
|
|
e999df8eff | ||
|
|
e0aa5522fb | ||
|
|
b66c448d7a | ||
|
|
35680c7b95 | ||
|
|
950f9bbf3d | ||
|
|
d143d8da22 |
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
||||
# API Gateway 环境变量模板
|
||||
# 小银网关 环境变量模板
|
||||
# ── 怎么用 ──
|
||||
# 1) 本机最简:复制成项目根的 .env 并填入真实 token(根 .env 不覆盖真实环境变量)。
|
||||
# 2) 交给「网关配置页 → 环境变量」那张卡管理:写 data/.env(权限 600,已进 .gitignore)。
|
||||
|
||||
+3
-1
@@ -30,6 +30,8 @@ data/feedback_media/
|
||||
# 运行期状态(第三十轮):会话落盘 / 视频归属落盘 —— 都是运行数据,且含账号名与凭证哈希,
|
||||
# 属"可重新生成、不该进版本库"的一类(重启后从空开始,语义上无害)
|
||||
data/sessions.json
|
||||
# 封禁历史(2026-11-19 补):运行时数据,且**含被封 IP 与操作人**,属隐私,不入库
|
||||
data/ban_history.jsonl
|
||||
data/video_owners.json
|
||||
|
||||
# 智能体运行记录(第三十八轮):运行时数据(谁在什么时候用了哪个智能体),
|
||||
@@ -47,7 +49,7 @@ data/*.bak
|
||||
# ── 设计稿(不入库,历史上从未入库)──────────────────────────────────
|
||||
# design/v1、v2、v3 是"出设计图"用的脚本 + 渲染出的 PNG(约 11MB)。
|
||||
# 它们与产品构建、网关运行完全无关,且 2026-09-13 曾被清理归档到
|
||||
# /root/.trash/2026-09-13-api-gateway-cleanup/design/(cp -a 可恢复)。
|
||||
# /root/.trash/<归档>/design/(cp -a 可恢复)。
|
||||
# 需要时本地恢复即可,不进版本库。
|
||||
design/
|
||||
|
||||
|
||||
+63
-28
@@ -1,5 +1,40 @@
|
||||
# CHANGELOG
|
||||
|
||||
## 2026-11-19 · 修 OpenCode 模型同步(官方文档改版导致连续两天 exit=2)
|
||||
|
||||
**症状**:自动化日报的「三、模型清单同步」整块失败,`logs/model-sync.log` 连续两天:
|
||||
|
||||
```
|
||||
[2026-11-17 23:02:18] exit=2 抓取/解析失败:RuntimeError: OpenCode 文档没解析出 Endpoints 表(页面可能改版)
|
||||
[2026-11-18 23:02:29] exit=2 同上
|
||||
```
|
||||
|
||||
**根因**:官方把 `## Endpoints` 表改成了「去 console 页看 / 用 models 接口」,
|
||||
HTML 里已经没有带 `opencode.ai/` 地址的模型行,`fetch_opencode()` 的 `<tr>/<td>` 解析拿不到任何行。
|
||||
|
||||
**修法**:改为优先读官方 models 接口(**无需鉴权**,实测不带 token 也 200):
|
||||
|
||||
```
|
||||
GET https://opencode.ai/inference/go/v1/models # 与 /zen/go/v1/models 同源同内容
|
||||
```
|
||||
|
||||
每条模型自带 `id` / `name` / `type` / `api{chat-completions,responses,messages,generate-content}` /
|
||||
`recommended_api` / `limit{context,output}` / `cost.text.*.price`(都为 0 = 免费)/ `go.limited_regions`。
|
||||
脚本据此推导协议线、免费标记、地区限制,**HTML 表解析降级为兜底**(接口不可用才走)。
|
||||
|
||||
**同步结果**(2026-11-19 08:02 首次落盘):
|
||||
|
||||
| 动作 | 内容 |
|
||||
|---|---|
|
||||
| 删除 | `opencode/mimo-v2.5`、`opencode/mimo-v2.5-pro`(上游已被 V2.6 取代,文档也不再收录)|
|
||||
| 上下文 | `hy4-flash-free` → 1,048,576 / 65,536;`qwen4-max` → 1,000,000 / 262,144 |
|
||||
| 跳过 | `gemini-4-argon`(只有 generate-content 线);`beam-free`、`muse-spark-1.2/1.3-contributor`(`go.limited_regions`,与旧硬编码名单一致)|
|
||||
|
||||
落盘后网关 28 个模型、`/healthz` 200,`hot_reload` 自动生效未重启;再跑一次输出「无漂移」。
|
||||
`sync_onemin.py` 同步验证通过(49 接口 / 43 配置 / 跳过重名 6)。
|
||||
|
||||
---
|
||||
|
||||
## 2026-10-31 · 新增 1min.AI 供应商(43 个模型)
|
||||
|
||||
老板:「查看 https://docs.1min.ai/docs/api/openai-compatible 文档,把 1min 供应商加入 ai 网关项目里」。
|
||||
@@ -89,10 +124,10 @@ FTS5(当前 400 行无感)、echarts 按需引入(收益 < 风险)。
|
||||
|
||||
### ① 应用数据每日备份(新增)
|
||||
此前每日任务只做「进程巡检」,**完全没备份网关数据**(账号/会话/历史/反馈/调用日志)。
|
||||
- 新增 `/root/dsh/security/backup-app-data.sh`:
|
||||
- 新增 `<运维脚本目录>/backup-app-data.sh`:
|
||||
- `calllog.db` 用 **`VACUUM INTO` 做一致性快照**(不锁业务读写,比 `cp` 安全)
|
||||
- 账号/会话/历史/反馈/agents.yaml/gateway.yaml/`.env` 一并打包
|
||||
- 打包 → `/root/dsh/security/backups/app/app-data-YYYY-MM-DD.tar.gz`,权限 600,**保留 14 份**
|
||||
- 打包 → `<备份目录>/app-data-YYYY-MM-DD.tar.gz`,权限 600,**保留 14 份**
|
||||
- 新增 systemd 定时器 `dsh-gateway-backup.timer`:**每天 03:30**(在 03:00 巡检之后);
|
||||
实测触发 `status=0/SUCCESS`,首份备份 6.7 MB。
|
||||
|
||||
@@ -500,9 +535,9 @@ token 正常(输入 41 / 输出 12 / 推理 12);成员视角只看到自
|
||||
|
||||
老板:「旧托管的都删了,代码,文档相关的都去掉」。
|
||||
|
||||
- **远端**:三个项目(`api-gateway` / `QwenPawChat` / `QwenPawChatWeChat`)都删掉 `origin`
|
||||
- **远端**:三个项目(`xiaoyin-gateway` / `QwenPawChat` / `QwenPawChatWeChat`)都删掉 `origin`
|
||||
(旧托管的仓库地址)—— 现在只留 `gitea` 一个远端。
|
||||
- **脚本**:旧的推送脚本移除(归档到 `/root/.trash/2026-10-12-retire-cleanup/`,
|
||||
- **脚本**:旧的推送脚本移除(归档到 `/root/.trash/<归档>/`,
|
||||
含 `MANIFEST.md`;内容仍可从 git 历史取回);`scripts/push_gitea.sh` 的注释里也去掉了旧托管表述。
|
||||
- **文档**:`README.md` 发布纪律段、`docs/agents-dev-plan.md` 里的旧托管表述改成 Gitea(或直接删掉)。
|
||||
- **历史条目**:按要求**一并清掉** —— CHANGELOG / MEMORY / 日记 / digest Sources 里的旧托管字样全部去掉,不再保留。
|
||||
@@ -512,7 +547,7 @@ token 正常(输入 41 / 输出 12 / 推理 12);成员视角只看到自
|
||||
|
||||
老板:「统一成 main,都默认 main 分支」。
|
||||
|
||||
- **api-gateway**:本地分支 `master` → `main`(`git branch -m master main`);Gitea 侧推上 `main`
|
||||
- **xiaoyin-gateway**:本地分支 `master` → `main`(`git branch -m master main`);Gitea 侧推上 `main`
|
||||
后把仓库默认分支改成 `main`、删掉旧的 `master` 分支。
|
||||
- **QwenPawChat / QwenPawChatWeChat**:本来就是 `main`,无需改(三个项目至此一致)。
|
||||
- **本机 git** 设 `init.defaultBranch = main` —— 以后**新建**仓库默认就是 `main`。
|
||||
@@ -538,12 +573,12 @@ token 正常(输入 41 / 输出 12 / 推理 12);成员视角只看到自
|
||||
|
||||
- **新增 `scripts/push_gitea.sh`**:与旧推送脚本同一套安全口径(一次性带凭据内嵌 URL;
|
||||
不带密码退出 2 / 工作区不干净退出 3 / 推完核对「远端 = 本地」/ 复查 `.git/config` 无明文;
|
||||
**密码不内置进任何文件**),只是目标换成 `https://git.wangjinding.com/Jidekin/api-gateway.git`。
|
||||
**密码不内置进任何文件**),只是目标换成 `https://git.wangjinding.com/Jidekin/xiaoyin-gateway.git`。
|
||||
- **旧的推送脚本已停用并移除**(不再使用)。
|
||||
- **`README.md`**「版本号与发布纪律 → 发布流程」一节:推送目标改为 `推 Gitea`。
|
||||
- **背景**:旧托管的凭据已实测失效(推送与 `ls-remote` 都回 `Repository Not Found.`);同期老板起了自建 Gitea
|
||||
(容器 `1Panel-gitea-CjQz`,`commitgo/gitea-ee:27.3.8`,公网 `https://git.wangjinding.com`),
|
||||
三个项目(`api-gateway` / `QwenPawChat` / `QwenPawChatWeChat`)都已建 **private** 仓库并推了**全量历史**。
|
||||
三个项目(`xiaoyin-gateway` / `QwenPawChat` / `QwenPawChatWeChat`)都已建 **private** 仓库并推了**全量历史**。
|
||||
- **remote 布局**:三个项目只留 `gitea` 一个远端(旧的 `origin` 已删除)。
|
||||
- **待办**:若要免密自动推送,可在 Gitea 建 API token(需老板同意;本次没擅自建)。
|
||||
|
||||
@@ -656,7 +691,7 @@ token 正常(输入 41 / 输出 12 / 推理 12);成员视角只看到自
|
||||
(切到 `agnes/agnes-3.0-flash` 报 401「无效的令牌」)。走网关的 `wangjinding` 正常
|
||||
(网关侧 Agnes Key 是好的)。要用 Agnes 直连需先修 Key。
|
||||
|
||||
**上线**:`supervisorctl restart api-gateway:api-gateway_00` + `npm run build`;
|
||||
**上线**:`supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` + `npm run build`;
|
||||
线上 `version=2.6.0`、入口 `index-BQYagb1Q.js`、Agents chunk `Agents-CN_agann.js`;
|
||||
真机验证:下拉 112 项 / 7 组 → 选 `wjd` → UI 显示 `wjd` → 磁盘 `agent.json`
|
||||
`{"provider_id":"wangjinding","model":"wjd"}` → 引擎回读一致 → 列表页同步。
|
||||
@@ -1019,7 +1054,7 @@ Prometheus:api_gateway_tokens_cached_total 1920 / api_gateway_tokens_reasoning
|
||||
- `scripts/sync_models.py`:新增 `fetch_models_dev()`、`fetch_agnes_context()`(逐模型页解析「限制与价格」表),`diff()` 产出 `ctx_drift`,`apply_plan` 走 `_set_context`(块内改值、保留行尾注释、幂等),`verify()` 回读校验,报告显示漂移;`_DRIFT_KEYS` 与 `plan_is_empty` 认 `ctx_set`。
|
||||
- 测试 **201 passed / 0 failed**(新增 3 个),`ci_check.sh` 全绿。
|
||||
|
||||
**上线**:`supervisorctl restart api-gateway:api-gateway_00`(pid 3492804)→ 实测 `/v1/models` 45 个模型、**38 个带 `context_window`**(含 `wjd` 别名继承 = 1,000,000 / 384,000),图片/视频模型正确为 0;health 200。代码已推远端(`08a4aee`,远端 = 本地)。
|
||||
**上线**:`supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`(pid 3492804)→ 实测 `/v1/models` 45 个模型、**38 个带 `context_window`**(含 `wjd` 别名继承 = 1,000,000 / 384,000),图片/视频模型正确为 0;health 200。代码已推远端(`08a4aee`,远端 = 本地)。
|
||||
|
||||
## 2026-09-24 · 修「QwenPaw 缓存命中率恒 0」:流式 usage 丢掉 `prompt_tokens_details`
|
||||
|
||||
@@ -1063,7 +1098,7 @@ Prometheus:api_gateway_tokens_cached_total 1920 / api_gateway_tokens_reasoning
|
||||
|
||||
### ① 删除 `opencode/deepseek-flash` / `opencode/omen-alpha`
|
||||
- 此前在 `PROTECTED` 名单里护着(上游在服务、官方文档表未收录,怕收录滞后删错);老板拍板以上游文档为准 → **名单清空**(机制保留:以后要临时护住某个 id 在此登记即可;被别名 / media 引用的 id 本来就有独立保护)。
|
||||
- `--apply` 落盘删除,opencode 网关 35 → **33 = 文档 33**(Agnes 10 = 10,无漂移);两个模型块原文归档到 `/root/.trash/2026-09-24-opencode-models-doc-sync/removed-model-blocks.yaml`。
|
||||
- `--apply` 落盘删除,opencode 网关 35 → **33 = 文档 33**(Agnes 10 = 10,无漂移);两个模型块原文归档到 `/root/.trash/<归档>/removed-model-blocks.yaml`。
|
||||
- 线上确证:`hot_reload` 生效,`/models` 已不含这两个 id(总数 47 → 45),Agnes 的免费 / 限时免费标注不受影响。
|
||||
- 顺手修一个删块 bug(本次实测踩到):`_find_model_blocks()` 用「下一个 `- id` 行」当块尾,会把**紧贴下一个模型的分组标题注释**(本文件惯例:`# ── …` 写在组里第一个模型上方;同步自己写的「官方文档新增」标记同理)一起吞掉 —— 删 `deepseek-flash` 时连带删了 `# ── Anthropic Messages 线(文档主推这条)`。现改为块尾只收口到「块头注释」之前(`_block_end` + `_BLOCK_HEADER_RE`),标题已恢复,回归用例 `test_remove_block_keeps_next_group_header_comment` 钉住。
|
||||
- 测试 **196 passed / 0 failed**。
|
||||
@@ -1073,7 +1108,7 @@ Prometheus:api_gateway_tokens_cached_total 1920 / api_gateway_tokens_reasoning
|
||||
`ecb99e6 → afd2f69 → 16d973c`,**远端 `master` tip = 本地 HEAD**,`.git/config` 无 token。
|
||||
|
||||
### ③ 立「上生产必须同步推远端」规则(老板硬性要求)
|
||||
- `README.md` 新增段落:凡**重启上线生产**(`supervisorctl restart api-gateway:api-gateway_00`)或 **`npm run build` 覆盖 `frontend/dist`** 的代码改动,验证通过后**必须**推远端;顺序=改代码 → 测试/CI → 上线 → 确证线上生效 → commit → push;纯注释/配置靠热重载生效的也照推。唯一原则:**线上跑着的代码 = 仓库里的代码**。
|
||||
- `README.md` 新增段落:凡**重启上线生产**(`supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`)或 **`npm run build` 覆盖 `frontend/dist`** 的代码改动,验证通过后**必须**推远端;顺序=改代码 → 测试/CI → 上线 → 确证线上生效 → commit → push;纯注释/配置靠热重载生效的也照推。唯一原则:**线上跑着的代码 = 仓库里的代码**。
|
||||
- 新增推送脚本:一次性带凭据内嵌 URL 推送,推完自动核对「远端 = 本地」并复查 `.git/config` 无凭据;无凭据退出 2、工作区不干净退出 3;**脚本内不内置凭据**(凭据只在 `MEMORY.md`)。
|
||||
|
||||
## 2026-09-24 · Agnes 免费 / 限时免费标注 + 免费标签间距对齐
|
||||
@@ -1098,7 +1133,7 @@ Prometheus:api_gateway_tokens_cached_total 1920 / api_gateway_tokens_reasoning
|
||||
|
||||
### 上线
|
||||
- 配置:`--apply` 落盘(备份 `data/gateway.yaml.bak`,权限 600,回读校验通过),`hot_reload` 自动生效。
|
||||
- 后端:`supervisorctl restart api-gateway:api-gateway_00`(pid 3465113,health 200)。
|
||||
- 后端:`supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`(pid 3465113,health 200)。
|
||||
- 前端:`npm run build` 覆盖 `frontend/dist`,线上 `/web` 已换 `index-CkVhRx-u.js` / `Models-RN5bN2Hd.js`(旧 chunk 404),入口包里能查到「限时免费」。
|
||||
- 实测 `/v1/models` 载荷:Agnes 6 个免费 + `agnes-video-2.5-flash` 限时免费 + 3 个付费档无标注;`space-bunny-free` 免费标注不受影响。
|
||||
|
||||
@@ -1199,7 +1234,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
- **README**:供应商表模型数 17 → 35、模型清单小节按「线 + 免费」重写、三线直传小节数字同步。
|
||||
|
||||
### 踩坑记录(下次别再犯)
|
||||
- 探测上游必须带**专属 UA**(`api-gateway/2.4.0 (jakon opencode-go)`):用 python urllib 的默认 UA
|
||||
- 探测上游必须带**专属 UA**(`xiaoyin-gateway/2.4.0 (jakon opencode-go)`):用 python urllib 的默认 UA
|
||||
会被 Cloudflare 拦成 `403 error code: 1010`,看起来像"模型不可用",其实是 UA 被 ban。
|
||||
|
||||
### 验证
|
||||
@@ -1348,7 +1383,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
是对的。
|
||||
|
||||
### 上线与验证
|
||||
- 后端 `supervisorctl restart api-gateway:api-gateway_00`;前端 `npm run build` 覆盖
|
||||
- 后端 `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`;前端 `npm run build` 覆盖
|
||||
`frontend/dist`(网关 `StaticFiles` 直接挂载)→ 线上入口 **`index-Bf3pWvHR.js`**。
|
||||
- 生产验证:`/healthz` 200、登录页 + 中英切换(真浏览器)、`/health/agnes` 无凭据 401、
|
||||
`GET /` 导航无 `docs`、env 值校验 400 且文件未变、水印图下载 200、未登记 video_id 轮询
|
||||
@@ -1373,7 +1408,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
- 单测 173 passed / 0 failed(`test_conversation_id_isolated_per_account`、
|
||||
`test_api_conversation_id_flows_to_session_header`、`test_non_ascii_...` 已更新为「不传→非
|
||||
None 稳定会话」新语义)
|
||||
- 生产已重启(`api-gateway:api-gateway_00`,pid 1488509),`/healthz` ok、无回归
|
||||
- 生产已重启(`xiaoyin-gateway:xiaoyin-gateway_00`,pid 1488509),`/healthz` ok、无回归
|
||||
- **真实的 `cached_tokens>0` 演示暂被挡**:opencode 免费 5 小时额度仍锁定(上游 429),待额度
|
||||
重置(约 3h)后可再实测两通相同前缀调用确认命中。
|
||||
|
||||
@@ -1412,13 +1447,13 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
### 验证
|
||||
- 后端单测:**165 passed / 0 failed**(删 6 个路由引擎用例、改写 10 个、新增 2 个)。
|
||||
- 前端:`vue-tsc --noEmit` 0 错、`npm run build` 成功、`check-i18n` 中英 699/699 对称。
|
||||
- 生产**未动**:后端需 `supervisorctl restart api-gateway:api-gateway_00`(踢会话),
|
||||
- 生产**未动**:后端需 `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`(踢会话),
|
||||
前端 dist 覆盖需老板点头。
|
||||
|
||||
### 上线(老板批准重启,2026-09-18 15:16)
|
||||
- 前端 `npm run build` 产物覆盖 `frontend/dist`(新入口 `index-CWUVm0px.js`,公网
|
||||
`https://api.wangjinding.com/web/...` 已服务新入口、旧入口 404)。
|
||||
- 后端 `supervisorctl restart api-gateway:api-gateway_00` → 新 pid,127.0.0.1:8808 正常,
|
||||
`http://127.0.0.1:8808/web/...` 已服务新入口、旧入口 404)。
|
||||
- 后端 `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` → 新 pid,127.0.0.1:8808 正常,
|
||||
`/health` 200、启动日志「已加载 3 供应商」。
|
||||
- **代码仍未提交 git**(老板明确要求"先别提交")。
|
||||
|
||||
@@ -1450,7 +1485,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
(chat/completions 7106ms、responses 2014ms、messages 1360ms)。
|
||||
|
||||
|
||||
按轮次记录 api-gateway 的修复与优化(README 侧重能力/配置说明,这里侧重每轮的改动、排查、验证与上线)。
|
||||
按轮次记录 xiaoyin-gateway 的修复与优化(README 侧重能力/配置说明,这里侧重每轮的改动、排查、验证与上线)。
|
||||
|
||||
---
|
||||
|
||||
@@ -1505,7 +1540,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
- 两个账号(admin / liunuanshu)用**同一个** `conversation_id` 各调 `kimi-k3` → **都 200**(派生后的值被上游正常接受);
|
||||
- 缓存归属实验(直连上游、真实 key,prompt≈940 token):见上文**结论更正**的三组数据。
|
||||
- 文档:README 补「取值限制 / 派生规则 / OpenAI SDK 用 extra_body」+ 缓存结论更正;本 CHANGELOG 记一轮。
|
||||
- **上线状态**:含 Python 代码改动 → 需 `supervisorctl restart api-gateway:api-gateway_00` 才生效(会踢网页会话),
|
||||
- **上线状态**:含 Python 代码改动 → 需 `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` 才生效(会踢网页会话),
|
||||
**待老板批准**;本轮无前端改动,不需要 `npm run build`。
|
||||
|
||||
---
|
||||
@@ -1521,7 +1556,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
(否则"200"可能只是上游忽略图片块,无法证明它真的看了图)。
|
||||
- **颜色判别(64×64 纯色 PNG,红 `220,30,30` / 蓝 `30,60,220` / 绿 `30,200,80`)**:`deepseek-v4.1-flash`
|
||||
**红/蓝/绿三色全部答对**,与已标视觉的 `deepseek-v4-flash-vision-exp` 表现完全一致。
|
||||
- **过网关复测**(公网 `https://api.wangjinding.com`):直连 `deepseek-v4.1-flash` 三色全对;路由别名 `wjd`
|
||||
- **过网关复测**(公网 `http://127.0.0.1:8808`):直连 `deepseek-v4.1-flash` 三色全对;路由别名 `wjd`
|
||||
带图请求被排到视觉模型、答对「红色」。
|
||||
- **踩坑(判定方法的坑)**:它是**推理模型**,`max_tokens` 给小了(首次探针用 40)时 token 全被
|
||||
`reasoning_content` 吃光、`content` 返回空串——**看起来像"只收图不回答"**。复测放大到 300+ 才拿到答案。
|
||||
@@ -1575,7 +1610,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
- **单测**:**168 passed / 0 failed**(+10:参数解析/白名单拦截/真配置锁定/强制覆盖/自动修正重发/不无限重试/配置冲突/流式修正/测速文案/面板保留 params);前端 `vue-tsc --noEmit` 通过、`check:i18n` 726/726 对称、`check:svg` 通过、`npm run build` 成功(在副本内构建,未覆盖生产 dist)。
|
||||
|
||||
### 上线(待老板批准)
|
||||
- 含 Python 代码改动(`config` / `adapters` / `main` / `settings`)→ 需 `supervisorctl restart api-gateway:api-gateway_00` 才生效(会踢网页会话)。
|
||||
- 含 Python 代码改动(`config` / `adapters` / `main` / `settings`)→ 需 `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` 才生效(会踢网页会话)。
|
||||
- 前端需 `npm run build` 覆盖 `frontend/dist`(挂锁/提示条才会出现在线上)。
|
||||
- 远端推送新增提交。
|
||||
|
||||
@@ -1612,7 +1647,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
### 改动
|
||||
- **`data/.env`**:新增 `OPENCODE_API_KEY`(600、gitignored)。
|
||||
- **`data/gateway.yaml`**:
|
||||
- 新增 `providers.opencode`:`base_url https://opencode.ai/zen/go/v1`、`token_env OPENCODE_API_KEY`、`requires_session_header: true`、`extra_headers.User-Agent: api-gateway/2.4.0 (jakon opencode-go)`,收录 **17 个**文本模型(`glm-5.3-flash/5.3/5.2/5.1`、`kimi-k3/k2.7-code/k2.6`、`longcat-2.0`、`deepseek-v4-pro/v4-flash/flash/v4.1-flash/v4-flash-vision-exp(视觉)`、`mimo-v2.5/v2.5-pro`、`hy4-preview/hy3`)。
|
||||
- 新增 `providers.opencode`:`base_url https://opencode.ai/zen/go/v1`、`token_env OPENCODE_API_KEY`、`requires_session_header: true`、`extra_headers.User-Agent: xiaoyin-gateway/2.4.0 (jakon opencode-go)`,收录 **17 个**文本模型(`glm-5.3-flash/5.3/5.2/5.1`、`kimi-k3/k2.7-code/k2.6`、`longcat-2.0`、`deepseek-v4-pro/v4-flash/flash/v4.1-flash/v4-flash-vision-exp(视觉)`、`mimo-v2.5/v2.5-pro`、`hy4-preview/hy3`)。
|
||||
- `routes.wjd` 追加这 17 个(wjd 链 = 20 个文本模型)。
|
||||
- 未收录:`glm-5`、`kimi-k2.5`、`hy3-preview`(上游实测 400 Model is unavailable);`/messages`、`/responses` 线模型未接入(适配器不含该契约)。
|
||||
- **`app/config.py`**:`ProviderConfig` 加 `requires_session_header` 字段并解析。
|
||||
@@ -1632,7 +1667,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
- 单测:**155 passed / 0 failed**;前端 `vue-tsc --noEmit` 通过。
|
||||
|
||||
### 上线(待老板批准)
|
||||
- 含 Python 代码改动(config / adapters / settings)→ 需 `supervisorctl restart api-gateway:api-gateway_00` 才生效(会踢网页会话);纯 yaml 的 hot_reload 只重载供应商/模型定义,`requires_session_header` 字段与注入逻辑要重启后代码才认。
|
||||
- 含 Python 代码改动(config / adapters / settings)→ 需 `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` 才生效(会踢网页会话);纯 yaml 的 hot_reload 只重载供应商/模型定义,`requires_session_header` 字段与注入逻辑要重启后代码才认。
|
||||
- 前端 build 覆盖 `dist`(纯前端上线动作)与远端推送待老板确认。
|
||||
|
||||
**一句话**:老板拍板——**现有 + 以后新增的每一个文本模型都必须加入 `routes.wjd` 兜底链**。本次把 `agnes-2.5-flash` 补进 wjd,并把这句作为长期规则写入 MEMORY / README / CHANGELOG,供后续新增模型照做。
|
||||
@@ -1694,7 +1729,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
- 单测 **155 passed / 0 failed**;全项目 grep `智谱|bigmodel|GLM|cogview|cogvideox|ufileos|ZHIPU|zhipu|video_style|_ZHIPU` 除 CHANGELOG 历史外**全部清零**。
|
||||
- 前端 `npm run build` 过(typecheck + i18n 对称),新入口 `index-BynIw5Ue.js`。
|
||||
- 配置校验:providers `[agnes,volc_engine]`、模型 `agnes[3] + volc[1]`、`routes.wjd` 2 项、下载白名单仅 Agnes。
|
||||
- `supervisorctl restart api-gateway:api-gateway_00` 上线(`description`/适配器/校验等属代码改动,需重启)。
|
||||
- `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` 上线(`description`/适配器/校验等属代码改动,需重启)。
|
||||
|
||||
---
|
||||
|
||||
@@ -1745,7 +1780,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
### 验证
|
||||
- 单测:新增/修正 bigmodel 媒体契约断言、视频轮询必经 `?model=`(现两家视频供应商)、配置往返含新 media 键 → **155 passed / 0 failed**;前端 `npm run build` 过(typecheck + i18n 对称),新入口 `index-CxdHy_Sw.js`。
|
||||
- 真机隔离(uvicorn:8899 临时 users/history,连真实智谱):`/v1/models` 列出 8 个智谱模型;图像 → 200 `data[].url`;视频创建 → `video_id`+`task_status:PROCESSING`;轮询 → `status:processing`;非法参数(`mode=keyframe`)→ 400 干净拒绝。
|
||||
- 上线:`supervisorctl restart api-gateway:api-gateway_00`(代码改动需重启),前端 dist 已 build 覆盖。
|
||||
- 上线:`supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`(代码改动需重启),前端 dist 已 build 覆盖。
|
||||
- **补「下载白名单」**:上线后老板实测智谱图/视频下载报「不在白名单:maas-watermark-prod-new.cn-wlcb.ufileos.com」。已确认智谱图+视频产物**同一 CDN 域名**(实测视频 `SUCCESS` 结果 url 同域),在 `download.allowed_hosts` 补 `maas-watermark-prod-new.cn-wlcb.ufileos.com`(精确项 + 子域匹配,不泛放整个 `ufileos.com`;`evilufileos.com`、后缀撞车域名仍拒绝)。纯配置改动,`hot_reload` ≤15s 自动生效免重启。已用隔离服务器实测:智谱图经 `/v1/media/download` 拉回 200 + 有效 JPEG 97KB。
|
||||
|
||||
---
|
||||
@@ -1828,7 +1863,7 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
- `test_feedback_withdraw_only_when_pending`:feedback 撤回逻辑,非本次改动范围。
|
||||
|
||||
### 部署
|
||||
- `supervisorctl restart api-gateway:api-gateway_00`。
|
||||
- `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`。
|
||||
- 重启前验证文件已就位:yaml `safe_load` 通过、`providers = [agnes, b_ai, volc_engine, opencode]`、opencode 4 个模型。
|
||||
- 上线后校验:新 pid 61457、healthz `{"status":"ok"}`、`/v1/models` 200 且含 opencode 4 个免费模型、无凭证/错 key 仍 401、真实 chat 调用 `provider=opencode` 返回 200。
|
||||
|
||||
@@ -1971,4 +2006,4 @@ dict 即使一个模型都没变也是**真值** → 每天无漂移也重写一
|
||||
- 项目此前**不是 git 仓库**:`git init` 建库、设提交身份、首次提交(**91 个源码文件**)。
|
||||
- **`.gitignore` 补充**忽略 `node_modules/`、`frontend/node_modules/`、`frontend/dist/`、`dist/`、`*.egg-info/`、`.DS_Store` —— 否则 `git add -A` 会把 **15342 个 node_modules 文件**塞进仓库。
|
||||
- **推送前安全审计**:确认 `.env`、`data/users.json`、`data/history.json`、`data/feedback.json`、`data/feedback_media/` 全部被忽略、无任何密钥/隐私入库(仅无密钥的 `.env.example` 模板随库)。
|
||||
- **远程**:远端仓库 `Jidekin/api-gateway`,分支 `master`(2026-10-12 起统一为 `main`),首推成功(远端 `HEAD=6cc65ff` 与本地一致)。`origin` 配为不含凭据的干净地址,**凭据不写入 `.git/config`**;后续推送临时带凭据。
|
||||
- **远程**:远端仓库 `Jidekin/xiaoyin-gateway`,分支 `master`(2026-10-12 起统一为 `main`),首推成功(远端 `HEAD=6cc65ff` 与本地一致)。`origin` 配为不含凭据的干净地址,**凭据不写入 `.git/config`**;后续推送临时带凭据。
|
||||
@@ -1,4 +1,4 @@
|
||||
# API Gateway 快捷命令
|
||||
# 小银网关 快捷命令
|
||||
# Windows 若无 make,可手动执行对应命令;或装 https://chocolatey.org/packages/make
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
@@ -8,7 +8,7 @@ PORT ?= 8808
|
||||
.PHONY: help install run test lint clean
|
||||
|
||||
help: ## 显示帮助
|
||||
@echo "api-gateway 常用命令:"
|
||||
@echo "小银网关 常用命令:"
|
||||
@echo " make install 安装依赖"
|
||||
@echo " make run 本地启动(端口 $(PORT))"
|
||||
@echo " make test 跑单元测试(不依赖真实上游)"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# API Gateway
|
||||
# 小银网关
|
||||
|
||||
统一多供应商 LLM 接入网关,纯后端 FastAPI,配置驱动。支持 **Agnes AI**、**OpenCode Go**、**Dots AI(小红书)** 三个供应商,全部走 OpenAI 兼容协议。v2.4 已集成熔断、限流、图像/视频、指标、成本估算、热加载、测试等完整能力。
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
## 架构
|
||||
|
||||
```
|
||||
api-gateway/
|
||||
xiaoyin-gateway/
|
||||
├── data/gateway.yaml # 默认运行时配置(run.py 读取,hot_reload 开)
|
||||
├── app/
|
||||
│ ├── config.py # YAML 加载 → dataclass(供应商/模型/协议线/鉴权/熔断/可观测/定价)
|
||||
@@ -486,7 +486,7 @@ pricing: # 人民币/百万 token,用于估算成本
|
||||
## 启动
|
||||
|
||||
```bash
|
||||
cd api-gateway
|
||||
cd xiaoyin-gateway
|
||||
pip install -r requirements.txt
|
||||
python run.py # 默认读 data/gateway.yaml,端口 8808
|
||||
```
|
||||
@@ -611,7 +611,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
## 前端 Web 控制台
|
||||
|
||||
- 前端由网关托管:`frontend/dist` 由网关挂在 `/web`(同源、公开无密钥),浏览入口
|
||||
`https://api.wangjinding.com/web/`(哈希路由,默认 `/web/#/dashboard`,未登录跳 `/web/#/login`)。
|
||||
`http://127.0.0.1:8808/web/`(哈希路由,默认 `/web/#/dashboard`,未登录跳 `/web/#/login`)。
|
||||
- 登录:POST `/auth/login` 用原始 key 换会话(`sess-` 前缀、TTL 滑动过期 86400s),
|
||||
前端不持原始 key;登出 `/auth/logout`。
|
||||
- 根路径 `/`:浏览器(`Accept: text/html`)访问自动 307 跳 `/web/`;API 调用(Accept 无
|
||||
@@ -734,7 +734,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
`hint`/`feats` 节点确认为 0、窄屏 `.login-art` 已带 `url(login-banner-*.svg)` 且 `.orb` 为 `display:none`、
|
||||
真实交互(输入框聚焦输入、右上角切换器切到 English 后文案变 `Sign in`)通过;
|
||||
`typecheck` 0 error、`npm run build` 成功(新产物 `index-DG7g6NaW.js` / `Login--E4bzU7N.css` /
|
||||
`login-banner-7rrSIoiP.svg`)。线上 `https://api.wangjinding.com/web/#/login` 已服务新产物
|
||||
`login-banner-7rrSIoiP.svg`)。线上 `http://127.0.0.1:8808/web/#/login` 已服务新产物
|
||||
(公网取 `login-banner-7rrSIoiP.svg` 200 / 7139B),后端零改动、未重启。
|
||||
另修一处小 a11y 问题:`i18n.ts` 只在 `setLocale()` 里写 `<html lang>`,初始化路径漏了,
|
||||
导致 localStorage 存 `en` 的用户 `lang` 一直停在 `zh-CN`;改为模块初始化时也写一次。
|
||||
@@ -745,7 +745,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
不再额外发任何请求。i18n 无改动(那行是直读 `/healthz` 与 `location.origin`,没走 `t()`),
|
||||
无 key 残留。
|
||||
② 整页重做为**三套设计稿**,落在 `design/login-v3/`(该目录 2026-09-13 按老板指示清理归档,未 `rm`,恢复见
|
||||
`/root/.trash/2026-09-13-api-gateway-cleanup/MANIFEST.md`):`d1.html` 极简白卡(浅底单列居中卡)、
|
||||
`/root/.trash/<归档>/MANIFEST.md`):`d1.html` 极简白卡(浅底单列居中卡)、
|
||||
`d2.html` 深色玻璃卡(深色科技底 + 毛玻璃)、`d3.html` 通栏一体(左侧主题色品牌面 + 右侧白色
|
||||
表单面,整屏无卡片框);`h.html` 是「iframe 定尺预览机」(每条 `文件:宽x高x缩放`,按指定视口
|
||||
真实渲染再 scale 进浏览器窗口),出稿对照图都用它。三套各含桌面端与手机端形态、token 口径与
|
||||
@@ -769,17 +769,17 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
`index-BWFYxQdn.js`);用同源探针 `probe.html`(原 `design/login-v3/probe.html`,已随设计稿目录归档)逐格量过 **3 主题 × 7 分辨率**
|
||||
(1280×720 / 1024×768 / 1440×900 / 1920×1080 / 390×844 / 360×640 / 414×896)共 21 组:
|
||||
全部 `ovX=ovY=0` 无溢出、卡片 440×444 居中、三主题的卡片 / 按钮 / logo / 聚焦环颜色各自正确、
|
||||
旧结构节点 0;英文单独验过(`API Gateway Console` / `Username` / `Password` / `Sign in`、
|
||||
旧结构节点 0;英文单独验过(`Xiaoyin Gateway Console` / `Username` / `Password` / `Sign in`、
|
||||
`<html lang="en">`、卡片 434 高同样无溢出);真机交互验过语言切换(右上角胶囊 → English →
|
||||
文案与 `<html lang>` 同步)与空提交报错(卡片内红色提示、卡片自动增高不溢出)。
|
||||
线上 `https://api.wangjinding.com/web/#/login` 已服务新产物(`Login-CazImMjd.css` 200 / 4426B,
|
||||
线上 `http://127.0.0.1:8808/web/#/login` 已服务新产物(`Login-CazImMjd.css` 200 / 4426B,
|
||||
旧 `Login-BMLIXfzt.css` 404),后端零改动、未重启。
|
||||
> 探针为什么挂在 vite dev 上:CSP 里有 `frame-ancestors 'none'`(安全项,不为此放宽),
|
||||
> `/web` 下的页面不能被 iframe 嵌(`__probe.html` 放 `/web` 里量不到东西),所以改用
|
||||
> **无 CSP 的 vite dev(`--port 5199`)**同源托管探针:同源才能读 iframe 的 DOM、才能直接写
|
||||
> `localStorage` 切主题/语言,再逐格量溢出与计算样式。探针跑完即从 `frontend/public/` 删除
|
||||
> (否则会被 build 拷进 `dist`),只留 `design/login-v3/probe.html` 这一份;该探针与三套设计稿
|
||||
> 已于 2026-09-13 一并归档到 `/root/.trash/2026-09-13-api-gateway-cleanup/`(未 `rm`,可恢复)。
|
||||
> 已于 2026-09-13 一并归档到 `/root/.trash/<归档>/`(未 `rm`,可恢复)。
|
||||
- 修 data URI 下载的 CSP 坑:产物是 `data:` 时原实现用 `fetch(dataURI)` 取字节,而 CSP
|
||||
`connect-src 'self'` 会把它拦掉(上游以 base64 直回图片时「下载」必失败,本地 vite preview
|
||||
无 CSP 时看不出来)。改为本地 base64 解码 `dataUriToBlob()`,不触网、也不动 CSP 白名单。
|
||||
@@ -844,7 +844,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 来源:老板要求全站体检(前端 8 分辨率 × 3 主题 × 中英 × 11 页 + 后端 130 单测),
|
||||
> 体检发现的问题**全部核实属实**后按 P0 → P1 → P2 顺序修完。
|
||||
> (注:README 的轮次序列主线是后端修复轮(第九~十六轮),媒体产物下载与前端整体重设计两轮未单独编号;
|
||||
> 本轮即「体检发现项修复」轮,内部代号 `fix18`,备份在 `/root/.trash/2026-09-13-fix18-backup/`。)
|
||||
> 本轮即「体检发现项修复」轮,内部代号 `fix18`,备份在 `/root/.trash/<归档>/`。)
|
||||
>
|
||||
> - **P0 全局类名撞车(真 Bug,肉眼可见)**:`style.css` 里有个全局进度条样式
|
||||
> `.bar { height: 5px; overflow: hidden }`,而**对话页输入区那一行按钮的容器 class 也叫 `bar`** ——
|
||||
@@ -886,13 +886,13 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 改为 `repeat(2, minmax(0, 1fr))`(手机端原来的两列覆盖也随之删掉,规则收敛到 `style.css` 一处),
|
||||
> 每格 141px(可用 127px):中英标签全部单行、三格等高(zh 49px / en 46px)、右边界距卡片 15px。
|
||||
> 实测 1280/1440/1024 桌面 + 390 手机 × 中英 7 组全部 `折行=no`、横向溢出 0。
|
||||
> - 上线与复核(2026-09-13 17:13 老板批准重启):`supervisorctl restart api-gateway:api-gateway_00`;
|
||||
> - 上线与复核(2026-09-13 17:13 老板批准重启):`supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`;
|
||||
> 线上 `/healthz` 200、非对象 JSON 400、错误密码 401、无凭证 401;线上 CSS 内含 `.meter{height:5px}`、
|
||||
> `.set-row>.lb{...flex:0 0 auto}`、手机端 `min-height:34px`,旧的 `.bar{height:5px` 已消失;
|
||||
> 专项探针 24 组合(B/A/C 主题 × 1280/390 × 6 页)横向溢出全 0,输入区 34/86px、张数输入 51px、
|
||||
> 手机触控目标 34px、字号 11.5px,`.acc-sub` 仅手机显示、操作按钮 3 个全在屏内。
|
||||
> 收尾(同日傍晚,老板「收掉、清掉、改」):临时体检环境(后端 8899 + vite dev 5199 + `gwcheck.vite.config.mts`)
|
||||
> 已停进程并归档到 `/root/.trash/2026-09-13-fix18-cleanup/`(含 MANIFEST.md 与恢复命令);
|
||||
> 已停进程并归档到 `/root/.trash/<归档>/`(含 MANIFEST.md 与恢复命令);
|
||||
> `frontend/dist.bak-0913-0127` 与 4 处 `__pycache__` 同样归档;场景卡改两列后构建并上线
|
||||
> (`index-Gg1BF2WV.js` / `index-DdRZNrpf.css`,纯静态切换、后端零改动未重启);
|
||||
> 顺手补 `.gitignore` 里漏掉的 `.test_history.json`。
|
||||
@@ -1075,7 +1075,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> - 未实测项(如实记):**390px 手机断点没测到** —— 本会话浏览器没有视口控制(试过 Ctrl+缩放压低 CSS 视口无效),故用 `flex-wrap` 兜住「5 颗图标超宽」的最坏情况,建议真机上瞄一眼。
|
||||
>
|
||||
> - **上线(2026-09-13 20:0x,老板批准)**:`npm run build` → 线上现役 `index-BYW9huII.js` / `index-BCEpjaoj.css` / `Users-Ym7Y7v4h.js`(旧 `index-BV89HnWe.js` 已 404);
|
||||
> `supervisorctl restart api-gateway:api-gateway_00`(旧 pid 2102891 → 新 pid 2157737,仍监听 `127.0.0.1:8808`)。
|
||||
> `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00`(旧 pid 2102891 → 新 pid 2157737,仍监听 `127.0.0.1:8808`)。
|
||||
> **本轮有后端改动,重启会清空内存态网页会话 —— 所有人(含 admin)需要重新登录。**
|
||||
> 复核:公网 `/healthz` 200、`/web/` 200 且引用新 hash、新 asset 200(`immutable` 长缓存)与旧 asset 404、
|
||||
> CSP 未放宽、`index.html` 仍 `no-cache`;新端点在线判据 = 无凭证调 `PUT /auth/users/x/disabled` 得 **401**(旧代码是 404)。
|
||||
@@ -1120,7 +1120,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 「跳到」滚动生效(目标卡片 y 4221 → 62)、会话时长改成 45 保存 → 盘上文件立刻更新且生成 `.bak`(权限 600)、
|
||||
> 页面出「已保存并生效」。
|
||||
> - 上线:`npm run build` → 线上现役 `index-T9rUvEqS.js` / `GatewayConfig-Cujt5GjO.js`
|
||||
> (旧 `index-BMd-U-9_.js` 已 404);`supervisorctl restart api-gateway:api-gateway_00` →
|
||||
> (旧 `index-BMd-U-9_.js` 已 404);`supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` →
|
||||
> 新 pid **2102891**(`127.0.0.1:8808`)—— **本轮有后端改动,重启踢掉所有网页会话,需重新登录**。
|
||||
> 随后小修一处文案(`{'{'}"status":"ok"{'}'}` 里花括号写法之间多打了空格,渲染成 `{ "status":"ok" }`,
|
||||
> 与 /health 真实报文不符)→ 再 `npm run build` → 现役 **`index-CladK7BT.js` /
|
||||
@@ -1132,7 +1132,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 线上产物含 `sec-server` / `sec-download` 分区。
|
||||
> 线上逐屏复核没做(当前管理员密码非默认值,小银不掌握、也不去试),面板的浏览器实测以隔离实例为准。
|
||||
> - 收尾:隔离实例 8899 已 kill(线上 8808 未受影响),`/tmp` 残留与临时配置副本归档到
|
||||
> `/root/.trash/2026-09-13-gw23-cleanup/`(含 `MANIFEST.md`),`frontend/public/` 与 `dist/` 无探针残留。
|
||||
> `/root/.trash/<归档>/`(含 `MANIFEST.md`),`frontend/public/` 与 `dist/` 无探针残留。
|
||||
>
|
||||
> - **追加一(同日 19:2x,老板「模型定价去掉」「左侧菜单上下间距缩短一点,让滚动条不要出现」)**
|
||||
> - **侧栏间距收紧**(`layouts/SideNav.vue`):菜单项内边距 `9px→7px`(行高 **36→32px**)、项间距 `2px→1px`、
|
||||
@@ -1161,8 +1161,8 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 生产 `data/` 只读)真浏览器实测:**侧栏 11 项、无「网关配置」**;设置页**无**那颗跳转按钮;
|
||||
> 手敲 `#/gateway-config` **落回 `/dashboard`**。构建产物静态核对:定价块文案仍在(`addPrice` / `h_pricing` /
|
||||
> `输入价` / `输出价` / `list-edit` 均能在产物里找到)→ 功能只是藏起来、没被删。
|
||||
> - 收尾:隔离实例已 kill,两轮残留分别归档 `/root/.trash/2026-09-13-gw25-tweaks-cleanup/` 与
|
||||
> `/root/.trash/2026-09-13-gw26-hide-gwconfig-cleanup/`(各含 `MANIFEST.md`)。
|
||||
> - 收尾:隔离实例已 kill,两轮残留分别归档 `/root/.trash/<归档>/` 与
|
||||
> `/root/.trash/<归档>/`(各含 `MANIFEST.md`)。
|
||||
> - 备注:生产 `data/users.json` 在 19:29 有一次写入,**不是本次验证造成**(隔离实例的账号/配置/历史全走 `/tmp`),
|
||||
> 看字段像线上侧的登录/建 Key 动作。
|
||||
>
|
||||
@@ -1174,7 +1174,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 推算"开始出滚动条"的窗口高从最初的 ~605px、上一版的 ~538px 降到 **~508px**。
|
||||
> - 上线:纯前端 `npm run build` 覆盖 `frontend/dist`(未重启后端,会话没掉)。线上现役
|
||||
> **`index-BV89HnWe.js`** / `MainLayout-BOSEGVwr.css`(`index-BeKWQQGn.js`、`MainLayout-8X3ca3Qa.css` 已 404)。
|
||||
> - 收尾:残留归档 `/root/.trash/2026-09-13-gw27-rail-spacing-cleanup/`(含 `MANIFEST.md`)。
|
||||
> - 收尾:残留归档 `/root/.trash/<归档>/`(含 `MANIFEST.md`)。
|
||||
|
||||
> **第二十二轮(2026-09-13)意见反馈 / 用户反馈 + 侧栏底部清理 + 处理进度**
|
||||
> 来源:老板三点 ——「侧栏菜单左下角那行去掉」「普通用户新增意见反馈,支持上传图片」
|
||||
@@ -1241,7 +1241,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 处理中·已处理 400 / API Key 撤不动 403)。撤回部分在隔离实例复核过接口与真浏览器交互。
|
||||
> - 上线(2026-09-13 18:4x,老板批准「补上说明后直接上线」):`npm run build` → 线上现役
|
||||
> `index-b0LZHsJm.js` / `index-BCEpjaoj.css`(旧 `index-CDcUA_16.js` 已 404);
|
||||
> `supervisorctl restart api-gateway:api-gateway_00` → pid **2055315**(127.0.0.1:8808)——
|
||||
> `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` → pid **2055315**(127.0.0.1:8808)——
|
||||
> **本轮有后端改动,重启会踢掉所有网页会话,需重新登录**。(该次 pid 已被下方追加项的上线覆盖。)
|
||||
> 追加项(老板 18:39「待处理的单子用户可以自己撤回」)代码与隔离实测完成后,老板 18:5x 批准上线:
|
||||
> 再次 `npm run build` + `supervisorctl restart` → 现役 `index-9Whl_Fn4.js`(旧 `index-b0LZHsJm.js` 已 404)、
|
||||
@@ -1259,7 +1259,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 追加项(老板「处理的每个环节都要记录和展示,改好后直接重启上线」)**已上线**:
|
||||
> `npm run build`(先确认 `frontend/public/` 无探针残留)→ 现役 `index-BTllhoyi.js`
|
||||
> (旧 `index-9Whl_Fn4.js` 已 404;`index-BCEpjaoj.css` 哈希未变,本轮无样式改动);
|
||||
> `supervisorctl restart api-gateway:api-gateway_00` → pid **2073622**(`127.0.0.1:8808`)——
|
||||
> `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` → pid **2073622**(`127.0.0.1:8808`)——
|
||||
> **有后端改动,重启踢掉了所有网页会话,需重新登录**。
|
||||
> 复核(全部实测):公网 `/web/` 200 且引用新 hash、`index-BTllhoyi.js` 与
|
||||
> `FeedbackTimeline-CfkAgUmj.js` / `Feedback-DsePxU4t.js` / `FeedbackInbox-D1R_k-8C.js` 全 200、
|
||||
@@ -1268,7 +1268,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> (路由已随重启生效)。**生产 `data/*` 全程只读**(并未往线上写测试反馈)。
|
||||
> 收尾:隔离实例(8899 / vite dev 5199)已 kill,探针 `gwmv23.html` + 临时 vite 配置
|
||||
> `gwcheck23.vite.config.mts` 与 `/tmp/gw23` 已归档到
|
||||
> `/root/.trash/2026-09-13-fix22b-cleanup/`(含 `MANIFEST.md`),`frontend/public/` 已清空、
|
||||
> `/root/.trash/<归档>/`(含 `MANIFEST.md`),`frontend/public/` 已清空、
|
||||
> `dist` 无探针残留。
|
||||
|
||||
> **第二十一轮(2026-09-13)顶栏「铃铛」删除 + 主题下拉点不开(tooltip 套在 dropdown 触发器里)**
|
||||
@@ -1354,7 +1354,7 @@ curl "http://localhost:8808/v1/videos/<video_id>?model=agnes-video-2.5-flash&wai
|
||||
> 窄屏 151~175px,无横向溢出);`vue-tsc` 0 错、`vite build` 通过、后端单测 **137 passed / 0 failed**。
|
||||
> - 上线(2026-09-13 17:44,老板批准):`npm run build` → 线上现役
|
||||
> `index-Yy0kGuVA.js` / `index-DKyqf84q.css` / `Logs-N__ABTKT.js` / `Videos-Bzh1nuOL.js` + `Videos-BVOcHXwL.css`;
|
||||
> `supervisorctl restart api-gateway:api-gateway_00` → pid **1999293**(127.0.0.1:8808)。
|
||||
> `supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00` → pid **1999293**(127.0.0.1:8808)。
|
||||
> 复核:公网 `/web/` 200 且引用新 hash、新旧 asset 分别 200 / 404、`/healthz` 200、CSP 头未放宽;
|
||||
> 拉线上产物实测含胶囊计数与空结果提示(`Logs`)、新版卡片结构(`Videos`)与窄屏缩略拉伸规则(`Videos` CSS)。
|
||||
> 注意:**重启会踢掉所有网页会话,需重新登录**。
|
||||
@@ -1385,10 +1385,10 @@ VERSION = "2.4.0" # ← 只改这一处
|
||||
```
|
||||
改代码 → 跑测试(python tests/test_gateway.py 或 bash scripts/ci_check.sh)
|
||||
→ 纯前端:npm run build(dist 即线上目录)
|
||||
后端/代码:supervisorctl restart api-gateway:api-gateway_00
|
||||
后端/代码:supervisorctl restart xiaoyin-gateway:xiaoyin-gateway_00
|
||||
→ 真机验证(线上 healthz / 页面 / 接口)
|
||||
→ git commit
|
||||
→ 推 Gitea(scripts/push_gitea.sh,仓库 Jidekin/api-gateway 分支 main)
|
||||
→ 推 Gitea(scripts/push_gitea.sh,仓库 Jidekin/xiaoyin-gateway 分支 main)
|
||||
```
|
||||
|
||||
**「只要上生产就必须推」** 是既有硬性规矩:保持"线上跑着的代码 = 仓库里的代码"。**凡是重启上线(后端
|
||||
@@ -1398,9 +1398,9 @@ restart)或 `npm run build` 覆盖 `frontend/dist` 的代码改动,验证通
|
||||
的顺序取凭据(token 是 2026-10-12 建的 Gitea API token,scope `write:repository`);
|
||||
凭据只一次性内嵌进本次推送 URL,**不写 `.git/config`、也不内置进仓库任何文件**;
|
||||
退出码 2=没凭据 / 3=工作区不干净 / 4=推送后远端≠本地 / 5=`.git/config` 出现明文。
|
||||
仓库 `https://git.wangjinding.com/Jidekin/api-gateway.git`、分支 `main`
|
||||
仓库 `https://git.wangjinding.com/Jidekin/xiaoyin-gateway.git`、分支 `main`
|
||||
(`remote` 名就叫 `gitea`)。**三个项目分支已统一为 `main`**
|
||||
(2026-10-12:api-gateway 原 `master` 改名 `main`,Gitea 默认分支同步改、旧 `master` 分支删除)。
|
||||
(2026-10-12:xiaoyin-gateway 原 `master` 改名 `main`,Gitea 默认分支同步改、旧 `master` 分支删除)。
|
||||
|
||||
## 测试
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
"""API Gateway - 统一多供应商 LLM 接入网关"""
|
||||
"""小银网关 - 统一多供应商 LLM 接入网关"""
|
||||
@@ -28,7 +28,7 @@ from app.config import (
|
||||
)
|
||||
from app.models import CHAT_CORE_KEYS, PROTECTED_VIDEO_KEYS, strip_protected
|
||||
|
||||
log = logging.getLogger("api-gateway")
|
||||
log = logging.getLogger("xiaoyin-gateway")
|
||||
|
||||
# ── 上游"某参数只允许取某个值"的报错形态(第二十五轮)──
|
||||
# 各家措辞不同,这里收录已实测到的两类:
|
||||
|
||||
@@ -36,7 +36,7 @@ from typing import Any, AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
log = logging.getLogger("api-gateway.agents")
|
||||
log = logging.getLogger("xiaoyin-gateway.agents")
|
||||
|
||||
#: 单轮对话的超时(秒)。引擎可能跑很久(多步工具),给足。
|
||||
DEFAULT_TIMEOUT = 300.0
|
||||
|
||||
@@ -37,9 +37,9 @@ from app.adapters.qwenpaw_engine import (
|
||||
stream_chat,
|
||||
)
|
||||
|
||||
log = logging.getLogger("api-gateway.agents")
|
||||
log = logging.getLogger("xiaoyin-gateway.agents")
|
||||
|
||||
QWENPAW_CONFIG = Path("/root/.qwenpaw/config.json")
|
||||
QWENPAW_CONFIG = Path("~/.qwenpaw/config.json")
|
||||
|
||||
|
||||
# ── 运行记录(data/agent_runs.json)────────────────────────────────────
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import threading
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
log = logging.getLogger("api-gateway.circuit")
|
||||
log = logging.getLogger("xiaoyin-gateway.circuit")
|
||||
|
||||
|
||||
class CircuitBreaker:
|
||||
|
||||
@@ -327,6 +327,7 @@ class ServerConfig:
|
||||
webhook_allow_private: bool = False # 视频 callback_url 是否允许指向内网/回环地址(SSRF 防护,默认否)
|
||||
docs_enabled: bool = False # 是否开放 FastAPI 文档(/docs、/redoc、/openapi.json)——安全默认关
|
||||
auth_fail_limit_per_min: int = 20 # 同一来源 IP 每分钟允许的鉴权失败次数,超过 → 429(防暴力枚举)
|
||||
auth_fail_ban_seconds: int = 3600 # 超限后拉黑时长(秒);2026-11-06 新增,0=只限流不拉黑
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -861,6 +862,8 @@ def parse_config(raw: dict[str, Any]) -> GatewayConfig:
|
||||
docs_enabled=_opt_bool(srv_raw.get("docs_enabled"), "server.docs_enabled", False),
|
||||
auth_fail_limit_per_min=_opt_int(srv_raw.get("auth_fail_limit_per_min"),
|
||||
"server.auth_fail_limit_per_min", 20, minimum=1),
|
||||
auth_fail_ban_seconds=_opt_int(srv_raw.get("auth_fail_ban_seconds"),
|
||||
"server.auth_fail_ban_seconds", 3600, minimum=0),
|
||||
)
|
||||
|
||||
# 网关入口鉴权(客户端 key 数组,可配多用户)
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
"""OpenCode Go 模型的套餐元数据(月度额度 / 是否用请求训练 / 零数据保留)。
|
||||
|
||||
**只用于展示,不参与路由与计费。** 数据来自官方 models 接口(实测无需鉴权):
|
||||
|
||||
GET https://opencode.ai/inference/go/v1/models
|
||||
|
||||
其中每个模型带 `go` 字段:
|
||||
|
||||
go: {
|
||||
monthly_usage: {"go": 100, "go-plus": 200, "go-teams": 105},
|
||||
training: false, # 是否用你的请求训练模型
|
||||
zdr: true, # 零数据保留(不保留任何内容)
|
||||
limited_regions: false,
|
||||
}
|
||||
|
||||
官方口径(docs/console/go):`monthly_usage` 是「**只用这一个模型时,各套餐每月额度
|
||||
能覆盖多少用量**」(文档举例用的是美元)。所以前端展示成「$100/月」这类形式。
|
||||
|
||||
设计取舍:
|
||||
· 自带 6 小时缓存,失败后 5 分钟重试;
|
||||
· 拉取失败一律返回**已有缓存或空 dict** —— `/v1/models` 绝不因此报错或变慢太多
|
||||
(首次拉取加 6 秒上限;之后走内存)。
|
||||
· 不写进 gateway.yaml:这是上游随时会变的市场信息,不属于网关的静态配置,
|
||||
也不该让模型同步脚本再背一层。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
_URL = "https://opencode.ai/inference/go/v1/models"
|
||||
log = logging.getLogger("xiaoyin-gateway.gomodels")
|
||||
_TTL = 6 * 3600
|
||||
_RETRY_AFTER_FAIL = 300
|
||||
_TIMEOUT = 6
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cache: dict[str, dict] = {}
|
||||
_at = 0.0
|
||||
|
||||
|
||||
def _fetch() -> dict[str, dict]:
|
||||
req = urllib.request.Request(
|
||||
_URL,
|
||||
headers={"Accept": "application/json", "User-Agent": "xiaoyin-gateway/gomodels"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp: # noqa: S310
|
||||
payload = json.loads(resp.read().decode("utf-8", "replace"))
|
||||
|
||||
out: dict[str, dict] = {}
|
||||
for m in payload.get("data") or []:
|
||||
mid = m.get("id")
|
||||
g = m.get("go") or {}
|
||||
usage = g.get("monthly_usage") or {}
|
||||
if not mid or (not usage and g.get("training") is None):
|
||||
continue
|
||||
out[mid] = {
|
||||
"monthly_usage": {k: int(v) for k, v in usage.items()
|
||||
if isinstance(v, (int, float))},
|
||||
"training": bool(g.get("training")),
|
||||
"zdr": bool(g.get("zdr")),
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def cache_stamp() -> float:
|
||||
"""上次成功刷新的时间戳(0 = 还没拿到过)。调用方可据此判断展示数据是否需要重拼。"""
|
||||
return _at
|
||||
|
||||
|
||||
def get_go_meta(force: bool = False) -> dict[str, dict]:
|
||||
"""{model_id: {"monthly_usage": {...}, "training": bool, "zdr": bool}}。
|
||||
|
||||
过期才刷新;刷新失败保留旧数据,并推迟 `_RETRY_AFTER_FAIL` 秒再试。
|
||||
"""
|
||||
global _at
|
||||
now = time.time()
|
||||
if not force and _cache and now - _at < _TTL:
|
||||
return _cache
|
||||
if not _lock.acquire(blocking=False):
|
||||
return _cache # 别的线程正在刷新,先用旧的
|
||||
try:
|
||||
if force or not _cache or time.time() - _at >= _TTL:
|
||||
try:
|
||||
fresh = _fetch()
|
||||
except Exception as exc: # noqa: BLE001 —— 展示数据,失败不影响主流程
|
||||
# 2026-11-19:一定要留痕 —— 前端这一列空了,运维得能一眼看出是"没拉到"还是"没渲染"
|
||||
log.warning("OpenCode Go 元数据拉取失败(前端额度/训练列会空):%s", exc)
|
||||
fresh = None
|
||||
if fresh:
|
||||
_cache.clear()
|
||||
_cache.update(fresh)
|
||||
_at = time.time()
|
||||
log.info("OpenCode Go 元数据已载入:%d 个模型", len(fresh))
|
||||
else:
|
||||
_at = time.time() - _TTL + _RETRY_AFTER_FAIL
|
||||
finally:
|
||||
_lock.release()
|
||||
return _cache
|
||||
+441
-17
@@ -1,4 +1,4 @@
|
||||
"""API 网关主入口:FastAPI 应用(v2.4 全功能版)。
|
||||
"""小银网关主入口:FastAPI 应用(v2.4 全功能版)。
|
||||
|
||||
特性:
|
||||
- 多供应商 OpenAI 兼容 /chat/completions(同模型重试 + 熔断;第二十七轮起三线直传:
|
||||
@@ -56,6 +56,8 @@ from app.sessions import SessionStore
|
||||
from app.users import UsersStore, UserError, key_limit_for_role
|
||||
from app.history import HistoryStore, HistoryError, MAX_ITEMS as HISTORY_CAP
|
||||
from app.feedback import FeedbackStore, FeedbackError, MAX_ENTRIES as FEEDBACK_CAP
|
||||
# 2026-11-19: OpenCode Go 套餐元数据(月度额度 / 是否训练 / 零保留),只用于前端展示
|
||||
from app.gomodels import get_go_meta, cache_stamp as gomodels_cache_stamp
|
||||
from app.video_owners import VideoOwnerStore
|
||||
from app import settings as gw_settings
|
||||
from app.agents import AgentStore, AgentsError
|
||||
@@ -160,7 +162,7 @@ def _setup_logging() -> None:
|
||||
|
||||
# 基础日志先起来,进 lifespan 后按 observability 重配
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s")
|
||||
log = logging.getLogger("api-gateway")
|
||||
log = logging.getLogger("xiaoyin-gateway")
|
||||
|
||||
# 调用日志的内容上限(2026-10-23,2.9.12 再放宽):默认 **4 MiB**(≈100 万 token 的文本)。
|
||||
# 老板要求「详情内容都不要截断」—— 4 MiB 对任何正常对话都等于不截断;
|
||||
@@ -209,7 +211,7 @@ def _warn_security_posture(cfg) -> None:
|
||||
async def lifespan(app: FastAPI):
|
||||
global config
|
||||
_setup_logging()
|
||||
log.info("API Gateway 启动,已加载 %d 供应商", len(config.providers))
|
||||
log.info("小银网关启动,已加载 %d 供应商", len(config.providers))
|
||||
_warn_security_posture(config)
|
||||
for w in validate_warnings(config):
|
||||
log.warning("配置告警: %s", w)
|
||||
@@ -273,7 +275,7 @@ async def lifespan(app: FastAPI):
|
||||
_, pending = await asyncio.wait(set(_bg_tasks), timeout=5)
|
||||
for t in pending:
|
||||
t.cancel()
|
||||
log.info("API Gateway 关闭,等待在途请求(graceful_shutdown=%ds)", config.server.graceful_shutdown)
|
||||
log.info("小银网关关闭,等待在途请求(graceful_shutdown=%ds)", config.server.graceful_shutdown)
|
||||
# 第六轮: 快照后再迭代(避免迭代中字典被改动 → RuntimeError)
|
||||
for adapter in list(_state.get("adapters", {}).values()):
|
||||
await adapter.close()
|
||||
@@ -386,7 +388,7 @@ _docs_on = config.server.docs_enabled # 安全默认关(report: /docs、/ope
|
||||
VERSION = "2.9.16"
|
||||
|
||||
app = FastAPI(
|
||||
title="API Gateway",
|
||||
title="小银网关",
|
||||
description="统一多供应商 LLM 接入网关(Agnes / OpenCode Go / Dots AI)",
|
||||
version=VERSION,
|
||||
lifespan=lifespan,
|
||||
@@ -953,6 +955,19 @@ async def _validate_callback_url(raw: str | None, allow_private: bool) -> None:
|
||||
# ── IP 级鉴权失败限流(安全报告:中低危——无 IP 限流可暴力枚举 / 刷流量)──
|
||||
_AUTH_FAILS: dict[str, deque] = {}
|
||||
_AUTH_FAIL_MAX_IPS = 1000 # 最多跟踪的 IP,超限清空一次(防内存膨胀)
|
||||
# 2026-11-06: 鉴权失败超限后拉黑一段时间(默认 1 小时),期间该 IP 一律 429。
|
||||
# key=IP, value=解封时间戳(time.time())。只影响这一个 IP,不波及其他来源。
|
||||
_BANNED: dict[str, float] = {}
|
||||
_BANNED_MAX_IPS = 10000 # 最多跟踪的封禁 IP,超限清最旧的一批(防内存膨胀)
|
||||
# 封禁备注(手动封禁时可填「谁、为什么」),与 _BANNED 同生命周期,解封/过期时一并清掉。
|
||||
_BAN_NOTES: dict[str, str] = {}
|
||||
# 永久封禁(不随时间过期)。与 _BANNED 分开存,免得拿"极大时间戳"糊弄,
|
||||
# 导致剩余时间算出天文数字、前端还得猜哪个算永久。
|
||||
_BANNED_FOREVER: set[str] = set()
|
||||
# 封禁操作历史(封/解封/延长),落盘 JSONL,重启不丢。只保留最近 _BAN_HISTORY_MAX 条。
|
||||
_BAN_HISTORY: list[dict] = []
|
||||
_BAN_HISTORY_MAX = 500
|
||||
_BAN_HISTORY_FILE = Path(__file__).resolve().parent.parent / "data" / "ban_history.jsonl"
|
||||
|
||||
|
||||
_TRUSTED_PROXY_IPS = {"127.0.0.1", "::1"} # 本机反代(nginx/openresty):只有它写的 XFF 可信
|
||||
@@ -979,10 +994,142 @@ def _client_ip(request: Request) -> str:
|
||||
return peer or "unknown"
|
||||
|
||||
|
||||
def _record_auth_fail(request: Request, limit_per_min: int) -> bool:
|
||||
"""记录一次鉴权失败;返回 True 表示该来源 60s 内已超限(应直接 429)。"""
|
||||
def _ban_remaining(ip: str) -> int:
|
||||
"""该 IP 还要被限制的秒数:0=未封禁,-1=永久封禁,>0=剩余秒数。
|
||||
|
||||
顺带清理已过期的定时封禁(投机清理,不要求调用方配合)。
|
||||
"""
|
||||
if ip in _BANNED_FOREVER:
|
||||
return -1
|
||||
exp = _BANNED.get(ip)
|
||||
if exp is None:
|
||||
return 0
|
||||
left = int(exp - time.time())
|
||||
if left <= 0:
|
||||
_BANNED.pop(ip, None)
|
||||
_BAN_NOTES.pop(ip, None)
|
||||
return 0
|
||||
return left
|
||||
|
||||
|
||||
def _ban_history_add(action: str, ip: str, *, seconds: int = 0,
|
||||
note: str = "", actor: str = "", permanent: bool = False) -> None:
|
||||
"""记一条封禁操作历史(封/解封/延长/清空),并追加到 JSONL。
|
||||
|
||||
历史上限 _BAN_HISTORY_MAX 条(内存),文件则是纯追加、由运维按需轮转。
|
||||
落盘失败不影响主流程 —— 封禁本身比日志重要。
|
||||
"""
|
||||
item = {
|
||||
"id": uuid.uuid4().hex[:12], # 删除时用的稳定标识(时间戳会撞,不能用)
|
||||
"ts": int(time.time()),
|
||||
"action": action, # ban / manual_ban / unban / unban_all / extend / auto_ban
|
||||
"ip": ip,
|
||||
"seconds": seconds,
|
||||
"permanent": permanent,
|
||||
"note": note,
|
||||
"actor": actor,
|
||||
}
|
||||
_BAN_HISTORY.append(item)
|
||||
if len(_BAN_HISTORY) > _BAN_HISTORY_MAX:
|
||||
del _BAN_HISTORY[: len(_BAN_HISTORY) - _BAN_HISTORY_MAX]
|
||||
try:
|
||||
_BAN_HISTORY_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
with _BAN_HISTORY_FILE.open("a", encoding="utf-8") as fh:
|
||||
fh.write(json.dumps(item, ensure_ascii=False) + "\n")
|
||||
except OSError as e:
|
||||
log.warning("封禁历史上写盘失败(不影响封禁本身):%s", e)
|
||||
|
||||
|
||||
def _ban_history_save() -> None:
|
||||
"""把内存里的历史整体重写到 JSONL(删除后调用)。
|
||||
|
||||
为什么不是「删文件里某一行」:JSONL 没有索引,原地删要读全量再写回,
|
||||
代价和整体重写一样,但整体重写不会留下空洞或半行,更安全。
|
||||
"""
|
||||
try:
|
||||
_BAN_HISTORY_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = _BAN_HISTORY_FILE.with_suffix(".jsonl.tmp")
|
||||
with tmp.open("w", encoding="utf-8") as fh:
|
||||
for h in _BAN_HISTORY:
|
||||
fh.write(json.dumps(h, ensure_ascii=False) + "\n")
|
||||
tmp.replace(_BAN_HISTORY_FILE) # 原子替换,避免写一半被读到
|
||||
except OSError as e:
|
||||
log.warning("封禁历史重写盘失败(不影响封禁本身):%s", e)
|
||||
|
||||
|
||||
def _ban_history_load() -> None:
|
||||
"""启动时把历史文件读回内存(文件丢了/坏了就当空历史,不阻塞启动)。
|
||||
|
||||
老版本写的行没有 id,这里补一个,保证删除接口对历史数据同样可用。
|
||||
"""
|
||||
try:
|
||||
if not _BAN_HISTORY_FILE.is_file():
|
||||
return
|
||||
with _BAN_HISTORY_FILE.open("r", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
h = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue # 半行/坏行直接跳过,别为一条脏数据拖垮整个历史
|
||||
if not isinstance(h, dict):
|
||||
continue
|
||||
h.setdefault("id", uuid.uuid4().hex[:12])
|
||||
for k, dv in (("ts", 0), ("action", "unknown"), ("ip", ""), ("seconds", 0),
|
||||
("permanent", False), ("note", ""), ("actor", "")):
|
||||
h.setdefault(k, dv)
|
||||
_BAN_HISTORY.append(h)
|
||||
if len(_BAN_HISTORY) > _BAN_HISTORY_MAX:
|
||||
del _BAN_HISTORY[: len(_BAN_HISTORY) - _BAN_HISTORY_MAX]
|
||||
log.info("封禁历史已载入 %d 条", len(_BAN_HISTORY))
|
||||
except OSError as e:
|
||||
log.warning("封禁历史读取失败(按空历史启动):%s", e)
|
||||
|
||||
|
||||
_ban_history_load()
|
||||
|
||||
|
||||
def _record_auth_fail(request: Request, limit_per_min: int, ban_seconds: int = 3600) -> int:
|
||||
"""记录一次鉴权失败。
|
||||
|
||||
返回 0 表示还没到限流阈值(调用方按原样回 401);
|
||||
返回 >0 表示该来源应被 429,值是**还要等多少秒**:
|
||||
- 已被拉黑 → 剩余拉黑秒数
|
||||
- 本次刚触发 → ban_seconds(>0 时顺便写入封禁表)
|
||||
|
||||
2026-11-06: 从「只限流 60 秒」改成「超限即拉黑 ban_seconds 秒(默认 1 小时)」。
|
||||
只针对该 IP,其他来源完全不受影响。
|
||||
"""
|
||||
ip = _client_ip(request)
|
||||
now = time.time()
|
||||
|
||||
# 2026-11-06 安全网:回环 / 私网 / 本机反代永不拉黑。
|
||||
# 原因:网关只监听 127.0.0.1,正常流量都经 OpenResty 回源(带 XFF,能拿到真实 IP);
|
||||
# 但如果某次 XFF 缺失,_client_ip 会退回 peer=127.0.0.1 —— 一旦拉黑它,
|
||||
# 等于把**所有人**一起封死。这里直接豁免,宁可少封一个也不误伤全局。
|
||||
if ip in ("127.0.0.1", "::1", "localhost", "unknown", ""):
|
||||
dq0 = _AUTH_FAILS.get(ip)
|
||||
if dq0 is None:
|
||||
if len(_AUTH_FAILS) >= _AUTH_FAIL_MAX_IPS:
|
||||
_AUTH_FAILS.clear()
|
||||
dq0 = deque()
|
||||
_AUTH_FAILS[ip] = dq0
|
||||
dq0.append(now)
|
||||
while dq0 and now - dq0[0] > 60.0:
|
||||
dq0.popleft()
|
||||
# 仍然返回限流(保护服务),但不写封禁表
|
||||
return 60 if len(dq0) >= limit_per_min else 0
|
||||
if ip.startswith("10.") or ip.startswith("192.168.") or ip.startswith("172."):
|
||||
return 0 # 内网来源不参与封禁(自家设备误配 Key 不该被锁死)
|
||||
|
||||
# 已在封禁期内(含永久):直接返回,不再累计。
|
||||
# 注意 left 可能是 -1(永久),所以判断用真值而不是 >0。
|
||||
left = _ban_remaining(ip)
|
||||
if left:
|
||||
return left
|
||||
|
||||
dq = _AUTH_FAILS.get(ip)
|
||||
if dq is None:
|
||||
if len(_AUTH_FAILS) >= _AUTH_FAIL_MAX_IPS:
|
||||
@@ -992,7 +1139,22 @@ def _record_auth_fail(request: Request, limit_per_min: int) -> bool:
|
||||
dq.append(now)
|
||||
while dq and now - dq[0] > 60.0:
|
||||
dq.popleft()
|
||||
return len(dq) >= limit_per_min
|
||||
|
||||
if len(dq) >= limit_per_min:
|
||||
# 触发限流:清掉计数,按需写入封禁表
|
||||
_AUTH_FAILS.pop(ip, None)
|
||||
if ban_seconds > 0:
|
||||
if len(_BANNED) >= _BANNED_MAX_IPS:
|
||||
# 清掉最早解封的一批(保留最近的一半)
|
||||
keep = sorted(_BANNED.items(), key=lambda kv: kv[1])[-_BANNED_MAX_IPS // 2:]
|
||||
_BANNED.clear()
|
||||
_BANNED.update(dict(keep))
|
||||
_BANNED[ip] = now + ban_seconds
|
||||
_BAN_NOTES.pop(ip, None)
|
||||
log.warning("鉴权失败超限,拉黑 IP %s 共 %d 秒", ip, ban_seconds)
|
||||
return ban_seconds
|
||||
return 60
|
||||
return 0
|
||||
|
||||
|
||||
def _key_token(key: str) -> str | None:
|
||||
@@ -1127,8 +1289,12 @@ async def require_auth(
|
||||
log.info("已停用账号 %s 的 API Key 被调用,已拒绝(%s %s)",
|
||||
owner, request.method, request.url.path)
|
||||
raise HTTPException(403, "账号已被停用,请联系管理员")
|
||||
if _record_auth_fail(request, cfg.server.auth_fail_limit_per_min):
|
||||
raise HTTPException(429, "鉴权失败次数过多,已在 60 秒内触发限流,请稍后重试")
|
||||
_wait = _record_auth_fail(request, cfg.server.auth_fail_limit_per_min,
|
||||
cfg.server.auth_fail_ban_seconds)
|
||||
if _wait:
|
||||
_mins = max(1, (_wait + 59) // 60)
|
||||
raise HTTPException(429, f"鉴权失败次数过多,该 IP 已被限制访问,请 {_mins} 分钟后重试",
|
||||
headers={"Retry-After": str(_wait)})
|
||||
raise HTTPException(401, "无效或缺失的账号 / API Key", headers={"WWW-Authenticate": "Bearer"})
|
||||
account, role, kind = identity
|
||||
_set_identity(request, account, role)
|
||||
@@ -1330,7 +1496,7 @@ def _attach_cost(resp: dict, model: str, usage: dict, cfg) -> None:
|
||||
# ─────────────────────────────────────
|
||||
# GET /models + GET /v1/models(P1-7 / P0-3)
|
||||
# ─────────────────────────────────────
|
||||
def _models_payload():
|
||||
def _models_payload_base():
|
||||
cfg = _cfg()
|
||||
# 优化: 目录按配置 mtime 缓存(热重载改配置才重建;静默期每次请求直接命中,省掉
|
||||
# all_models() 的重复遍历与对象构建)。cfg 引用同一 config 对象,
|
||||
@@ -1407,6 +1573,40 @@ def _models_payload():
|
||||
return payload
|
||||
|
||||
|
||||
def _models_payload():
|
||||
"""在按 mtime 缓存的目录上,现拼 OpenCode Go 的套餐元数据。
|
||||
|
||||
2026-11-19(老板要求):前端要显示「这个模型每月能调多少」「是否拿你的代码训练」。
|
||||
这两个字段来自官方 models 接口(有自己的 6 小时缓存,见 app/gomodels.py),
|
||||
所以**不烤进** `_models_cache`(否则配置不变就永远停在第一次的快照)。
|
||||
|
||||
拼好后按 (配置 mtime, go 缓存时间戳) 再缓存一层 —— 两个都没变时返回**同一个对象**
|
||||
(`test_models_payload_cached_and_invalidated_by_mtime` 依赖这个身份语义);
|
||||
任一变化就重拼。拿不到 go 数据时直接原样返回 base。
|
||||
"""
|
||||
base = _models_payload_base()
|
||||
go = get_go_meta()
|
||||
if not go:
|
||||
return base
|
||||
# 缓存键带上 base 的对象 id(并**持有 base 的强引用**,保证 id 不会被复用)——
|
||||
# 这样只要 base 被重建(配置热重载,或测试直接把 _models_cache 置 None 换 config),
|
||||
# 合并层就跟着失效;go 数据刷新(时间戳变化)也会失效。
|
||||
key = (id(base), gomodels_cache_stamp())
|
||||
cached = _state.get("_models_cache_go")
|
||||
if cached is not None and cached[0] == key and cached[2] is base:
|
||||
return cached[1]
|
||||
data = []
|
||||
for item in base.get("data") or []:
|
||||
mid = item.get("id")
|
||||
# 别名(alias_of)不重复挂:它的额度/训练口径就是目标模型的,前端按目标取
|
||||
if mid in go and "alias_of" not in item:
|
||||
item = {**item, "go": go[mid]}
|
||||
data.append(item)
|
||||
payload = {**base, "data": data}
|
||||
_state["_models_cache_go"] = (key, payload, base)
|
||||
return payload
|
||||
|
||||
|
||||
@app.get("/models")
|
||||
async def list_models(request: Request, _auth=Depends(require_auth)):
|
||||
return _models_payload()
|
||||
@@ -3133,7 +3333,7 @@ async def metrics_prometheus(request: Request, _auth=Depends(require_auth)):
|
||||
raise HTTPException(404, "metrics 已禁用")
|
||||
snap = _usage_snapshot()
|
||||
lines = [
|
||||
"# API Gateway Prometheus 指标",
|
||||
"# Xiaoyin Gateway Prometheus 指标",
|
||||
f'api_gateway_uptime_seconds {snap["uptime_seconds"]}',
|
||||
# 第二十七轮: api_gateway_fallback_total 随「路由别名 / fallback 链」一起删除 ——
|
||||
# 快照里已没有 fallback_total 字段,这里再读就是 KeyError(曾被 live_check 抓到 500)。
|
||||
@@ -3194,7 +3394,7 @@ async def metrics_prometheus(request: Request, _auth=Depends(require_auth)):
|
||||
"# HELP api_gateway_circuit_recent_failures 熔断窗口内近期失败数",
|
||||
"# TYPE api_gateway_circuit_recent_failures gauge",
|
||||
]
|
||||
# "# API Gateway Prometheus 指标" 是第一行注释,保留在 HELP 之前
|
||||
# "# Xiaoyin Gateway Prometheus 指标" 是第一行注释,保留在 HELP 之前
|
||||
head, body = lines[0], lines[1:]
|
||||
return "\n".join([head] + help_lines + body) + "\n"
|
||||
|
||||
@@ -3464,7 +3664,7 @@ async def root(request: Request, _auth=Depends(require_auth_or_open)):
|
||||
return RedirectResponse("/web/")
|
||||
cfg = _cfg()
|
||||
return {
|
||||
"name": "API Gateway",
|
||||
"name": "小银网关",
|
||||
"version": VERSION,
|
||||
"endpoints": {
|
||||
"chat": "POST /v1/chat/completions(OpenAI Chat Completions 线)",
|
||||
@@ -3550,8 +3750,12 @@ async def auth_login(request: Request):
|
||||
username = str(body.get("username") or "").strip()
|
||||
password = str(body.get("password") or "")
|
||||
if not username or not await _offload(_users.verify, username, password):
|
||||
if _record_auth_fail(request, _cfg().server.auth_fail_limit_per_min):
|
||||
raise HTTPException(429, "登录失败次数过多,已在 60 秒内触发限流,请稍后重试")
|
||||
_wait = _record_auth_fail(request, _cfg().server.auth_fail_limit_per_min,
|
||||
_cfg().server.auth_fail_ban_seconds)
|
||||
if _wait:
|
||||
_mins = max(1, (_wait + 59) // 60)
|
||||
raise HTTPException(429, f"登录失败次数过多,该 IP 已被限制访问,请 {_mins} 分钟后重试",
|
||||
headers={"Retry-After": str(_wait)})
|
||||
raise HTTPException(401, "账号或密码错误", headers={"WWW-Authenticate": "Bearer"})
|
||||
# 第二十四轮: 账号被管理员停用 → 密码对也不发会话,并明确告知原因(让人知道去找管理员,
|
||||
# 而不是反复试密码)。校验顺序在口令之后:不知道密码的人依旧只看到 401,探不出账号状态。
|
||||
@@ -3759,6 +3963,226 @@ def _require_session(request: Request) -> str:
|
||||
|
||||
|
||||
# ── 各账号自管 API Key(默认无,页面自建) ──
|
||||
# ── 鉴权失败拉黑管理(2026-11-06,仅管理员)────────────────────────────
|
||||
# 对应 _BANNED 字典(_record_auth_fail 写入)。只读 + 解封,不提供"手动封禁"
|
||||
# —— 手动封禁走 iptables/防火墙更合适,这里只负责查看和放行误封的 IP。
|
||||
@app.get("/admin/banned")
|
||||
async def admin_list_banned(request: Request, _auth=Depends(require_auth)):
|
||||
"""列出当前被封禁的 IP(仅管理员)。"""
|
||||
_require_admin(request)
|
||||
now = time.time()
|
||||
items = []
|
||||
for ip, exp in list(_BANNED.items()):
|
||||
left = int(exp - now)
|
||||
if left <= 0:
|
||||
_BANNED.pop(ip, None)
|
||||
_BAN_NOTES.pop(ip, None)
|
||||
continue
|
||||
items.append({
|
||||
"ip": ip,
|
||||
"banned_until": int(exp),
|
||||
"remaining_seconds": left,
|
||||
"remaining_minutes": (left + 59) // 60,
|
||||
"note": _BAN_NOTES.get(ip, ""),
|
||||
"permanent": False,
|
||||
})
|
||||
# 永久封禁排在最后(没有解封时间,按 IP 排)
|
||||
for ip in sorted(_BANNED_FOREVER):
|
||||
items.append({
|
||||
"ip": ip,
|
||||
"banned_until": 0,
|
||||
"remaining_seconds": -1,
|
||||
"remaining_minutes": -1,
|
||||
"note": _BAN_NOTES.get(ip, ""),
|
||||
"permanent": True,
|
||||
})
|
||||
items.sort(key=lambda x: (x["permanent"], x["banned_until"] or 0))
|
||||
return {
|
||||
"count": len(items),
|
||||
"ban_seconds": _cfg().server.auth_fail_ban_seconds,
|
||||
"auth_fail_limit_per_min": _cfg().server.auth_fail_limit_per_min,
|
||||
"items": items,
|
||||
}
|
||||
|
||||
|
||||
@app.post("/admin/banned")
|
||||
async def admin_ban(request: Request, _auth=Depends(require_auth)):
|
||||
"""手动封禁一个 IP(仅管理员)。
|
||||
|
||||
参数:{"ip": "1.2.3.4", "seconds": 3600};seconds 缺省用 server.auth_fail_ban_seconds。
|
||||
与自动拉黑共用 _BANNED 表,所以能在列表里看到、也能被同一个解封接口放行。
|
||||
白名单(回环/私网)同样豁免 —— 手动也封不掉本机反代,避免一键把全站弄挂。
|
||||
"""
|
||||
_require_admin(request)
|
||||
body = await _json_object(request)
|
||||
ip = str(body.get("ip") or "").strip()
|
||||
if not ip:
|
||||
raise HTTPException(400, "缺少参数 ip")
|
||||
# 只接受 IPv4/IPv6 字面量,挡住把整段/域名/通配塞进来的误操作
|
||||
try:
|
||||
ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
raise HTTPException(400, f"不是合法的 IP 地址: {ip}")
|
||||
if ip in ("127.0.0.1", "::1", "localhost", "unknown", "") or ip.startswith(("10.", "192.168.", "172.")):
|
||||
raise HTTPException(400, "回环/内网地址不允许手动封禁(会把本机反代或自家设备一起锁死)")
|
||||
|
||||
permanent = bool(body.get("permanent"))
|
||||
default_sec = _cfg().server.auth_fail_ban_seconds or 3600
|
||||
if permanent:
|
||||
seconds = 0
|
||||
else:
|
||||
raw_sec = body.get("seconds")
|
||||
try:
|
||||
seconds = int(raw_sec) if raw_sec is not None else default_sec
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, "seconds 必须是整数(秒)")
|
||||
if seconds < 60 or seconds > 30 * 86400:
|
||||
raise HTTPException(400, "seconds 需在 60 ~ 2592000(30 天)之间(永久请传 permanent=true)")
|
||||
|
||||
now = time.time()
|
||||
note = str(body.get("note") or "").strip()[:120]
|
||||
if permanent:
|
||||
_BANNED.pop(ip, None)
|
||||
_BANNED_FOREVER.add(ip)
|
||||
banned_until = 0
|
||||
else:
|
||||
if len(_BANNED) >= _BANNED_MAX_IPS:
|
||||
keep = sorted(_BANNED.items(), key=lambda kv: kv[1])[-_BANNED_MAX_IPS // 2:]
|
||||
_BANNED.clear()
|
||||
_BANNED.update(dict(keep))
|
||||
_BANNED_FOREVER.discard(ip)
|
||||
_BANNED[ip] = now + seconds
|
||||
banned_until = int(now + seconds)
|
||||
_AUTH_FAILS.pop(ip, None)
|
||||
if note:
|
||||
_BAN_NOTES[ip] = note
|
||||
else:
|
||||
_BAN_NOTES.pop(ip, None)
|
||||
log.warning("管理员 %s 手动封禁 IP %s %s%s", request.state.account, ip,
|
||||
"(永久)" if permanent else f"共 {seconds} 秒",
|
||||
f"(备注:{note})" if note else "")
|
||||
_ban_history_add("manual_ban", ip, seconds=seconds, note=note,
|
||||
actor=request.state.account, permanent=permanent)
|
||||
return {"status": "ok", "ip": ip, "banned_seconds": seconds,
|
||||
"banned_until": banned_until, "permanent": permanent}
|
||||
|
||||
|
||||
@app.put("/admin/banned/{ip}")
|
||||
async def admin_extend(request: Request, ip: str, _auth=Depends(require_auth)):
|
||||
"""延长某 IP 的封禁(仅管理员)。
|
||||
|
||||
参数:{"seconds": 3600} 或 {"permanent": true}。
|
||||
语义是**在当前剩余时间上加**,不是重置 —— 所以连点两次「延长 1 小时」= 续 2 小时。
|
||||
"""
|
||||
_require_admin(request)
|
||||
body = await _json_object(request)
|
||||
try:
|
||||
ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
raise HTTPException(400, f"不是合法的 IP 地址: {ip}")
|
||||
|
||||
if ip not in _BANNED and ip not in _BANNED_FOREVER:
|
||||
raise HTTPException(404, f"{ip} 当前没有被封禁,无法延长")
|
||||
|
||||
permanent = bool(body.get("permanent"))
|
||||
now = time.time()
|
||||
if permanent:
|
||||
_BANNED.pop(ip, None)
|
||||
_BANNED_FOREVER.add(ip)
|
||||
total = 0
|
||||
else:
|
||||
raw_sec = body.get("seconds")
|
||||
try:
|
||||
seconds = int(raw_sec) if raw_sec is not None else (_cfg().server.auth_fail_ban_seconds or 3600)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, "seconds 必须是整数(秒)")
|
||||
if seconds < 60 or seconds > 30 * 86400:
|
||||
raise HTTPException(400, "seconds 需在 60 ~ 2592000(30 天)之间")
|
||||
if ip in _BANNED_FOREVER:
|
||||
# 永久封禁没有"剩余时间"可加,先转成定时再算
|
||||
_BANNED_FOREVER.discard(ip)
|
||||
base = now
|
||||
else:
|
||||
base = max(_BANNED.get(ip, now), now)
|
||||
_BANNED[ip] = base + seconds
|
||||
total = seconds
|
||||
log.warning("管理员 %s 延长 IP %s 的封禁:%s", request.state.account, ip,
|
||||
"改为永久" if permanent else f"+{total} 秒")
|
||||
_ban_history_add("extend", ip, seconds=total, actor=request.state.account, permanent=permanent)
|
||||
return {"status": "ok", "ip": ip, "extended_seconds": total, "permanent": permanent}
|
||||
|
||||
|
||||
@app.get("/admin/banned/history")
|
||||
async def admin_ban_history(request: Request, limit: int = 50, ip: str | None = None,
|
||||
_auth=Depends(require_auth)):
|
||||
"""封禁操作历史(仅管理员)。默认最近 50 条,可按 IP 过滤。"""
|
||||
_require_admin(request)
|
||||
rows = _BAN_HISTORY
|
||||
if ip:
|
||||
rows = [h for h in rows if h.get("ip") == ip]
|
||||
rows = rows[-max(1, min(limit, _BAN_HISTORY_MAX)):]
|
||||
return {"count": len(rows), "items": list(reversed(rows))}
|
||||
|
||||
|
||||
# ⚠️ 顺序敏感:下面两个必须以 "history" 结尾的路由**声明在** DELETE /admin/banned/{ip}
|
||||
# 之前,否则 FastAPI 会把 "history" 当成一个 IP 交给解封接口处理。
|
||||
@app.delete("/admin/banned/history/{hid}")
|
||||
async def admin_ban_history_delete(request: Request, hid: str, _auth=Depends(require_auth)):
|
||||
"""删除一条封禁历史(仅管理员)。只动历史记录,不影响任何实际封禁。"""
|
||||
_require_admin(request)
|
||||
keep = [h for h in _BAN_HISTORY if h.get("id") != hid]
|
||||
if len(keep) == len(_BAN_HISTORY):
|
||||
raise HTTPException(404, f"找不到历史记录 {hid}")
|
||||
_BAN_HISTORY[:] = keep
|
||||
_ban_history_save()
|
||||
log.info("管理员 %s 删除封禁历史 %s", request.state.account, hid)
|
||||
return {"status": "ok", "id": hid}
|
||||
|
||||
|
||||
@app.delete("/admin/banned/history")
|
||||
async def admin_ban_history_clear(request: Request, _auth=Depends(require_auth)):
|
||||
"""清空全部封禁历史(仅管理员)。只动历史记录,不影响任何实际封禁。"""
|
||||
_require_admin(request)
|
||||
n = len(_BAN_HISTORY)
|
||||
_BAN_HISTORY.clear()
|
||||
_ban_history_save()
|
||||
log.info("管理员 %s 清空封禁历史(共 %d 条)", request.state.account, n)
|
||||
return {"status": "ok", "cleared": n}
|
||||
|
||||
|
||||
@app.delete("/admin/banned/{ip}")
|
||||
async def admin_unban(request: Request, ip: str, _auth=Depends(require_auth)):
|
||||
"""解除某个 IP 的封禁(仅管理员)。"""
|
||||
_require_admin(request)
|
||||
# set.discard() 恒返回 None,不能拿它判断"是否存在",必须先查成员再删
|
||||
was_timed = _BANNED.pop(ip, None) is not None
|
||||
was_forever = ip in _BANNED_FOREVER
|
||||
_BANNED_FOREVER.discard(ip)
|
||||
existed = was_timed or was_forever
|
||||
_AUTH_FAILS.pop(ip, None) # 连失败计数一起清,避免刚放行又被立刻封回去
|
||||
_BAN_NOTES.pop(ip, None)
|
||||
log.info("管理员 %s 解除 IP %s 的封禁(原本存在=%s)",
|
||||
request.state.account, ip, existed)
|
||||
if existed:
|
||||
_ban_history_add("unban", ip, actor=request.state.account)
|
||||
return {"status": "ok", "ip": ip, "was_banned": existed}
|
||||
|
||||
|
||||
@app.delete("/admin/banned")
|
||||
async def admin_unban_all(request: Request, _auth=Depends(require_auth)):
|
||||
"""清空全部封禁(仅管理员)。用于批量误封后的快速恢复。"""
|
||||
_require_admin(request)
|
||||
n = len(_BANNED) + len(_BANNED_FOREVER)
|
||||
_BANNED.clear()
|
||||
_BANNED_FOREVER.clear()
|
||||
_BAN_NOTES.clear()
|
||||
_AUTH_FAILS.clear()
|
||||
log.info("管理员 %s 清空全部封禁(共 %d 个 IP)", request.state.account, n)
|
||||
if n:
|
||||
_ban_history_add("unban_all", "*", actor=request.state.account, note=f"清空 {n} 个")
|
||||
return {"status": "ok", "cleared": n}
|
||||
|
||||
|
||||
@app.get("/auth/apikeys")
|
||||
async def auth_list_apikeys(request: Request, _auth=Depends(require_auth)):
|
||||
"""列出本账号 Key(含明文,便于反复复制)。
|
||||
@@ -4280,7 +4704,7 @@ async def opencode_go_usage(_auth=Depends(require_auth)):
|
||||
raise HTTPException(503, "OpenCode Go 未配置 API Key")
|
||||
|
||||
base = str(pconfig.base_url or "https://opencode.ai/zen/go/v1").rstrip("/")
|
||||
ua = (pconfig.extra_headers or {}).get("User-Agent") or f"api-gateway/{VERSION}"
|
||||
ua = (pconfig.extra_headers or {}).get("User-Agent") or f"xiaoyin-gateway/{VERSION}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.get(
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ from collections import deque
|
||||
from contextvars import ContextVar
|
||||
from typing import Any
|
||||
|
||||
log = logging.getLogger("api-gateway.metrics")
|
||||
log = logging.getLogger("xiaoyin-gateway.metrics")
|
||||
|
||||
# 请求级「归属账号」上下文(ContextVar,每 task/请求独立;由 main.py require_auth 写入)。
|
||||
# 访问日志与指标通过它给每条记录打上账号,实现:
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
log = logging.getLogger("api-gateway.sessions")
|
||||
log = logging.getLogger("xiaoyin-gateway.sessions")
|
||||
|
||||
# 落盘文件名固定为 sessions.json;结构带 version,便于以后改格式时兼容读取。
|
||||
_FILE_VERSION = 1
|
||||
|
||||
+8
-2
@@ -41,7 +41,7 @@ from app.config import (
|
||||
validate_warnings,
|
||||
)
|
||||
|
||||
log = logging.getLogger("api-gateway.settings")
|
||||
log = logging.getLogger("xiaoyin-gateway.settings")
|
||||
|
||||
# ── 改了必须重启进程才生效的键(其余都是"每请求读配置",保存即生效) ──
|
||||
# host / port:uvicorn 在进程启动时绑定,改文件不会重绑。
|
||||
@@ -141,6 +141,9 @@ def config_to_view(cfg: GatewayConfig) -> dict[str, Any]:
|
||||
"webhook_allow_private": s.webhook_allow_private,
|
||||
"docs_enabled": s.docs_enabled,
|
||||
"auth_fail_limit_per_min": s.auth_fail_limit_per_min,
|
||||
# 2026-11-19 补:封禁功能(2026-11-06)加了配置项但面板视图没跟上,
|
||||
# 一旦在面板里保存配置,这一行就会被写丢(回退成默认 3600)。
|
||||
"auth_fail_ban_seconds": s.auth_fail_ban_seconds,
|
||||
},
|
||||
"auth": {"session_ttl_minutes": cfg.auth.session_ttl_minutes},
|
||||
"circuit": {
|
||||
@@ -479,6 +482,9 @@ _SERVER_KEYS = (
|
||||
"host", "port", "timeout", "retry", "health_auth", "hot_reload", "hot_reload_interval",
|
||||
"metrics_enabled", "rate_limit_rps", "max_body_size", "cors_origins", "graceful_shutdown",
|
||||
"batch_max_concurrency", "batch_max_items", "webhook_allow_private", "docs_enabled",
|
||||
# 2026-11-19 补:封禁功能(2026-11-06)落盘了这两个键但忘了搬上面板,
|
||||
# 导致「文件里有、面板里没有」—— 保存一次面板就会把它们丢掉。
|
||||
"auth_fail_limit_per_min", "auth_fail_ban_seconds",
|
||||
"auth_fail_limit_per_min",
|
||||
)
|
||||
_CIRCUIT_KEYS = ("enabled", "failure_threshold", "cooldown", "window")
|
||||
@@ -510,7 +516,7 @@ def restart_keys_changed(old: GatewayConfig, new: GatewayConfig) -> list[str]:
|
||||
|
||||
# ── 渲染 yaml 文本 ────────────────────────────────────────
|
||||
_HEADER = """\
|
||||
# AI 网关配置文件(data/ 目录)
|
||||
# 小银网关配置文件(data/ 目录)
|
||||
#
|
||||
# ⚠ 本文件由管理页面「网关配置」生成(管理员账号),页面保存时会**整份重写**:
|
||||
# 想要的历史决策/踩坑说明在 README.md(按轮次记录),这里只保留必要的现场注释。
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
log = logging.getLogger("api-gateway.users")
|
||||
log = logging.getLogger("xiaoyin-gateway.users")
|
||||
|
||||
USERNAME_RE = re.compile(r"^[A-Za-z0-9]+$")
|
||||
ITERATIONS = 200_000
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
log = logging.getLogger("api-gateway.video_owners")
|
||||
log = logging.getLogger("xiaoyin-gateway.video_owners")
|
||||
|
||||
_FILE_VERSION = 1
|
||||
|
||||
|
||||
+55
-28
@@ -1,4 +1,4 @@
|
||||
# AI 网关配置文件(data/ 目录)
|
||||
# 小银网关配置文件(data/ 目录)
|
||||
# 供应商:Agnes / OpenCode Go(订阅编程模型)/ Dots AI
|
||||
# 密钥统一走 token_env 指向的环境变量(本机见 data/.env),不再在 yaml 存明文
|
||||
# 端口默认 8808
|
||||
@@ -232,8 +232,6 @@ providers:
|
||||
- id: "agnes-video-2.5-flash"
|
||||
display_name: "Agnes Video 2.5 Flash"
|
||||
type: "video"
|
||||
free: true # 2026-09-24 自动同步:文档「当前优惠」写当前限时免费(scripts/sync_models.py)
|
||||
free_limited: true # 限时免费;文档改口径后同步会自动撤掉这行
|
||||
# 2026-09-24 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
- id: "agnes-2.5-pro"
|
||||
display_name: "Agnes 2.5 Pro"
|
||||
@@ -264,6 +262,11 @@ providers:
|
||||
context_window: 1000000 # 同步 2026-10-21(scripts/sync_models.py)
|
||||
max_output_tokens: 65536 # 同步 2026-10-21(scripts/sync_models.py)
|
||||
# 文档现价 ¥3/M 输入、¥6/M 输出
|
||||
# 2026-11-09 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
- id: "agnes-2.5-pro-theta"
|
||||
display_name: "Agnes 2.5 Pro Theta"
|
||||
type: "text"
|
||||
# 文档现价 ¥3/M 输入、¥6/M 输出
|
||||
|
||||
opencode:
|
||||
name: "OpenCode Go"
|
||||
@@ -276,7 +279,7 @@ providers:
|
||||
# 每次请求动态注入会话头(不能放静态 extra_headers——会被 _get_adapter 缓存冻结)。
|
||||
requires_session_header: true
|
||||
extra_headers:
|
||||
User-Agent: "api-gateway/2.4.0 (jakon opencode-go)"
|
||||
User-Agent: "xiaoyin-gateway/2.4.0 (jakon opencode-go)"
|
||||
# 无媒体能力(纯文本编程模型;图像/视频不走本供应商)
|
||||
media: {}
|
||||
# ── 协议线(第二十七轮「三线直传」)──────────────────────────
|
||||
@@ -301,6 +304,7 @@ providers:
|
||||
responses:
|
||||
path: "/responses"
|
||||
auth: "bearer"
|
||||
rate_limit_rps: 3.0 # 2026-11-06 新增:主动限流,避免被上游 429
|
||||
# ── 模型 ─────────────────────────────────────────────────
|
||||
# models[].protocols = 该模型**能用哪几条线**(入站格式必须与出站一致)。
|
||||
# 取值:chat/completions | messages | responses;不写 = 只认 chat/completions。
|
||||
@@ -331,12 +335,6 @@ providers:
|
||||
context_window: 1000000 # 第三十三轮(2026-09-24):上下文窗口(token),每日同步维护
|
||||
max_output_tokens: 131072 # 最大输出(token)
|
||||
protocols: ["chat/completions"]
|
||||
- id: "glm-5.2"
|
||||
display_name: "GLM-5.2"
|
||||
type: "text"
|
||||
context_window: 1000000 # 第三十三轮(2026-09-24):上下文窗口(token),每日同步维护
|
||||
max_output_tokens: 131072 # 最大输出(token)
|
||||
protocols: ["chat/completions"]
|
||||
- id: "kimi-k2.7-code"
|
||||
display_name: "Kimi K2.7 Code"
|
||||
type: "text"
|
||||
@@ -355,18 +353,6 @@ providers:
|
||||
context_window: 1000000 # 第三十三轮(2026-09-24):上下文窗口(token),每日同步维护
|
||||
max_output_tokens: 131072 # 最大输出(token)
|
||||
protocols: ["chat/completions"]
|
||||
- id: "mimo-v2.5"
|
||||
display_name: "MiMo V2.5"
|
||||
type: "text"
|
||||
context_window: 1000000 # 第三十三轮(2026-09-24):上下文窗口(token),每日同步维护
|
||||
max_output_tokens: 128000 # 最大输出(token)
|
||||
protocols: ["chat/completions"]
|
||||
- id: "mimo-v2.5-pro"
|
||||
display_name: "MiMo V2.5 Pro"
|
||||
type: "text"
|
||||
context_window: 1048576 # 第三十三轮(2026-09-24):上下文窗口(token),每日同步维护
|
||||
max_output_tokens: 128000 # 最大输出(token)
|
||||
protocols: ["chat/completions"]
|
||||
- id: "hy4-preview"
|
||||
display_name: "Hy4 Preview"
|
||||
type: "text"
|
||||
@@ -398,7 +384,7 @@ providers:
|
||||
display_name: "Kimi K3"
|
||||
type: "text"
|
||||
context_window: 1048576 # 第三十三轮(2026-09-24):上下文窗口(token),每日同步维护
|
||||
max_output_tokens: 131072 # 最大输出(token)
|
||||
max_output_tokens: 1048576 # 最大输出(token)
|
||||
protocols: ["chat/completions", "messages"]
|
||||
- id: "minimax-m3"
|
||||
display_name: "MiniMax M3"
|
||||
@@ -495,7 +481,7 @@ providers:
|
||||
display_name: "Kimi K3.1 Pro"
|
||||
type: "text"
|
||||
context_window: 1048576 # 同步 2026-10-25(scripts/sync_models.py)
|
||||
max_output_tokens: 131072 # 同步 2026-10-25(scripts/sync_models.py)
|
||||
max_output_tokens: 1048576 # 同步 2026-10-25(scripts/sync_models.py)
|
||||
# 协议线取自官方 Endpoints 表,未逐线实测(现网其它模型是实测过的)
|
||||
protocols: ["chat/completions"]
|
||||
# 2026-10-27 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
@@ -507,6 +493,41 @@ providers:
|
||||
# 协议线取自官方 Endpoints 表,未逐线实测(现网其它模型是实测过的)
|
||||
protocols: ["chat/completions"]
|
||||
free: true # 官方价格表标 Free
|
||||
# 2026-11-06 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
- id: "hy4"
|
||||
display_name: "Hy4"
|
||||
type: "text"
|
||||
context_window: 1048576 # 同步 2026-11-07(scripts/sync_models.py)
|
||||
max_output_tokens: 65536 # 同步 2026-11-07(scripts/sync_models.py)
|
||||
# 协议线取自官方 Endpoints 表,未逐线实测(现网其它模型是实测过的)
|
||||
protocols: ["chat/completions"]
|
||||
# 2026-11-07 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
# 2026-11-10 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
- id: "longcat-2.5-free"
|
||||
display_name: "Longcat 2.5 Free"
|
||||
type: "text"
|
||||
context_window: 1000000 # 同步 2026-11-10(scripts/sync_models.py)
|
||||
max_output_tokens: 262144 # 同步 2026-11-10(scripts/sync_models.py)
|
||||
# 协议线取自官方 Endpoints 表,未逐线实测(现网其它模型是实测过的)
|
||||
protocols: ["chat/completions"]
|
||||
free: true # 官方价格表标 Free
|
||||
# 2026-11-16 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
- id: "hy4-flash-free"
|
||||
display_name: "Hy4 Flash Free"
|
||||
type: "text"
|
||||
context_window: 1048576 # 同步 2026-11-19(scripts/sync_models.py)
|
||||
max_output_tokens: 65536 # 同步 2026-11-19(scripts/sync_models.py)
|
||||
# 协议线取自官方 Endpoints 表,未逐线实测(现网其它模型是实测过的)
|
||||
protocols: ["chat/completions"]
|
||||
free: true # 官方价格表标 Free
|
||||
# 2026-11-16 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
- id: "qwen4-max"
|
||||
display_name: "Qwen4 Max"
|
||||
type: "text"
|
||||
context_window: 1000000 # 同步 2026-11-19(scripts/sync_models.py)
|
||||
max_output_tokens: 262144 # 同步 2026-11-19(scripts/sync_models.py)
|
||||
# 协议线取自官方 Endpoints 表,未逐线实测(现网其它模型是实测过的)
|
||||
protocols: ["messages"]
|
||||
# 2026-10-09 自动同步:官方文档新增(scripts/sync_models.py)
|
||||
# ── Dots AI(小红书 Dots Studio,第三十六轮新增)──────────────
|
||||
# 官方文档:https://dots.ai/platform/docs(2026-09-28 通读)
|
||||
@@ -569,20 +590,25 @@ server:
|
||||
hot_reload: true # 监听 gateway.yaml mtime 自动重载(改配置免重启)
|
||||
hot_reload_interval: 15 # 重载检查间隔(秒)
|
||||
metrics_enabled: true # 记录调用指标(/metrics)
|
||||
rate_limit_rps: 20 # 全局单 user QPS 上限(2026-10-23 由 null 改为 20:防泄露 Key 打爆额度;
|
||||
rate_limit_rps: 50 # 全局单 user QPS 上限(2026-11-06 由 20 改为 50:多客户端并发时 20 太紧)(2026-10-23 由 null 改为 20:防泄露 Key 打爆额度;
|
||||
# 供应商级限流仍由 provider.rate_limit_rps 控制,两者取更严的那个)
|
||||
# 请求体字节上限。2026-09-24 从 2MB 提到 20MB:带图对话(生成/上传的 PNG 以
|
||||
# base64 内联进历史,单张 100KB~750KB)几张就顶爆 2MB → 上游 413
|
||||
# 「请求体超过上限 2000000 字节」。内部网关 + nginx 两层把关,保留限制只调大数字。
|
||||
max_body_size: 20000000
|
||||
cors_origins: ["*"] # CORS 允许来源(生产收紧为具体域名)
|
||||
cors_origins: # CORS 允许来源(2026-11-06 由 ["*"] 收紧为白名单)
|
||||
- "http://127.0.0.1:8808"
|
||||
- "http://localhost:8808"
|
||||
- "http://127.0.0.1:5173" # Vite dev server
|
||||
- "http://localhost:5173"
|
||||
graceful_shutdown: 30 # 优雅关闭等待在途请求的秒数
|
||||
# ── 防滥用 / 安全 ──
|
||||
batch_max_concurrency: 16 # /batch 并发上限(客户端 max_concurrency 会被钳到此值)
|
||||
batch_max_items: 64 # /batch 单次最大条目数(超出返回 400)
|
||||
webhook_allow_private: false # 视频 callback_url 是否允许指向内网/回环(SSRF 防护,默认禁)
|
||||
docs_enabled: false # FastAPI 文档(/docs、/openapi.json)是否开放(安全默认关)
|
||||
auth_fail_limit_per_min: 20 # 同一来源 IP 每分钟鉴权失败上限,超过 → 429(防暴力枚举)
|
||||
auth_fail_limit_per_min: 60 # 同一来源 IP 每分钟鉴权失败上限(2026-11-06 由 20 改为 60:客户端配错 Key 重试容易误触发),超过 → 429(防暴力枚举)
|
||||
auth_fail_ban_seconds: 3600 # 2026-11-06 新增:鉴权失败超限后拉黑 1 小时(0=只限流不拉黑)
|
||||
|
||||
# ── 供应商熔断(Circuit Breaker) ──────────────────────
|
||||
# 某供应商连续/滑动窗口失败达到 failure_threshold 就熔断 cooldown 秒,
|
||||
@@ -606,7 +632,8 @@ pricing:
|
||||
agnes-3.0-flash: { input: 0, output: 0 } # 同步 2026-09-24(原 0.35/1;文档现价 ¥0/M 输入、¥0/M 输出)
|
||||
agnes-2.5-flash: { input: 0, output: 0 } # 文档现价暂免(输入/输出/缓存命中均 ¥0/百万)
|
||||
agnes-2.5-pro: { input: 3, output: 6 } # 2026-09-24 自动同步(文档现价)
|
||||
agnes-2.5-pro-beta: { input: 3, output: 6 } # 2026-10-21 自动同步(文档现价)
|
||||
agnes-2.5-pro-beta: { input: 0.7, output: 2.1 } # 2026-10-21 自动同步(文档现价)
|
||||
agnes-2.5-pro-theta: { input: 0.7, output: 2 } # 2026-11-09 自动同步(文档现价)
|
||||
|
||||
# ── 媒体下载代理白名单(第十七轮)────────────────────────
|
||||
# 生成的图片/视频挂在第三方 CDN 上且不带 CORS 头,浏览器里既 fetch 不到 blob、
|
||||
|
||||
@@ -175,7 +175,7 @@
|
||||
### Step 0 · 建 QwenPaw profile `ai-gateway` ✅ **已完成**(2026-09-29)
|
||||
|
||||
```
|
||||
0. 备份:cp /root/.qwenpaw/config.json → config.json.bak-<日期>(记回滚方式)
|
||||
0. 备份:cp ~/.qwenpaw/config.json → config.json.bak-<日期>(记回滚方式)
|
||||
1. 复制骨架:default 的 workspaces → workspaces/ai-gateway
|
||||
2. 清私人内容:该 profile 的 SOUL.md / AGENTS.md 改写为"网关智能体"版本
|
||||
(不继承"小银"身份、老板的私人上下文、项目记忆)—— 见 §4 已定-B
|
||||
@@ -197,7 +197,7 @@
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 备份 | `config.json.bak-20260929-agents` |
|
||||
| 工作区 | `/root/.qwenpaw/workspaces/ai-gateway/`(**全新空白,未复制 default 的任何私人文件**) |
|
||||
| 工作区 | `<工作区>/`(**全新空白,未复制 default 的任何私人文件**) |
|
||||
| 提示词 | 新写 `SOUL.md` + `AGENTS.md`(网关智能体版);`system_prompt_files: ["AGENTS.md","SOUL.md"]`(**不含 PROFILE.md**) |
|
||||
| 注册 | `config.json` 的 `agents.profiles` + `agent_order` 均已加 `ai-gateway` |
|
||||
| 工具 | ✅ **全开 27 个**(决策⑪);`approval_level: OFF` |
|
||||
@@ -490,8 +490,8 @@ scripts/ci_check.sh 跑绿
|
||||
- 改 `router.ts`、`lib/nav.ts`、`components/Icon.vue`、`locales/zh.ts`、`locales/en.ts`
|
||||
|
||||
**QwenPaw 侧**
|
||||
- 改 `/root/.qwenpaw/config.json`(profiles 加一项)
|
||||
- 新增 `/root/.qwenpaw/workspaces/ai-gateway/`(骨架 + SOUL.md / AGENTS.md)
|
||||
- 改 `~/.qwenpaw/config.json`(profiles 加一项)
|
||||
- 新增 `<工作区>/`(骨架 + SOUL.md / AGENTS.md)
|
||||
|
||||
**文档**
|
||||
- 改 `README.md`、`CHANGELOG.md`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# API 网关 Web 前端 —— 设计文档
|
||||
# 小银网关 Web 前端 —— 设计文档
|
||||
|
||||
> 版本 v0.1(待审)|2026-09-11
|
||||
> 对象:`https://api.wangjinding.com`(网关,端口 8808,已开鉴权,127.0.0.1 反代对外)
|
||||
> 对象:`http://127.0.0.1:8808`(网关,端口 8808,已开鉴权,127.0.0.1 反代对外)
|
||||
|
||||
---
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
## 3. 总体架构与鉴权
|
||||
|
||||
```
|
||||
浏览器 SPA (Vue3) ──同源──> api.wangjinding.com
|
||||
浏览器 SPA (Vue3) ──同源──> 127.0.0.1:8808
|
||||
├─ /web/... 静态资源(Vue 构建产物)
|
||||
├─ POST /auth/login 登录(验 key → 发短时 Cookie/会话 token)
|
||||
├─ POST /v1/* 业务调用(带会话凭证)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# AI 网关项目体检报告(2026-10-23)
|
||||
# 小银网关项目体检报告(2026-10-23)
|
||||
|
||||
> 范围:`/root/dsh/projects/api-gateway`(v2.9.15)。方法:跑测试 + 静态检查 + 数据/权限/备份审计 + 真实接口压测。
|
||||
> 范围:`/root/dsh/projects/<项目>`(v2.9.15)。方法:跑测试 + 静态检查 + 数据/权限/备份审计 + 真实接口压测。
|
||||
|
||||
## 一、已修复(本次体检发现)
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
## 现象
|
||||
|
||||
```
|
||||
POST https://api.wangjinding.com/v1/chat/completions
|
||||
POST http://127.0.0.1:8808/v1/chat/completions
|
||||
Authorization: Bearer wjd-...
|
||||
User-Agent: WorkBuddy/5.8.3 → HTTP 403
|
||||
```
|
||||
@@ -14,7 +14,7 @@ User-Agent: WorkBuddy/5.8.3 → HTTP 403
|
||||
|
||||
## 根因
|
||||
|
||||
`api.wangjinding.com` 前面挂着 **1Panel 的 WAF(1pwaf)**,它会检查**请求体内容**:
|
||||
`127.0.0.1:8808` 前面挂着 **1Panel 的 WAF(1pwaf)**,它会检查**请求体内容**:
|
||||
|
||||
| 请求体里出现 | 结果 |
|
||||
|---|---|
|
||||
@@ -29,7 +29,7 @@ AI 编程客户端(WorkBuddy / Cursor / 各类 CLI)把**用户代码**原样
|
||||
判断依据(WAF 访问日志):
|
||||
|
||||
```
|
||||
/opt/1panel/www/sites/api.wangjinding.com/log/access.log
|
||||
/opt/1panel/www/sites/127.0.0.1:8808/log/access.log
|
||||
117.85.65.211 - - [22/Oct/2026:17:40:26 +0800] "POST /v1/chat/completions HTTP/1.1" 403 16711
|
||||
"-" "WorkBuddy/5.8.3" "116.228.205.72" ← 最后一列是真实客户端 IP(经 EO 回源后)
|
||||
```
|
||||
@@ -65,12 +65,12 @@ docker exec 1Panel-openresty-npAh nginx -s reload
|
||||
```bash
|
||||
K=wjd-... # 任一成员的 Key
|
||||
# 1) 以前被拦的内容现在应 200
|
||||
curl -s -o /dev/null -w '%{http_code}\n' https://api.wangjinding.com/v1/chat/completions \
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8808/v1/chat/completions \
|
||||
-H "Authorization: Bearer $K" -H 'Content-Type: application/json' \
|
||||
-d '{"model":"deepseek-v4.1-flash","messages":[{"role":"user","content":"<script>alert(1)</script> system(\"ls\")"}],"max_tokens":5}'
|
||||
# 2) /v1/ 之外必须仍然拦截(这是安全底线,别把 WAF 整个关掉)
|
||||
curl -s -o /dev/null -w '%{http_code}\n' https://api.wangjinding.com/.env # 期望 403
|
||||
curl -s -o /dev/null -w '%{http_code}\n' https://api.wangjinding.com/etc/passwd # 期望 403
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8808/.env # 期望 403
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8808/etc/passwd # 期望 403
|
||||
```
|
||||
|
||||
## ⚠️ 持久化注意
|
||||
@@ -78,13 +78,13 @@ curl -s -o /dev/null -w '%{http_code}\n' https://api.wangjinding.com/etc/passwd
|
||||
线上这套 WAF 配置由 **阿里云那台的 1Panel 主控**通过 agent 下发。
|
||||
直接改文件**立刻生效**,但如果在面板里保存一次 WAF 设置,这条白名单**可能被覆盖**。
|
||||
|
||||
**建议在面板里也加一遍**:`网站 → api.wangjinding.com → WAF → 白名单 → URL 白名单 → ^/v1/`。
|
||||
**建议在面板里也加一遍**:`网站 → 127.0.0.1:8808 → WAF → 白名单 → URL 白名单 → ^/v1/`。
|
||||
之后如果又出现 403,先按本文「判断依据」确认是不是 WAF,再补规则即可。
|
||||
|
||||
## 给调用方的配置口径
|
||||
|
||||
```
|
||||
Base URL : https://api.wangjinding.com/v1
|
||||
Base URL : http://127.0.0.1:8808/v1
|
||||
API Key : wjd-...(成员自己的 Key)
|
||||
Model : deepseek-v4.1-flash ← 注意不要写 opencode/deepseek-v4.1-flash(会 400 未知模型)
|
||||
或 wjd ← 虚拟 id,由管理员在网关里映射到具体模型
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>API 网关管理台</title>
|
||||
<title>小银网关管理台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
Generated
+2
-2
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "api-gateway-web",
|
||||
"name": "xiaoyin-gateway-web",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "api-gateway-web",
|
||||
"name": "xiaoyin-gateway-web",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"dompurify": "^3.4.15",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "api-gateway-web",
|
||||
"name": "xiaoyin-gateway-web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
|
||||
@@ -161,7 +161,7 @@ const pageSub = computed(() => {
|
||||
const key = String(route.name || '')
|
||||
const sub = t(`nav.sub${key}`)
|
||||
// 没写副标题的页面,t() 会把 key 原样返回 —— 这时显示连接地址兜底
|
||||
return sub.startsWith('nav.') ? 'api.wangjinding.com' : sub
|
||||
return sub.startsWith('nav.') ? location.host : sub
|
||||
})
|
||||
|
||||
function onTheme(cmd: string | number | object) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<span class="logo"><Icon name="bolt" :size="17" /></span>
|
||||
<div>
|
||||
<b>{{ t('nav.title') }}</b>
|
||||
<span>api.wangjinding.com</span>
|
||||
<span>{{ apiHost }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const apiHost = location.host
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -45,6 +45,7 @@ export function navGroups(isAdmin: boolean): NavGroup[] {
|
||||
// 第二十二轮定稿:管理员只处理反馈(「用户反馈」),不提意见 —— 所以这两项互斥。
|
||||
if (isAdmin) sys.push({ path: '/users', key: 'users', icon: 'users' })
|
||||
if (isAdmin) sys.push({ path: '/feedback-inbox', key: 'feedbackinbox', icon: 'inbox' })
|
||||
if (isAdmin) sys.push({ path: '/banned', key: 'banned', icon: 'ban' })
|
||||
// 第二十三轮追加:老板要求「网关配置先不要删掉、先隐藏起来,这块先不支持页面配置」→
|
||||
// 入口由 `lib/features.ts` 的开关统一控制(页面与路由都还在,只是不挂出来)。
|
||||
if (isAdmin && GATEWAY_CONFIG_ENABLED) sys.push({ path: '/gateway-config', key: 'gatewaycfg', icon: 'sliders' })
|
||||
|
||||
@@ -1,8 +1,72 @@
|
||||
// English locale resource
|
||||
export default {
|
||||
banned: {
|
||||
title: 'Banned IPs',
|
||||
count: '{n} IP(s) banned',
|
||||
rule: 'An IP is auto-banned for {mins} min after {n} auth failures within a minute. While banned, every API request from it returns 429; other sources are unaffected.',
|
||||
remaining: '{mins} min left',
|
||||
until: 'Unban at',
|
||||
unban: 'Unban',
|
||||
empty: 'No banned IPs',
|
||||
unbanned: 'Unbanned {ip}',
|
||||
clearAll: 'Unban all',
|
||||
clearTitle: 'Clear all bans',
|
||||
clearConfirm: 'Clear all bans? Those IPs can access immediately afterwards.',
|
||||
cleared: 'Cleared {n} ban(s)',
|
||||
manualTitle: 'Manual ban',
|
||||
manualSub: 'Ban an IP right away instead of waiting for the auto rule',
|
||||
manualHint: 'Public IPs only. Loopback and private ranges (10./192.168./172.) cannot be banned, so the local reverse proxy and your own LAN devices stay reachable.',
|
||||
ipPlaceholder: 'IP address, e.g. 1.2.3.4',
|
||||
notePlaceholder: 'Note (optional, e.g. "brute force")',
|
||||
doBan: 'Ban',
|
||||
ipRequired: 'Please enter an IP address',
|
||||
banned: 'Banned {ip} for {mins} min',
|
||||
bannedForever: 'Permanently banned {ip}',
|
||||
extend: 'Extend',
|
||||
extended: 'Extended {ip} by {mins} min',
|
||||
extendedForever: '{ip} is now banned permanently',
|
||||
toPermanent: 'Make permanent',
|
||||
permanentTag: 'permanent',
|
||||
neverExpire: 'Permanent — will not expire automatically',
|
||||
historyTitle: 'Ban history',
|
||||
historySub: 'Recent actions (ban / unban / extend)',
|
||||
historyEmpty: 'No ban actions yet',
|
||||
unitDay: '{n} day(s)',
|
||||
unitHour: '{n} hour(s)',
|
||||
unitMin: '{n} min',
|
||||
hisOps: 'Action',
|
||||
hisDelete: 'Delete',
|
||||
hisDeleted: 'History entry deleted',
|
||||
hisClearAll: 'Clear history',
|
||||
hisClearConfirm: 'Clear all ban history? This cannot be undone (active bans are not affected).',
|
||||
hisCleared: 'Cleared {n} history entries',
|
||||
hisTime: 'Time',
|
||||
hisAction: 'Action',
|
||||
hisIp: 'IP',
|
||||
hisDuration: 'Duration',
|
||||
hisActor: 'By',
|
||||
hisNote: 'Note',
|
||||
act: {
|
||||
manual_ban: 'manual ban',
|
||||
auto_ban: 'auto ban',
|
||||
extend: 'extend',
|
||||
unban: 'unban',
|
||||
unban_all: 'clear all',
|
||||
},
|
||||
dur: {
|
||||
m10: '10 minutes',
|
||||
m30: '30 minutes',
|
||||
h1: '1 hour',
|
||||
h6: '6 hours',
|
||||
d1: '1 day',
|
||||
d30: '30 days',
|
||||
forever: 'permanent',
|
||||
},
|
||||
},
|
||||
|
||||
nav: {
|
||||
title: 'API Gateway',
|
||||
connected: 'Connected to api.wangjinding.com',
|
||||
title: 'Xiaoyin Gateway',
|
||||
connected: 'Connected',
|
||||
disconnected: 'Connection error',
|
||||
menudashboard: 'Dashboard',
|
||||
menuchat: 'Chat',
|
||||
@@ -16,6 +80,7 @@ export default {
|
||||
menulogs: 'Logs',
|
||||
menufeedback: 'Feedback',
|
||||
menufeedbackinbox: 'User feedback',
|
||||
menubanned: 'Banned IPs',
|
||||
feedbackTodoTip: '{n} pending (open + in progress)',
|
||||
menusettings: 'Settings',
|
||||
control: 'Console',
|
||||
@@ -75,7 +140,7 @@ export default {
|
||||
cancel: 'Cancel',
|
||||
},
|
||||
login: {
|
||||
title: 'API Gateway Console',
|
||||
title: 'Xiaoyin Gateway Console',
|
||||
userPlaceholder: 'Username',
|
||||
passPlaceholder: 'Password',
|
||||
btn: 'Sign in',
|
||||
@@ -551,6 +616,15 @@ export default {
|
||||
providers: 'Providers',
|
||||
loadErr: 'Failed to load models',
|
||||
capability: 'Capability',
|
||||
// 2026-11-19: OpenCode Go plan quota + training policy (from the official models API's go field)
|
||||
goQuota: 'Go quota',
|
||||
goQuotaHint: 'Monthly allowance each plan covers when you use only this model (official go.monthly_usage)',
|
||||
goQuotaValues: 'Go ${go}/mo · Go Plus ${plus}/mo · Go Teams ${teams}/mo',
|
||||
goQuotaFree: 'Free',
|
||||
goTrainingNo: 'No training',
|
||||
goTrainingYes: 'Trains',
|
||||
goTrainingHint: 'Official go.training flag: whether this model trains on your requests',
|
||||
goZdrHint: 'Zero data retention: upstream keeps none of your content',
|
||||
visionTag: 'Vision',
|
||||
freeTag: 'Free',
|
||||
freeHint: 'Officially free model: no usage-based billing (quota is set by the vendor; both the Agnes and OpenCode Go free tiers are labelled)',
|
||||
|
||||
@@ -1,8 +1,72 @@
|
||||
// 中文文案资源
|
||||
export default {
|
||||
banned: {
|
||||
title: '封禁列表',
|
||||
count: '共 {n} 个 IP 被封',
|
||||
rule: '同一 IP 每分钟鉴权失败达到 {n} 次即自动封禁 {mins} 分钟;被封期间该 IP 的所有 API 请求返回 429,其他来源不受影响。',
|
||||
remaining: '剩余 {mins} 分钟',
|
||||
until: '解封时间',
|
||||
unban: '解封',
|
||||
empty: '当前没有被封禁的 IP',
|
||||
unbanned: '已解封 {ip}',
|
||||
clearAll: '全部解封',
|
||||
clearTitle: '清空全部封禁',
|
||||
clearConfirm: '确定清空全部封禁?清空后这些 IP 可以立即重新访问。',
|
||||
cleared: '已清空 {n} 个封禁',
|
||||
manualTitle: '手动封禁',
|
||||
manualSub: '立即拉黑指定 IP,不必等它触发自动规则',
|
||||
manualHint: '只支持公网 IP;回环地址和内网段(10./192.168./172.)不允许封禁,避免把本机反代或自家设备锁死。',
|
||||
ipPlaceholder: 'IP 地址,例如 1.2.3.4',
|
||||
notePlaceholder: '备注(可选,例如「持续爆破」)',
|
||||
doBan: '封禁',
|
||||
ipRequired: '请先填写 IP 地址',
|
||||
banned: '已封禁 {ip},时长 {mins} 分钟',
|
||||
bannedForever: '已永久封禁 {ip}',
|
||||
extend: '延长',
|
||||
extended: '已为 {ip} 延长 {mins} 分钟',
|
||||
extendedForever: '{ip} 已改为永久封禁',
|
||||
toPermanent: '改为永久',
|
||||
permanentTag: '永久',
|
||||
neverExpire: '永久有效,不会自动解封',
|
||||
historyTitle: '封禁历史',
|
||||
historySub: '最近的操作记录(封禁 / 解封 / 延长)',
|
||||
historyEmpty: '还没有封禁操作记录',
|
||||
unitDay: '{n} 天',
|
||||
unitHour: '{n} 小时',
|
||||
unitMin: '{n} 分钟',
|
||||
hisOps: '操作',
|
||||
hisDelete: '删除',
|
||||
hisDeleted: '已删除该条历史',
|
||||
hisClearAll: '清空历史',
|
||||
hisClearConfirm: '确定清空全部封禁历史?此操作不可恢复(不会影响当前封禁)。',
|
||||
hisCleared: '已清空 {n} 条历史',
|
||||
hisTime: '时间',
|
||||
hisAction: '操作',
|
||||
hisIp: 'IP',
|
||||
hisDuration: '时长',
|
||||
hisActor: '操作人',
|
||||
hisNote: '备注',
|
||||
act: {
|
||||
manual_ban: '手动封禁',
|
||||
auto_ban: '自动封禁',
|
||||
extend: '延长',
|
||||
unban: '解封',
|
||||
unban_all: '清空',
|
||||
},
|
||||
dur: {
|
||||
m10: '10 分钟',
|
||||
m30: '30 分钟',
|
||||
h1: '1 小时',
|
||||
h6: '6 小时',
|
||||
d1: '1 天',
|
||||
d30: '30 天',
|
||||
forever: '永久',
|
||||
},
|
||||
},
|
||||
|
||||
nav: {
|
||||
title: 'API 网关',
|
||||
connected: '已连接 api.wangjinding.com',
|
||||
title: '小银网关',
|
||||
connected: '已连接',
|
||||
disconnected: '连接异常',
|
||||
menudashboard: '仪表盘',
|
||||
menuchat: '对话',
|
||||
@@ -16,6 +80,7 @@ export default {
|
||||
menulogs: '日志',
|
||||
menufeedback: '意见反馈',
|
||||
menufeedbackinbox: '用户反馈',
|
||||
menubanned: '封禁管理',
|
||||
feedbackTodoTip: '{n} 条待办(未处理 + 处理中)',
|
||||
menusettings: '设置',
|
||||
control: '控制台',
|
||||
@@ -75,7 +140,7 @@ export default {
|
||||
cancel: '取消',
|
||||
},
|
||||
login: {
|
||||
title: 'API 网关管理台',
|
||||
title: '小银网关管理台',
|
||||
userPlaceholder: '用户名',
|
||||
passPlaceholder: '密码',
|
||||
btn: '登录',
|
||||
@@ -556,6 +621,15 @@ export default {
|
||||
providers: '供应商',
|
||||
loadErr: '加载模型失败',
|
||||
capability: '能力',
|
||||
// 2026-11-19:OpenCode Go 的套餐额度与训练策略(数据来自官方 models 接口的 go 字段)
|
||||
goQuota: 'Go 额度',
|
||||
goQuotaHint: '只用这一个模型时,各套餐每月额度能覆盖多少用量(官方 models 接口的 go.monthly_usage)',
|
||||
goQuotaValues: 'Go ${go}/月 · Go Plus ${plus}/月 · Go Teams ${teams}/月',
|
||||
goQuotaFree: '免费',
|
||||
goTrainingNo: '不训练',
|
||||
goTrainingYes: '会训练',
|
||||
goTrainingHint: '官方 go.training:该模型是否用你的请求内容做训练',
|
||||
goZdrHint: '零数据保留:上游不保留请求内容',
|
||||
visionTag: '视觉',
|
||||
freeTag: '免费',
|
||||
freeHint: '官方免费模型:不按用量计费(额度以官方为准;Agnes 与 OpenCode Go 的免费档都会标出来)',
|
||||
|
||||
@@ -25,6 +25,7 @@ const router = createRouter({
|
||||
{ path: 'keys', name: 'keys', component: () => import('./views/ApiKeys.vue') },
|
||||
{ path: 'users', name: 'users', component: () => import('./views/Users.vue'), meta: { admin: true } },
|
||||
{ path: 'feedback-inbox', name: 'feedbackinbox', component: () => import('./views/FeedbackInbox.vue'), meta: { admin: true } },
|
||||
{ path: 'banned', name: 'banned', component: () => import('./views/Banned.vue'), meta: { admin: true } },
|
||||
{ path: 'feedback', name: 'feedback', component: () => import('./views/Feedback.vue'), meta: { memberOnly: true } },
|
||||
{ path: 'gateway-config', name: 'gatewaycfg', component: () => import('./views/GatewayConfig.vue'), meta: { admin: true } },
|
||||
{ path: 'logs', name: 'logs', component: () => import('./views/Logs.vue') },
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
<template>
|
||||
<div class="page page-col">
|
||||
<!-- ── 手动封禁 ─────────────────────────────────────────── -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<Icon name="ban" :size="15" />
|
||||
<b>{{ t('banned.manualTitle') }}</b>
|
||||
<span class="sub">{{ t('banned.manualSub') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="ban-form">
|
||||
<el-input
|
||||
v-model="newIp" size="small" class="w-ip" clearable
|
||||
:placeholder="t('banned.ipPlaceholder')" @keyup.enter="doBan"
|
||||
/>
|
||||
<el-select v-model="newDur" size="small" class="w-dur">
|
||||
<el-option
|
||||
v-for="o in DURATIONS" :key="o.k" :value="o.k"
|
||||
:label="t(`banned.dur.${o.k}`)"
|
||||
/>
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="newNote" size="small" class="w-note" clearable
|
||||
:placeholder="t('banned.notePlaceholder')" @keyup.enter="doBan"
|
||||
/>
|
||||
<el-button type="primary" size="small" :loading="banning" @click="doBan">
|
||||
<Icon name="ban" :size="13" /><span>{{ t('banned.doBan') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="form-hint">
|
||||
<Icon name="bell" :size="12" />
|
||||
<span>{{ t('banned.manualHint') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── 封禁列表 ─────────────────────────────────────────── -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('banned.title') }}</b>
|
||||
<span class="sub">{{ t('banned.count', { n: items.length }) }}</span>
|
||||
<div class="pager">
|
||||
<el-button size="small" :loading="loading" @click="reload">
|
||||
<Icon name="refresh" :size="13" /><span>{{ t('common.refresh') }}</span>
|
||||
</el-button>
|
||||
<el-button size="small" type="danger" plain :disabled="!items.length" @click="clearAll">
|
||||
<Icon name="trash" :size="13" /><span>{{ t('banned.clearAll') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="warn-bar">
|
||||
<Icon name="ban" :size="14" />
|
||||
<span>{{ t('banned.rule', { n: limit, mins: banMinutes }) }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="items.length" class="ban-list">
|
||||
<div v-for="b in items" :key="b.ip" class="ban-row">
|
||||
<span class="dot" :class="{ perm: b.permanent }" />
|
||||
<div class="ban-main">
|
||||
<div class="ban-top">
|
||||
<b class="code ban-ip">{{ b.ip }}</b>
|
||||
<el-tag v-if="b.permanent" size="small" type="danger" effect="plain">
|
||||
{{ t('banned.permanentTag') }}
|
||||
</el-tag>
|
||||
<el-tag v-if="b.note" size="small" type="warning" effect="plain">
|
||||
{{ b.note }}
|
||||
</el-tag>
|
||||
</div>
|
||||
<div class="ban-meta">
|
||||
<template v-if="b.permanent">
|
||||
<span>{{ t('banned.neverExpire') }}</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span>{{ t('banned.remaining', { mins: b.remaining_minutes }) }}</span>
|
||||
<span class="sep">·</span>
|
||||
<span>{{ t('banned.until') }} {{ fmtTs(b.banned_until) }}</span>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ban-acts">
|
||||
<el-dropdown trigger="click" :disabled="b.permanent" @command="(k: string) => extend(b.ip, k)">
|
||||
<el-button size="small" :disabled="b.permanent">
|
||||
<Icon name="plus" :size="13" /><span>{{ t('banned.extend') }}</span>
|
||||
</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item v-for="o in DURATIONS" :key="o.k" :command="o.k">
|
||||
+{{ t(`banned.dur.${o.k}`) }}
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item command="forever" divided>
|
||||
{{ t('banned.toPermanent') }}
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<el-button size="small" @click="unban(b.ip)">
|
||||
<Icon name="check" :size="13" /><span>{{ t('banned.unban') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else :description="t('banned.empty')" :image-size="72" />
|
||||
</div>
|
||||
|
||||
<!-- ── 封禁历史 ─────────────────────────────────────────── -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<Icon name="log" :size="15" />
|
||||
<b>{{ t('banned.historyTitle') }}</b>
|
||||
<span class="sub">{{ t('banned.historySub') }}</span>
|
||||
<div class="pager">
|
||||
<el-select v-model="hisLimit" size="small" class="w-his" @change="loadHistory">
|
||||
<el-option :value="20" label="20" />
|
||||
<el-option :value="50" label="50" />
|
||||
<el-option :value="100" label="100" />
|
||||
</el-select>
|
||||
<el-button size="small" :loading="hisLoading" @click="loadHistory">
|
||||
<Icon name="refresh" :size="13" /><span>{{ t('common.refresh') }}</span>
|
||||
</el-button>
|
||||
<el-button size="small" type="danger" plain :disabled="!history.length" @click="clearHistory">
|
||||
<Icon name="trash" :size="13" /><span>{{ t('banned.hisClearAll') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-table v-if="history.length" :data="history" size="small" class="his-table">
|
||||
<el-table-column :label="t('banned.hisTime')" width="150">
|
||||
<template #default="{ row }">{{ fmtTs(row.ts) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('banned.hisAction')" width="110">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="ACTION_TAG[row.action] || 'info'" size="small" effect="plain">
|
||||
{{ t(`banned.act.${row.action}`) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('banned.hisIp')" min-width="140">
|
||||
<template #default="{ row }"><span class="code">{{ row.ip }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('banned.hisDuration')" width="110">
|
||||
<template #default="{ row }">
|
||||
{{ row.permanent ? t('banned.permanentTag') : (row.seconds ? fmtDur(row.seconds) : '—') }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('banned.hisActor')" width="110">
|
||||
<template #default="{ row }">{{ row.actor || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('banned.hisNote')" min-width="140">
|
||||
<template #default="{ row }"><span class="muted-2">{{ row.note || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('banned.hisOps')" width="76" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button size="small" type="danger" text :title="t('common.delete')" @click="delHistory(row)">
|
||||
<Icon name="trash" :size="13" />
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else :description="t('banned.historyEmpty')" :image-size="60" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { api, errText } from '../api'
|
||||
import Icon from '../components/Icon.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const items = ref<any[]>([])
|
||||
const history = ref<any[]>([])
|
||||
const loading = ref(false)
|
||||
const banning = ref(false)
|
||||
const hisLoading = ref(false)
|
||||
const hisLimit = ref(50)
|
||||
const limit = ref(60)
|
||||
const banSeconds = ref(3600)
|
||||
let timer: any = null
|
||||
|
||||
const newIp = ref('')
|
||||
const newDur = ref('h1')
|
||||
const newNote = ref('')
|
||||
|
||||
const banMinutes = computed(() => Math.max(1, Math.round(banSeconds.value / 60)))
|
||||
|
||||
/** 时长预设。forever 走 permanent 字段,其余按秒传。 */
|
||||
const DURATIONS = [
|
||||
{ k: 'm10', v: 600 },
|
||||
{ k: 'm30', v: 1800 },
|
||||
{ k: 'h1', v: 3600 },
|
||||
{ k: 'h6', v: 21600 },
|
||||
{ k: 'd1', v: 86400 },
|
||||
{ k: 'd30', v: 2592000 },
|
||||
{ k: 'forever', v: 0 },
|
||||
] as { k: string; v: number }[]
|
||||
|
||||
const ACTION_TAG: Record<string, string> = {
|
||||
manual_ban: 'warning',
|
||||
auto_ban: 'info',
|
||||
extend: 'primary',
|
||||
unban: 'success',
|
||||
unban_all: 'danger',
|
||||
}
|
||||
|
||||
function fmtTs(ts: number): string {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts * 1000)
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
|
||||
function fmtDur(sec: number): string {
|
||||
if (sec >= 86400 && sec % 86400 === 0) return t('banned.unitDay', { n: sec / 86400 })
|
||||
if (sec >= 3600) return t('banned.unitHour', { n: Math.round(sec / 3600) })
|
||||
return t('banned.unitMin', { n: Math.round(sec / 60) })
|
||||
}
|
||||
|
||||
function durPayload(k: string): any {
|
||||
if (k === 'forever') return { permanent: true }
|
||||
const d = DURATIONS.find((x) => x.k === k)
|
||||
return { seconds: d ? d.v : 3600 }
|
||||
}
|
||||
|
||||
async function reload() {
|
||||
loading.value = true
|
||||
try {
|
||||
const j = await api('/admin/banned')
|
||||
items.value = j.items || []
|
||||
if (typeof j.auth_fail_limit_per_min === 'number') limit.value = j.auth_fail_limit_per_min
|
||||
if (typeof j.ban_seconds === 'number' && j.ban_seconds > 0) banSeconds.value = j.ban_seconds
|
||||
} catch (e: any) {
|
||||
ElMessage.error(errText(e))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
hisLoading.value = true
|
||||
try {
|
||||
const j = await api(`/admin/banned/history?limit=${hisLimit.value}`)
|
||||
history.value = j.items || []
|
||||
} catch (e: any) {
|
||||
ElMessage.error(errText(e))
|
||||
} finally {
|
||||
hisLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function doBan() {
|
||||
const ip = newIp.value.trim()
|
||||
if (!ip) { ElMessage.warning(t('banned.ipRequired')); return }
|
||||
banning.value = true
|
||||
try {
|
||||
const j = await api('/admin/banned', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ip, note: newNote.value.trim(), ...durPayload(newDur.value) }),
|
||||
})
|
||||
ElMessage.success(
|
||||
j.permanent
|
||||
? t('banned.bannedForever', { ip: j.ip })
|
||||
: t('banned.banned', { ip: j.ip, mins: Math.round(j.banned_seconds / 60) }),
|
||||
)
|
||||
newIp.value = ''
|
||||
newNote.value = ''
|
||||
await Promise.all([reload(), loadHistory()])
|
||||
} catch (e: any) {
|
||||
ElMessage.error(errText(e))
|
||||
} finally {
|
||||
banning.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function extend(ip: string, k: string) {
|
||||
try {
|
||||
const j = await api(`/admin/banned/${encodeURIComponent(ip)}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(durPayload(k)),
|
||||
})
|
||||
ElMessage.success(
|
||||
j.permanent ? t('banned.extendedForever', { ip }) : t('banned.extended', { ip, mins: Math.round(j.extended_seconds / 60) }),
|
||||
)
|
||||
await Promise.all([reload(), loadHistory()])
|
||||
} catch (e: any) {
|
||||
ElMessage.error(errText(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function unban(ip: string) {
|
||||
try {
|
||||
await api(`/admin/banned/${encodeURIComponent(ip)}`, { method: 'DELETE' })
|
||||
ElMessage.success(t('banned.unbanned', { ip }))
|
||||
await Promise.all([reload(), loadHistory()])
|
||||
} catch (e: any) {
|
||||
ElMessage.error(errText(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function delHistory(row: any) {
|
||||
try {
|
||||
await api(`/admin/banned/history/${encodeURIComponent(row.id)}`, { method: 'DELETE' })
|
||||
ElMessage.success(t('banned.hisDeleted'))
|
||||
await loadHistory()
|
||||
} catch (e: any) {
|
||||
ElMessage.error(errText(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function clearHistory() {
|
||||
try {
|
||||
await ElMessageBox.confirm(t('banned.hisClearConfirm'), t('banned.hisClearAll'), { type: 'warning' })
|
||||
} catch { return }
|
||||
try {
|
||||
const j = await api('/admin/banned/history', { method: 'DELETE' })
|
||||
ElMessage.success(t('banned.hisCleared', { n: j.cleared ?? 0 }))
|
||||
await loadHistory()
|
||||
} catch (e: any) {
|
||||
ElMessage.error(errText(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function clearAll() {
|
||||
try {
|
||||
await ElMessageBox.confirm(t('banned.clearConfirm'), t('banned.clearTitle'), { type: 'warning' })
|
||||
} catch { return }
|
||||
try {
|
||||
const j = await api('/admin/banned', { method: 'DELETE' })
|
||||
ElMessage.success(t('banned.cleared', { n: j.cleared ?? 0 }))
|
||||
await Promise.all([reload(), loadHistory()])
|
||||
} catch (e: any) {
|
||||
ElMessage.error(errText(e))
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
reload()
|
||||
loadHistory()
|
||||
timer = setInterval(reload, 10000)
|
||||
})
|
||||
onUnmounted(() => { if (timer) clearInterval(timer) })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 手动封禁表单:一行放下,窄屏自动换行 */
|
||||
.ban-form { display: flex; align-items: center; gap: var(--gap-sm); flex-wrap: wrap; }
|
||||
.w-ip { width: 220px; }
|
||||
.w-dur { width: 130px; }
|
||||
.w-note { width: 200px; }
|
||||
.w-his { width: 84px; }
|
||||
.form-hint {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
margin-top: var(--gap-sm); font-size: 11.5px; line-height: 1.6; color: var(--muted-2);
|
||||
}
|
||||
.form-hint .gw-icon { flex: none; }
|
||||
|
||||
/* 规则提示条 —— 与 ApiKeys 的 warn-bar 同一套观感(那边是 scoped,这里要自带) */
|
||||
.warn-bar {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
background: var(--warn-soft); color: var(--warn);
|
||||
border-radius: var(--radius-s); padding: 9px 12px;
|
||||
font-size: 12px; line-height: 1.6; margin-bottom: var(--gap-sm);
|
||||
}
|
||||
.warn-bar .gw-icon { flex: none; }
|
||||
|
||||
.ban-list { display: flex; flex-direction: column; }
|
||||
.ban-row {
|
||||
display: flex; align-items: center; gap: var(--gap-sm);
|
||||
padding: 11px 2px; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.ban-row:last-child { border-bottom: none; }
|
||||
.ban-row .dot {
|
||||
flex: none; width: 7px; height: 7px; border-radius: 50%;
|
||||
background: var(--warn);
|
||||
}
|
||||
.ban-row .dot.perm { background: var(--err, #e5484d); }
|
||||
.ban-main { flex: 1; min-width: 0; }
|
||||
.ban-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.ban-ip { font-size: 13px; font-weight: 600; }
|
||||
.ban-meta {
|
||||
margin-top: 3px; font-size: 11.5px; color: var(--muted-2);
|
||||
display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
|
||||
}
|
||||
.ban-meta .sep { color: var(--line); }
|
||||
.ban-acts { display: flex; align-items: center; gap: 6px; flex: none; }
|
||||
.his-table { width: 100%; }
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.w-ip, .w-note, .w-dur { width: 100%; }
|
||||
.ban-form :deep(.el-button) { width: 100%; }
|
||||
.ban-row { flex-wrap: wrap; }
|
||||
.ban-acts { width: 100%; justify-content: flex-end; }
|
||||
}
|
||||
</style>
|
||||
@@ -152,7 +152,7 @@ async function saveYaml() {
|
||||
function backupCfg() {
|
||||
const envs: Record<string, string> = {}
|
||||
for (const e of envKeys.value) envs[e.env] = e.value
|
||||
const data = { kind: 'api-gateway-backup', version: 1, config: yamlText.value, envs }
|
||||
const data = { kind: 'xiaoyin-gateway-backup', version: 1, config: yamlText.value, envs }
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
|
||||
const a = document.createElement('a')
|
||||
a.href = URL.createObjectURL(blob)
|
||||
|
||||
@@ -144,7 +144,7 @@
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { api } from '../api'
|
||||
import { api, errText } from '../api'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import { stamp } from '../lib/download'
|
||||
import { useSessionStore } from '../store/session'
|
||||
@@ -209,7 +209,7 @@ async function loadFull(row: any) {
|
||||
row.respLen = d.completion_len || 0
|
||||
row.full = true
|
||||
} catch (e: any) {
|
||||
row.fullErr = err(e)
|
||||
row.fullErr = errText(e)
|
||||
} finally {
|
||||
row.fullLoading = false
|
||||
}
|
||||
|
||||
@@ -134,6 +134,26 @@
|
||||
<span v-if="!row.vision && !paramKeys(row).length" class="muted-2">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<!-- 2026-11-19(老板要求):OpenCode Go 的套餐额度与训练策略。
|
||||
额度 = 「只用这一个模型时,该套餐每月能覆盖多少用量」(官方 go.monthly_usage,美元);
|
||||
训练 = 官方 go.training(false = 不拿你的请求训练)。
|
||||
只有 OpenCode Go 的模型带这个字段,其余供应商显示「—」。 -->
|
||||
<el-table-column width="150">
|
||||
<template #header>
|
||||
<el-tooltip :content="t('models.goQuotaHint')" placement="top">
|
||||
<span class="proto-th">{{ t('models.goQuota') }}</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<template v-if="row.goMeta">
|
||||
<span class="pill go-quota cap" :title="goQuotaHint(row)">{{ goQuotaText(row) }}</span>
|
||||
<span class="pill cap" :class="goTrains(row) ? 'err' : 'ok'" :title="t('models.goTrainingHint')">
|
||||
{{ goTrains(row) ? t('models.goTrainingYes') : t('models.goTrainingNo') }}
|
||||
</span>
|
||||
</template>
|
||||
<span v-else class="muted-2">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('models.keySet')" width="90">
|
||||
<template #default="{ row }">
|
||||
<span class="pill" :class="row.key_set ? 'ok' : 'err'">
|
||||
@@ -431,6 +451,10 @@ const textModelRows = computed(() =>
|
||||
paramNote: paramKeys(m).length ? paramNote(m) : '',
|
||||
// 支持的格式(第二十七轮):悬浮这一行就能看到「能用哪几条线 + 本次测速走的哪条」
|
||||
formats: protocolsOf(m),
|
||||
// 2026-11-19(老板要求):OpenCode Go 的套餐额度(每月能调多少)与训练策略。
|
||||
// 后端 /v1/models 的 go 字段(app/gomodels.py 从官方 models 接口拉取,缓存 6 小时);
|
||||
// 非 OpenCode 供应商没有这个字段 → 该列显示「—」。
|
||||
goMeta: m.go || null,
|
||||
})),
|
||||
)
|
||||
|
||||
@@ -454,6 +478,43 @@ function freeHint(m: any): string {
|
||||
return m && m.free_limited ? t('models.freeLimitedHint') : t('models.freeHint')
|
||||
}
|
||||
|
||||
// ── OpenCode Go 套餐额度 / 训练策略(2026-11-19 老板要求)──
|
||||
// 数据来自后端 /v1/models 的 go 字段(app/gomodels.py ← 官方 models 接口 go.monthly_usage)。
|
||||
// 官方口径:monthly_usage 是「只用这一个模型时,各套餐每月额度能覆盖多少用量」(美元)。
|
||||
// 单元格里只显示默认档(Go),三档明细与零保留说明放悬浮提示。
|
||||
const GO_PLAN_KEYS = ['go', 'go-plus', 'go-teams'] as const
|
||||
|
||||
function goUsageOf(m: any): Record<string, number> {
|
||||
return (m && m.goMeta && m.goMeta.monthly_usage) || {}
|
||||
}
|
||||
|
||||
function goQuotaText(m: any): string {
|
||||
const u = goUsageOf(m)
|
||||
if (u.go) return `$${u.go}`
|
||||
if (m && m.free) return t('models.goQuotaFree')
|
||||
return '—'
|
||||
}
|
||||
|
||||
function goQuotaHint(m: any): string {
|
||||
const u = goUsageOf(m)
|
||||
const parts: string[] = []
|
||||
if (GO_PLAN_KEYS.some((k) => u[k])) {
|
||||
parts.push(t('models.goQuotaValues', {
|
||||
go: u.go ?? '—',
|
||||
plus: u['go-plus'] ?? '—',
|
||||
teams: u['go-teams'] ?? '—',
|
||||
}))
|
||||
} else {
|
||||
parts.push(t('models.goQuotaHint'))
|
||||
}
|
||||
if (m && m.goMeta && m.goMeta.zdr) parts.push(t('models.goZdrHint'))
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
function goTrains(m: any): boolean {
|
||||
return !!(m && m.goMeta && m.goMeta.training)
|
||||
}
|
||||
|
||||
// ── 模型级强制参数(第二十五轮)──
|
||||
// 后端 /v1/models 在 params 里给出「该模型发往上游前会被强制覆盖的参数」
|
||||
// (例:kimi-k2.7-code 只接受 temperature=1)。这里只做展示,不提供编辑入口。
|
||||
@@ -471,7 +532,12 @@ const keySet = computed(() => {
|
||||
for (const p of Object.values(health.value.providers || {}) as any) ks[p.name] = !!p.api_key_set
|
||||
return ks
|
||||
})
|
||||
const modelRows = computed(() => models.value.map((m) => ({ ...m, key_set: keySet.value[m.provider_name] })))
|
||||
// 主表格的行数据(表格绑的就是 modelRows:`{...m}` 展开原始模型,保留全部接口字段)。
|
||||
// 2026-11-19:OpenCode Go 的套餐额度/训练列读 row.goMeta —— 必须在这里挂上,
|
||||
// 只挂在 textModelRows(另一个只用来数数量/测速的数组)上表格是看不到的。
|
||||
const modelRows = computed(() =>
|
||||
models.value.map((m) => ({ ...m, key_set: keySet.value[m.provider_name], goMeta: m.go || null })),
|
||||
)
|
||||
|
||||
const providerRows = computed(() => {
|
||||
const p = health.value.providers || {}
|
||||
@@ -597,6 +663,8 @@ onUnmounted(() => {
|
||||
.plock { color: var(--warn); }
|
||||
/* 免费模型:绿色系,跟「视觉」(主题色) / 「参数固定」(橙) 区分开;跟在模型名后面 */
|
||||
.pill.free { background: rgba(16, 185, 129, 0.14); color: #059669; }
|
||||
/* OpenCode Go 的套餐额度(2026-11-19):中性蓝,与免费(绿)/ 参数固定(橙)区分 */
|
||||
.pill.go-quota { background: rgba(59, 130, 246, 0.12); color: #2563eb; }
|
||||
/* 免费标注的间距(2026-09-24 老板:间隔不一样)——
|
||||
表格单元格里是行内排布、没有 flex gap,靠这个 margin 与模型名分开;
|
||||
测速行是 flex(.st-row gap: 8px),必须把 margin 归零:否则标签左侧 8+6=14px、
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# 开发/测试依赖(生产不需要)
|
||||
-r requirements.txt
|
||||
pytest>=8.0 # tests/ 有 225 个用例:/root/.venvs/api-gateway/bin/python -m pytest tests/ -q
|
||||
pytest>=8.0 # tests/ 有 225 个用例:/root/.venvs/xiaoyin-gateway/bin/python -m pytest tests/ -q
|
||||
@@ -20,7 +20,7 @@ if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
gs = int(os.environ.get("GATEWAY_GRACEFUL_SHUTDOWN", config.server.graceful_shutdown))
|
||||
print(f"[api-gateway] config={CONFIG_PATH} host={host} port={port} graceful_shutdown={gs}s")
|
||||
print(f"[xiaoyin-gateway] config={CONFIG_PATH} host={host} port={port} graceful_shutdown={gs}s")
|
||||
# 直接传入 app 对象(而非 import string),避免 uvicorn 二次导入 app.main 而再算一次配置。
|
||||
uvicorn.run(
|
||||
app,
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ run() { # run <说明> <命令...>
|
||||
fi
|
||||
}
|
||||
|
||||
echo "api-gateway CI 门禁($(date '+%F %T'))"
|
||||
echo "xiaoyin-gateway CI 门禁($(date '+%F %T'))"
|
||||
|
||||
# 1) 后端语法编译(覆盖整个 app 包 + run.py;不再维护手写文件清单)
|
||||
run "后端语法编译" "$PY" -m compileall -q app run.py
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
# **绝不写进本仓库任何文件**(仓库是要推到远端的)。
|
||||
set -euo pipefail
|
||||
|
||||
REPO_URL="https://git.wangjinding.com/Jidekin/api-gateway.git"
|
||||
REPO_URL="https://git.wangjinding.com/Jidekin/xiaoyin-gateway.git"
|
||||
USER="Jidekin"
|
||||
TOKEN_FILE="${HOME}/.gitea_token"
|
||||
|
||||
@@ -50,11 +50,11 @@ echo "== 推送 $BRANCH → Gitea($REPO_URL)=="
|
||||
echo " 本地 HEAD = $(git rev-parse --short HEAD)"
|
||||
|
||||
# 一次性内嵌凭据;输出里把凭据打码,避免它进日志/终端回滚缓冲
|
||||
git push "https://${USER}:${CRED}@git.wangjinding.com/Jidekin/api-gateway.git" "${BRANCH}:${BRANCH}" 2>&1 \
|
||||
git push "https://${USER}:${CRED}@git.wangjinding.com/Jidekin/xiaoyin-gateway.git" "${BRANCH}:${BRANCH}" 2>&1 \
|
||||
| sed "s/${CRED}/[CRED]/g"
|
||||
|
||||
# 推完核对:远端 HEAD 必须 = 本地 HEAD;并复查 .git/config 没被塞进明文凭据
|
||||
REMOTE_HEAD="$(git ls-remote "https://${USER}:${CRED}@git.wangjinding.com/Jidekin/api-gateway.git" "refs/heads/${BRANCH}" | awk '{print $1}')"
|
||||
REMOTE_HEAD="$(git ls-remote "https://${USER}:${CRED}@git.wangjinding.com/Jidekin/xiaoyin-gateway.git" "refs/heads/${BRANCH}" | awk '{print $1}')"
|
||||
LOCAL_HEAD="$(git rev-parse HEAD)"
|
||||
if [ "$REMOTE_HEAD" = "$LOCAL_HEAD" ]; then
|
||||
echo "✓ 远端 = 本地(${LOCAL_HEAD:0:7})"
|
||||
|
||||
+100
-3
@@ -46,7 +46,7 @@ import yaml
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
DEFAULT_CFG = ROOT / "data" / "gateway.yaml"
|
||||
|
||||
UA = "api-gateway-model-sync/1.0 (+ops; contact admin)"
|
||||
UA = "xiaoyin-gateway-model-sync/1.0 (+ops; contact admin)"
|
||||
OC_DOC_URL = "https://opencode.ai/v2/docs/console/go/"
|
||||
AGNES_PRICING_URL = "https://www.agnes-ai.cn/zh-Hans/docs/pricing.md"
|
||||
|
||||
@@ -114,6 +114,99 @@ OC_REGION_BLOCKED = {
|
||||
}
|
||||
OC_REGION_SKIPPED: list[str] = []
|
||||
|
||||
# ── 2026-11-19 文档二次改版:Endpoints 表不再逐条列 URL ──────────────
|
||||
# 官方把 `## Endpoints` 改成了「去看 console 页 / 用 models 接口」,HTML 里
|
||||
# 已经没有 `opencode.ai/` 的模型行 → 连续两天 exit=2「没解析出 Endpoints 表」。
|
||||
# 现在官方 models 接口直接给出机器可读的元数据(**无需鉴权**,实测不带 token 也 200):
|
||||
# GET https://opencode.ai/inference/go/v1/models (zen/go/v1/models 同源同内容)
|
||||
# 每条模型带:
|
||||
# id / name / type
|
||||
# api: {chat-completions|responses|messages|generate-content: {base_url, sdk}}
|
||||
# recommended_api: 官方推荐线
|
||||
# limit: {context, output}
|
||||
# cost.text.input.price / cost.text.output.price (都为 0 → 免费)
|
||||
# go.limited_regions: true → 对部分地区不开放(实测正是这三个 contributor / beam-free)
|
||||
# 口径:**以 models 接口为准**,HTML 表解析只作兜底;接口也挂了才报错。
|
||||
OC_MODELS_API = "https://opencode.ai/inference/go/v1/models"
|
||||
OC_MODELS_API_FALLBACK = "https://opencode.ai/zen/go/v1/models"
|
||||
|
||||
# models 接口的 api 键 → 网关协议线(网关只支持这三条线)
|
||||
OC_API_TO_PROTO = {
|
||||
"chat-completions": "chat/completions",
|
||||
"responses": "responses",
|
||||
"messages": "messages",
|
||||
}
|
||||
|
||||
|
||||
def _oc_protocol_from_api(model: dict) -> tuple[str | None, list[str]]:
|
||||
"""从 models 接口的 api / recommended_api 选网关协议线。
|
||||
|
||||
返回 (协议线, 文档声明的全部 api 键);认不出(例如只有 generate-content)返回 (None, keys)。
|
||||
"""
|
||||
keys = list((model.get("api") or {}).keys())
|
||||
supported = [OC_API_TO_PROTO[k] for k in keys if k in OC_API_TO_PROTO]
|
||||
if not supported:
|
||||
return None, keys
|
||||
rec = model.get("recommended_api")
|
||||
if rec in OC_API_TO_PROTO and OC_API_TO_PROTO[rec] in supported:
|
||||
return OC_API_TO_PROTO[rec], keys
|
||||
for proto in OC_PROTOCOLS: # 没有推荐或推荐不支持 → chat/completions 优先
|
||||
if proto in supported:
|
||||
return proto, keys
|
||||
return supported[0], keys
|
||||
|
||||
|
||||
def _oc_is_free(model: dict) -> bool:
|
||||
"""cost.text 的 input / output 单价都为 0 → 免费。"""
|
||||
price = (model.get("cost") or {}).get("text") or {}
|
||||
return ((price.get("input") or {}).get("price") == 0
|
||||
and (price.get("output") or {}).get("price") == 0)
|
||||
|
||||
|
||||
def fetch_opencode() -> dict[str, dict]:
|
||||
"""返回 {model_id: {name, protocol, free}}。
|
||||
|
||||
优先走官方 models 接口(稳定、机器可读);接口不可用时回退到旧的 HTML 表解析。
|
||||
"""
|
||||
payload = None
|
||||
err: Exception | None = None
|
||||
for url in (OC_MODELS_API, OC_MODELS_API_FALLBACK):
|
||||
try:
|
||||
payload = json.loads(_get(url, timeout=60))
|
||||
if isinstance(payload, dict) and payload.get("data"):
|
||||
break
|
||||
payload = None
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err = exc
|
||||
|
||||
if not payload:
|
||||
print(f"[warn] OpenCode models 接口不可用({err}),回退 HTML 解析", file=sys.stderr)
|
||||
return _fetch_opencode_html()
|
||||
|
||||
models: dict[str, dict] = {}
|
||||
skipped: list[str] = []
|
||||
region_skipped: list[str] = []
|
||||
for m in payload["data"]:
|
||||
mid = m.get("id")
|
||||
if not mid or (m.get("type") or "chat") != "chat":
|
||||
continue
|
||||
if (m.get("go") or {}).get("limited_regions") or mid in OC_REGION_BLOCKED:
|
||||
region_skipped.append(mid)
|
||||
continue
|
||||
proto, keys = _oc_protocol_from_api(m)
|
||||
if proto is None:
|
||||
skipped.append(f"{mid}({'/'.join(keys) or '无 api 字段'})")
|
||||
continue
|
||||
models[mid] = {"name": m.get("name") or mid,
|
||||
"protocol": proto,
|
||||
"free": _oc_is_free(m)}
|
||||
|
||||
if not models:
|
||||
raise RuntimeError("OpenCode models 接口返回 0 个可用模型(接口可能改版)")
|
||||
OC_SKIPPED[:] = sorted(skipped)
|
||||
OC_REGION_SKIPPED[:] = sorted(region_skipped)
|
||||
return models
|
||||
|
||||
|
||||
def _oc_protocol(url: str) -> str | None:
|
||||
"""文档 Endpoint → 网关协议线;认不出返回 None。"""
|
||||
@@ -124,8 +217,12 @@ def _oc_protocol(url: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def fetch_opencode() -> dict[str, dict]:
|
||||
"""返回 {model_id: {name, protocol, free}}。"""
|
||||
def _fetch_opencode_html() -> dict[str, dict]:
|
||||
"""【兜底】旧版 HTML 表解析。
|
||||
|
||||
2026-11-19 起官方 `## Endpoints` 表已不再逐条列 URL(内容搬到 console 页 +
|
||||
models 接口),这里正常不会走到;保留只为页面万一改回去时还能用。
|
||||
"""
|
||||
html = _get(OC_DOC_URL)
|
||||
models: dict[str, dict] = {}
|
||||
skipped: list[str] = []
|
||||
|
||||
@@ -43,7 +43,7 @@ DEFAULT_ENV = ROOT / "data" / ".env"
|
||||
|
||||
PROVIDER = "onemin"
|
||||
BASE_URL = "https://api.1min.ai/openai/v1"
|
||||
UA = "api-gateway-onemin-sync/1.0 (+ops; contact admin)"
|
||||
UA = "xiaoyin-gateway-onemin-sync/1.0 (+ops; contact admin)"
|
||||
|
||||
|
||||
# ── 工具 ────────────────────────────────────────────────────────────
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 124 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 115 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 113 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 110 KiB |
+535
@@ -0,0 +1,535 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>小银网关 — 一个网关,接住所有模型</title>
|
||||
<meta name="description" content="小银网关:把多家大模型供应商收进一个 OpenAI 兼容接口。三条协议线原样直传,熔断、限流、成本统计、管理台齐全。纯本地部署,MIT 开源。">
|
||||
<meta name="theme-color" content="#ffffff">
|
||||
<link rel="icon" href="/favicon.png">
|
||||
<style>
|
||||
:root{
|
||||
--blue:#3a7bfc; --blue-d:#0b66dd; --blue-l:#7ba7ff; --blue-bg:#eef4ff;
|
||||
--ink:#2f2f30; --ink-2:#4c4c4c; --ink-3:#8a8a8f;
|
||||
--gray:#f8f8f8; --gray-2:#f2f2f7; --line:#e8e8ee;
|
||||
--dark:#242424; --yellow:#ffb200;
|
||||
--max:1180px; --r:16px;
|
||||
--shadow:0 10px 40px -12px rgba(20,30,60,.18);
|
||||
--shadow-lg:0 24px 70px -25px rgba(20,30,60,.35);
|
||||
}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
html{scroll-behavior:smooth}
|
||||
body{
|
||||
font:16px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
|
||||
color:var(--ink);background:#fff;-webkit-font-smoothing:antialiased;overflow-x:hidden;
|
||||
}
|
||||
a{color:inherit;text-decoration:none}
|
||||
.wrap{max-width:var(--max);margin:0 auto;padding:0 24px}
|
||||
|
||||
/* ───────── 顶部导航 ───────── */
|
||||
header{
|
||||
position:sticky;top:0;z-index:50;background:rgba(255,255,255,.86);
|
||||
backdrop-filter:blur(14px);border-bottom:1px solid transparent;transition:.25s;
|
||||
}
|
||||
header.on{border-bottom-color:var(--line);box-shadow:0 2px 20px -12px rgba(0,0,0,.25)}
|
||||
.nav{display:flex;align-items:center;gap:34px;height:66px}
|
||||
.brand{display:flex;align-items:center;gap:10px;font-weight:800;font-size:17px;letter-spacing:.2px}
|
||||
.brand img{width:30px;height:30px;border-radius:8px}
|
||||
.nav-links{display:flex;gap:30px;margin-left:14px;font-size:15px;color:var(--ink-2)}
|
||||
.nav-links a{position:relative;padding:4px 0}
|
||||
.nav-links a:hover{color:var(--blue)}
|
||||
.nav-cta{margin-left:auto;display:flex;align-items:center;gap:14px}
|
||||
.nav-cta .ghost{font-size:15px;color:var(--ink-2)}
|
||||
.nav-cta .ghost:hover{color:var(--blue)}
|
||||
@media(max-width:820px){.nav-links{display:none}}
|
||||
|
||||
.btn{
|
||||
display:inline-flex;align-items:center;justify-content:center;gap:8px;
|
||||
border:0;cursor:pointer;font:inherit;font-weight:600;border-radius:999px;
|
||||
transition:transform .16s ease,box-shadow .16s ease,background .16s ease;
|
||||
}
|
||||
.btn:hover{transform:translateY(-2px)}
|
||||
.btn-blue{
|
||||
background:linear-gradient(96deg,var(--blue),var(--blue-d));color:#fff;
|
||||
padding:13px 30px;font-size:16px;box-shadow:0 10px 26px -10px rgba(58,123,252,.75);
|
||||
}
|
||||
.btn-sm{padding:9px 22px;font-size:14.5px}
|
||||
.btn-line{background:#fff;color:var(--ink);border:1px solid var(--line);padding:13px 26px;font-size:16px}
|
||||
.btn-line:hover{border-color:var(--blue-l);color:var(--blue)}
|
||||
.btn-dark{background:#fff;color:var(--dark);padding:13px 30px;font-size:16px}
|
||||
|
||||
/* ───────── HERO ───────── */
|
||||
.kv{position:relative;background:var(--gray);padding:76px 0 0;overflow:hidden}
|
||||
.kv::before,.kv::after{
|
||||
content:"";position:absolute;border-radius:50%;filter:blur(70px);opacity:.55;pointer-events:none;
|
||||
}
|
||||
.kv::before{width:520px;height:520px;left:-160px;top:-140px;background:radial-gradient(circle,#c9dcff,transparent 68%)}
|
||||
.kv::after{width:560px;height:560px;right:-180px;top:-60px;background:radial-gradient(circle,#dbe8ff,transparent 70%)}
|
||||
.kv-in{position:relative;text-align:center;z-index:1}
|
||||
.kv-tag{
|
||||
display:inline-flex;align-items:center;gap:9px;background:#fff;border:1px solid var(--line);
|
||||
color:var(--ink-2);font-size:13.5px;padding:7px 16px;border-radius:999px;margin-bottom:26px;
|
||||
box-shadow:0 4px 16px -8px rgba(20,30,60,.2);
|
||||
}
|
||||
.kv-tag b{color:var(--blue);font-weight:700}
|
||||
.dot{width:7px;height:7px;border-radius:50%;background:#22c55e;box-shadow:0 0 0 3px rgba(34,197,94,.18)}
|
||||
h1{
|
||||
font-size:clamp(38px,5.6vw,68px);line-height:1.1;font-weight:800;letter-spacing:-1.5px;color:var(--ink);
|
||||
}
|
||||
h1 em{
|
||||
font-style:normal;
|
||||
background:linear-gradient(96deg,var(--blue),var(--blue-d));
|
||||
-webkit-background-clip:text;background-clip:text;color:transparent;
|
||||
}
|
||||
.nw{white-space:nowrap}
|
||||
.kv-sub{
|
||||
margin:24px auto 0;max-width:720px;font-size:clamp(15px,1.7vw,19px);color:var(--ink-2);line-height:1.75;
|
||||
}
|
||||
.kv-meta{margin-top:20px;font-size:14.5px;color:var(--ink-3);display:flex;gap:0;justify-content:center;flex-wrap:wrap}
|
||||
.kv-meta i{font-style:normal;padding:0 14px;border-right:1px solid var(--line)}
|
||||
.kv-meta i:last-child{border:0}
|
||||
.kv-cta{margin-top:34px;display:flex;gap:14px;justify-content:center;flex-wrap:wrap}
|
||||
.kv-plat{margin-top:16px;font-size:13.5px;color:var(--ink-3)}
|
||||
|
||||
.badges{
|
||||
margin:44px auto 0;display:flex;justify-content:center;gap:14px;flex-wrap:wrap;
|
||||
max-width:900px;
|
||||
}
|
||||
.badge{
|
||||
display:flex;align-items:center;gap:8px;background:#fff;border:1px solid var(--line);
|
||||
border-radius:999px;padding:9px 18px;font-size:14px;color:var(--ink-2);font-weight:500;
|
||||
box-shadow:0 6px 20px -14px rgba(20,30,60,.4);
|
||||
}
|
||||
.badge b{color:var(--ink);font-weight:700}
|
||||
.badge .tick{color:var(--blue);font-weight:800}
|
||||
|
||||
/* 应用外观 */
|
||||
.shot{
|
||||
position:relative;max-width:960px;margin:56px auto 0;
|
||||
border-radius:18px 18px 0 0;background:#fff;border:1px solid var(--line);border-bottom:0;
|
||||
box-shadow:var(--shadow-lg);overflow:hidden;text-align:left;
|
||||
}
|
||||
.shot-bar{display:flex;align-items:center;gap:8px;padding:13px 16px;border-bottom:1px solid var(--line);background:#fbfbfd}
|
||||
.shot-bar i{width:11px;height:11px;border-radius:50%}
|
||||
.shot-bar i:nth-child(1){background:#ff5f57}.shot-bar i:nth-child(2){background:#febc2e}.shot-bar i:nth-child(3){background:#28c840}
|
||||
.shot-bar span{margin-left:12px;font-size:12.5px;color:var(--ink-3)}
|
||||
|
||||
/* 真实截图 */
|
||||
.shot img,.dark-shot img{display:block;width:100%;height:auto}
|
||||
.shot{border-radius:18px 18px 0 0}
|
||||
.gal{display:grid;grid-template-columns:1fr 1fr;gap:22px}
|
||||
@media(max-width:860px){.gal{grid-template-columns:1fr}}
|
||||
.gal figure{
|
||||
border:1px solid var(--line);border-radius:16px;overflow:hidden;background:#fff;
|
||||
box-shadow:var(--shadow);transition:.2s;
|
||||
}
|
||||
.gal figure:hover{box-shadow:var(--shadow-lg);transform:translateY(-3px)}
|
||||
.gal img{display:block;width:100%;height:auto}
|
||||
.gal figcaption{padding:16px 20px 18px;font-size:14.6px;color:var(--ink-2);line-height:1.65}
|
||||
.gal figcaption b{display:block;color:var(--ink);font-size:15.5px;margin-bottom:4px}
|
||||
|
||||
/* 平台信息 */
|
||||
.plat{margin:0 0 22px;background:#fff;border:1px solid var(--line);border-radius:16px;overflow:hidden}
|
||||
.plat-row{display:flex;gap:18px;align-items:flex-start;padding:15px 22px;border-bottom:1px solid var(--line);font-size:14.6px;color:var(--ink-2);line-height:1.7}
|
||||
.plat-row:last-child{border-bottom:0}
|
||||
.plat-row b{flex:none;width:82px;color:var(--ink);font-weight:700}
|
||||
.plat-chip{display:inline-block;background:var(--blue-bg);color:var(--blue-d);border-radius:999px;padding:3px 12px;font-size:13.5px;font-weight:600;margin:0 6px 6px 0}
|
||||
@media(max-width:640px){.plat-row{flex-direction:column;gap:6px}.plat-row b{width:auto}}
|
||||
|
||||
/* ───────── 通用区块 ───────── */
|
||||
section{padding:96px 0}
|
||||
.sec-white{background:#fff}
|
||||
.sec-gray{background:var(--gray)}
|
||||
.sec-head{text-align:center;max-width:680px;margin:0 auto 54px}
|
||||
.sec-head h2{font-size:clamp(26px,3.4vw,40px);font-weight:800;letter-spacing:-.8px;line-height:1.25}
|
||||
.sec-head h2 em{font-style:normal;color:var(--blue)}
|
||||
.sec-head p{margin-top:14px;color:var(--ink-2);font-size:16.5px}
|
||||
|
||||
/* 三大场景 */
|
||||
.scene{
|
||||
display:grid;grid-template-columns:1fr 1fr;gap:60px;align-items:center;
|
||||
padding:44px 0;
|
||||
}
|
||||
.scene+.scene{border-top:1px solid var(--line)}
|
||||
.scene.rev .scene-txt{order:2}
|
||||
.scene-ico{display:inline-flex;align-items:center;gap:10px;font-size:14px;font-weight:600;color:var(--blue);margin-bottom:16px}
|
||||
.scene-ico span{width:34px;height:34px;border-radius:11px;background:var(--blue-bg);display:grid;place-items:center;font-size:17px}
|
||||
.scene h3{font-size:clamp(24px,2.6vw,32px);font-weight:800;line-height:1.3;letter-spacing:-.5px}
|
||||
.scene ul{margin-top:24px;display:grid;gap:12px}
|
||||
.scene li{display:flex;gap:11px;color:var(--ink-2);font-size:15.5px;line-height:1.6}
|
||||
.scene li::before{content:"✓";color:var(--blue);font-weight:800;flex:none}
|
||||
.scene-more{margin-top:26px;display:inline-flex;align-items:center;gap:7px;color:var(--blue);font-weight:600;font-size:15px}
|
||||
.scene-visual{
|
||||
border-radius:20px;background:linear-gradient(160deg,#f4f8ff,#eaf1ff);border:1px solid var(--line);
|
||||
padding:26px;box-shadow:var(--shadow);min-height:230px;display:flex;flex-direction:column;gap:10px;justify-content:center;
|
||||
}
|
||||
.bar{height:11px;border-radius:6px;background:#fff;box-shadow:0 1px 2px rgba(20,30,60,.06)}
|
||||
.bar.w80{width:80%}.w60{width:60%}.w70{width:70%}.w45{width:45%}.w90{width:90%}
|
||||
.bar.blue{background:linear-gradient(90deg,var(--blue),var(--blue-l))}
|
||||
.mini-tabs{display:flex;gap:8px;margin-bottom:6px}
|
||||
.mini-tabs span{font-size:12px;padding:5px 12px;border-radius:999px;background:#fff;color:var(--ink-3);border:1px solid var(--line)}
|
||||
.mini-tabs span.on{background:var(--blue);color:#fff;border-color:var(--blue)}
|
||||
@media(max-width:880px){.scene{grid-template-columns:1fr;gap:30px}.scene.rev .scene-txt{order:0}}
|
||||
|
||||
/* 深色区块 */
|
||||
.dark{background:var(--dark);color:#fff;position:relative;overflow:hidden}
|
||||
.dark::before{content:"";position:absolute;width:700px;height:700px;right:-220px;top:-260px;
|
||||
background:radial-gradient(circle,rgba(58,123,252,.28),transparent 70%);pointer-events:none}
|
||||
.dark-in{position:relative;display:grid;grid-template-columns:1fr 1fr;gap:70px;align-items:center}
|
||||
.dark h2{font-size:clamp(28px,3.6vw,44px);font-weight:800;letter-spacing:-.6px;line-height:1.28}
|
||||
.dark .lead{margin-top:16px;color:rgba(255,255,255,.66);font-size:16px}
|
||||
.dark-list{margin-top:34px;display:grid;gap:2px}
|
||||
.dark-list div{
|
||||
display:flex;gap:16px;align-items:baseline;padding:15px 0;border-bottom:1px solid rgba(255,255,255,.1);
|
||||
}
|
||||
.dark-list div:last-child{border:0}
|
||||
.dark-list b{font-size:16.5px;font-weight:700;flex:none;min-width:96px}
|
||||
.dark-list span{color:rgba(255,255,255,.6);font-size:15px}
|
||||
.dark-shot{
|
||||
background:#1b1b1b;border:1px solid rgba(255,255,255,.12);border-radius:18px;overflow:hidden;
|
||||
box-shadow:0 30px 80px -30px #000;
|
||||
}
|
||||
.dark-shot .shot-bar{background:#161616;border-bottom-color:rgba(255,255,255,.1)}
|
||||
.dark-shot .shot-bar span{color:rgba(255,255,255,.4)}
|
||||
@media(max-width:880px){.dark-in{grid-template-columns:1fr;gap:36px}}
|
||||
|
||||
/* 功能网格 */
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(270px,1fr));gap:18px}
|
||||
.card{
|
||||
background:#fff;border:1px solid var(--line);border-radius:var(--r);padding:26px;
|
||||
transition:.2s;position:relative;
|
||||
}
|
||||
.card:hover{border-color:var(--blue-l);box-shadow:var(--shadow);transform:translateY(-3px)}
|
||||
.card h3{font-size:17px;font-weight:700;margin-bottom:9px;display:flex;align-items:center;gap:10px}
|
||||
.card .ico{width:32px;height:32px;border-radius:10px;background:var(--blue-bg);color:var(--blue);display:grid;place-items:center;font-size:15px;flex:none}
|
||||
.card p{color:var(--ink-2);font-size:14.8px;line-height:1.7}
|
||||
code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9em;background:var(--gray-2);padding:1.5px 6px;border-radius:5px;color:var(--blue-d)}
|
||||
|
||||
/* 快捷键 */
|
||||
.keys{display:grid;grid-template-columns:1fr 1fr;gap:0 40px}
|
||||
@media(max-width:760px){.keys{grid-template-columns:1fr}}
|
||||
.key-row{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:12px 0;border-bottom:1px solid var(--line);font-size:15px}
|
||||
.key-row>span:first-child{color:var(--ink-2)}
|
||||
kbd{
|
||||
font:12.5px/1 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#fff;
|
||||
border:1px solid var(--line);border-bottom-width:2px;border-radius:6px;padding:4px 7px;color:var(--ink);
|
||||
display:inline-block;margin-left:4px;
|
||||
}
|
||||
|
||||
/* 下载 */
|
||||
.dl-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:18px;margin-top:8px}
|
||||
.dl-card{
|
||||
background:#fff;border:1px solid var(--line);border-radius:18px;padding:30px;
|
||||
display:flex;flex-direction:column;transition:.2s;
|
||||
}
|
||||
.dl-card.primary{border:2px solid var(--blue);box-shadow:0 20px 50px -30px rgba(58,123,252,.8);position:relative}
|
||||
.dl-card.primary::after{
|
||||
content:"推荐";position:absolute;top:-13px;left:30px;background:linear-gradient(96deg,var(--blue),var(--blue-d));
|
||||
color:#fff;font-size:12px;font-weight:700;padding:4px 13px;border-radius:999px;
|
||||
}
|
||||
.dl-card h3{font-size:19px;font-weight:800;margin-bottom:8px}
|
||||
.dl-size{font-size:14px;color:var(--ink-3);margin-bottom:14px}
|
||||
.dl-card p{color:var(--ink-2);font-size:14.6px;line-height:1.7;flex:1;margin-bottom:22px}
|
||||
.note-ic{flex:none;width:20px;height:20px;border-radius:50%;background:var(--blue);color:#fff;
|
||||
font-size:12px;font-weight:800;font-style:italic;display:grid;place-items:center;margin-top:2px}
|
||||
.note{
|
||||
margin-top:26px;display:flex;gap:12px;align-items:flex-start;background:var(--blue-bg);
|
||||
border-radius:14px;padding:16px 20px;font-size:14.6px;color:var(--blue-d)
|
||||
}
|
||||
|
||||
footer{background:#fff;border-top:1px solid var(--line);padding:46px 0 56px;color:var(--ink-3);font-size:14px}
|
||||
.foot{display:flex;gap:26px;flex-wrap:wrap;align-items:center}
|
||||
.foot a:hover{color:var(--blue)}
|
||||
.foot .sp{margin-left:auto}
|
||||
.foot .sep{color:var(--line)}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header id="hd">
|
||||
<div class="wrap nav">
|
||||
<a class="brand" href="/"><img src="/favicon.png" alt="">小银网关</a>
|
||||
<nav class="nav-links">
|
||||
<a href="#scene">产品</a>
|
||||
<a href="#features">功能</a>
|
||||
<a href="#api">接口</a>
|
||||
<a href="#console">管理台</a>
|
||||
<a href="#about">关于</a>
|
||||
</nav>
|
||||
<div class="nav-cta">
|
||||
<a class="ghost" href="https://git.wangjinding.com/Jidekin/xiaoyin-gateway" target="_blank" rel="noopener">源码</a>
|
||||
<a class="btn btn-blue btn-sm" href="#deploy">快速开始</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- ══════════ HERO ══════════ -->
|
||||
<div class="kv">
|
||||
<div class="wrap kv-in">
|
||||
<div class="kv-tag"><i class="dot"></i><span>v<span data-ver>2.9.16</span> · <b>MIT 开源 · 纯本地部署</b></span></div>
|
||||
<h1>一个网关,<br><em>接住所有模型</em></h1>
|
||||
<p class="kv-sub">
|
||||
把 <span class="nw">4 家供应商、81 个模型</span>收进同一个 OpenAI 兼容接口。<br>
|
||||
三条协议线原样直传,网关只做路由、鉴权和限流,<b>不改你的字段</b>。
|
||||
</p>
|
||||
<div class="kv-meta">
|
||||
<i>纯后端 FastAPI</i><i>配置驱动 · 热加载</i><i>自带 Web 管理台</i>
|
||||
</div>
|
||||
<div class="kv-cta">
|
||||
<a class="btn btn-blue" href="#deploy">↓ 部署到自己机器</a>
|
||||
<a class="btn btn-line" href="#scene">看看怎么用</a>
|
||||
</div>
|
||||
<p class="kv-plat">Docker / 源码部署 · Python 3.10+ · 不依赖任何云服务</p>
|
||||
|
||||
<div class="badges">
|
||||
<div class="badge"><span class="tick">✓</span>三线直传</div>
|
||||
<div class="badge"><span class="tick">✓</span>统一密钥</div>
|
||||
<div class="badge"><span class="tick">✓</span>熔断 · 限流</div>
|
||||
<div class="badge"><span class="tick">✓</span>成本统计</div>
|
||||
<div class="badge"><span class="tick">✓</span>MIT 开源</div>
|
||||
</div>
|
||||
|
||||
<div class="shot">
|
||||
<div class="shot-bar"><i></i><i></i><i></i><span>终端 — 换一个 model,就换一家供应商</span></div>
|
||||
<pre class="term"><code><span class="c-com"># 同一个接口,model 决定走向哪一家</span>
|
||||
<span class="c-p">$</span> curl http://127.0.0.1:8808/v1/chat/completions \
|
||||
-H <span class="c-s">"Authorization: Bearer sk-你的key"</span> \
|
||||
-d <span class="c-s">'{"model": "agnes-3.0-flash",
|
||||
"messages": [{"role":"user","content":"你好"}]}'</span>
|
||||
|
||||
<span class="c-ok">200 OK</span> <span class="c-dim">{</span>"choices":[{"message":{"content":"你好!有什么可以帮你?"}}]<span class="c-dim">}</span></code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ══════════ 三大场景 ══════════ -->
|
||||
<section id="scene" class="sec-white">
|
||||
<div class="wrap">
|
||||
<div class="sec-head">
|
||||
<h2>一个网关,<em>解决三件事</em></h2>
|
||||
<p>
|
||||
以前每接一家模型就要改一次代码、换一套鉴权、记一套错误码。
|
||||
现在它们都在你身后,接口只有一个。
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid">
|
||||
<div class="card">
|
||||
<h3><span class="ico">⇄</span>一个 Key,四家供应商</h3>
|
||||
<p>请求里的 <code>model</code> 决定走向哪家:<b>1min.ai</b> 43 个模型、<b>OpenCode Go</b> 27 个、<b>Agnes AI</b> 10 个、<b>Dots(小红书)</b> 1 个。换模型不用换 SDK、不用换域名。</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><span class="ico">⑃</span>三条协议线,原样直传</h3>
|
||||
<p>OpenAI Chat、Anthropic Messages、Responses 三条线各按自家协议转发,<b>网关不翻译字段</b>。选错线直接 400,并告诉这个模型支持哪几条。</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><span class="ico">◎</span>管得住:熔断、限流、成本</h3>
|
||||
<p>同一模型自动重试 + 供应商级熔断;两级限流(全局 / 供应商);每次调用都有 token、耗时、成本估算,落在日志和 <code>/metrics</code> 里。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══════════ 深色数据块 ══════════ -->
|
||||
<section class="dark">
|
||||
<div class="wrap dark-in">
|
||||
<div class="sec-head">
|
||||
<h2>一套后端,<br>把复杂度吃掉</h2>
|
||||
</div>
|
||||
<div class="dark-list">
|
||||
<div><b>4</b><span>家供应商<br>共 81 个模型</span></div>
|
||||
<div><b>3</b><span>条协议线<br>原样直传</span></div>
|
||||
<div><b>2万+</b><span>行 Python<br>单进程 FastAPI</span></div>
|
||||
<div><b>0</b><span>依赖云服务<br>数据都在自己机器上</span></div>
|
||||
</div>
|
||||
<p class="dark-shot-tip">改配置不用重启:<code>POST /admin/reload</code> 热加载</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══════════ 功能九宫格 ══════════ -->
|
||||
<section id="features" class="sec-white">
|
||||
<div class="wrap">
|
||||
<div class="sec-head">
|
||||
<h2>该有的都有,<em>不该有的一个没有</em></h2>
|
||||
<p>没有账号体系绑死你、没有额度套餐、没有强制上报。装上就是你的。</p>
|
||||
</div>
|
||||
<div class="grid">
|
||||
<div class="card"><h3><span class="ico">⇄</span>多供应商分发</h3><p>model 名决定供应商;同名模型可配多条路由,按顺序故障转移。配置写在 YAML 里,改完热加载。</p></div>
|
||||
<div class="card"><h3><span class="ico">⑃</span>三线直传</h3><p>OpenAI Chat / Anthropic Messages / OpenAI Responses 三条线各走自家协议,字段不加工,客户端 SDK 直接可用。</p></div>
|
||||
<div class="card"><h3><span class="ico">⛨</span>熔断 · 重试</h3><p>同模型失败自动重试;某家供应商连续失败就熔断一段时间,请求自动绕开,chat 与媒体各自独立计数。</p></div>
|
||||
<div class="card"><h3><span class="ico">◔</span>两级限流</h3><p>全局 QPS + 每供应商 QPS 双层保护,超了返回 429 并带 Retry-After,不会把上游打爆。</p></div>
|
||||
<div class="card"><h3><span class="ico">▣</span>图像与视频</h3><p><code>/v1/images/generations</code> 直出图片;<code>/v1/videos</code> 支持异步轮询、等待模式和 Webhook 回调。</p></div>
|
||||
<div class="card"><h3><span class="ico">▲</span>指标与成本</h3><p><code>/metrics</code> 出 JSON,<code>/metrics/prometheus</code> 直接给 Prometheus 抓;按定价表估算每笔调用花多少钱。</p></div>
|
||||
<div class="card"><h3><span class="ico">↻</span>热加载</h3><p>改完 <code>gateway.yaml</code> 调一次 reload,新配置立即生效,不中断在途请求。</p></div>
|
||||
<div class="card"><h3><span class="ico">☺</span>账号 + 每账号 Key</h3><p>管理台账号密码登录,每个账号自己建 API Key,互不干扰;停用只影响该账号。</p></div>
|
||||
<div class="card"><h3><span class="ico">▤</span>自带管理台</h3><p>Vue 写的 Web 控制台:看日志、调配置、试模型、查用量,不用登服务器改文件。</p></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══════════ 接口一览 ══════════ -->
|
||||
<section id="api" class="sec-gray">
|
||||
<div class="wrap">
|
||||
<div class="sec-head">
|
||||
<h2>接口就那么几个</h2>
|
||||
<p>都是 OpenAI 兼容路径,换 base_url 就能接上你现有的客户端。</p>
|
||||
</div>
|
||||
<div class="api-list"><div class="api-row"><span class="api-m post">POST</span><b>/v1/chat/completions</b><i>对话(OpenAI 线)</i></div><div class="api-row"><span class="api-m post">POST</span><b>/v1/messages</b><i>对话(Anthropic 线,也认 x-api-key)</i></div><div class="api-row"><span class="api-m post">POST</span><b>/v1/responses</b><i>对话(Responses 线)</i></div><div class="api-row"><span class="api-m post">POST</span><b>/v1/chat/completions/batch</b><i>并发多 prompt 一次发出</i></div><div class="api-row"><span class="api-m post">POST</span><b>/v1/images/generations</b><i>出图</i></div><div class="api-row"><span class="api-m post">POST</span><b>/v1/videos</b><i>出视频(异步 / 等待 / Webhook)</i></div><div class="api-row"><span class="api-m get">GET</span><b>/models</b><i>这个网关现在有哪些模型</i></div><div class="api-row"><span class="api-m get">GET</span><b>/metrics</b><i>用量、耗时、成本(JSON / Prometheus)</i></div><div class="api-row"><span class="api-m get">GET</span><b>/health</b><i>运维看板</i></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
<!-- ══════════ 真实界面 ══════════ -->
|
||||
<section id="console" class="sec-white">
|
||||
<div class="wrap">
|
||||
<div class="sec-head">
|
||||
<h2>这些<em>都是真实界面</em></h2>
|
||||
<p>不是效果图。下面每一张都是管理台正在跑的样子,数据来自我自己这台机器。</p>
|
||||
</div>
|
||||
<div class="gal2">
|
||||
<figure class="shot2">
|
||||
<div class="shot-bar"><i></i><i></i><i></i><span>仪表盘 — 用量、成功率、延迟、供应商健康</span></div>
|
||||
<img src="/img/console-dashboard.jpg" alt="小银网关管理台仪表盘:请求总数、成功率、平均延迟、模型延迟 P50/P95、供应商状态与调用份额">
|
||||
</figure>
|
||||
<figure class="shot2">
|
||||
<div class="shot-bar"><i></i><i></i><i></i><span>模型与供应商 — 4 家 / 81 个模型</span></div>
|
||||
<img src="/img/console-models.jpg" alt="小银网关管理台:模型与供应商列表,显示每家供应商的模型数与 Key 配置状态">
|
||||
</figure>
|
||||
<figure class="shot2">
|
||||
<div class="shot-bar"><i></i><i></i><i></i><span>指标与成本 — Token 用量、缓存命中、调用分布</span></div>
|
||||
<img src="/img/console-metrics.jpg" alt="小银网关管理台指标页:Token 用量、缓存命中率、各模型与供应商调用分布">
|
||||
</figure>
|
||||
<figure class="shot2">
|
||||
<div class="shot-bar"><i></i><i></i><i></i><span>对话 — 选模型即选供应商,带 token 与耗时</span></div>
|
||||
<img src="/img/console-chat.jpg" alt="小银网关管理台对话页:选择 agnes-3.0-flash 模型提问,显示 token 用量、耗时与成本">
|
||||
</figure>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══════════ 部署 ══════════ -->
|
||||
<section id="deploy" class="sec-white">
|
||||
<div class="wrap">
|
||||
<div class="sec-head">
|
||||
<h2>部署,<em>三条命令的事</em></h2>
|
||||
<p>一台小机器就够:单进程 FastAPI,内存几百 MB,没有数据库、没有中间件。</p>
|
||||
</div>
|
||||
<div class="grid" style="grid-template-columns:1fr">
|
||||
<div class="card">
|
||||
<h3><span class="ico">⌨</span>从源码跑起来</h3>
|
||||
<pre class="code"><code>git clone https://git.wangjinding.com/Jidekin/xiaoyin-gateway.git
|
||||
cd xiaoyin-gateway
|
||||
pip install -r requirements.txt
|
||||
|
||||
cp .env.example .env <span class="c-com"># 填各家供应商的 token</span>
|
||||
vim data/gateway.yaml <span class="c-com"># 配供应商、模型、限流</span>
|
||||
|
||||
python run.py <span class="c-com"># 默认 127.0.0.1:8808</span></code></pre>
|
||||
<p>起来之后打开 <code>http://127.0.0.1:8808/web</code> 就是管理台。</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3><span class="ico">⌗</span>配一个供应商长这样</h3>
|
||||
<pre class="code"><code><span class="c-com"># data/gateway.yaml</span>
|
||||
providers:
|
||||
agnes:
|
||||
base_url: https://api.agnes-ai.cn/v1
|
||||
api_key: <span class="c-dim">${AGNES_API_KEY}</span>
|
||||
models:
|
||||
- name: agnes-3.0-flash
|
||||
protocols: [chat, messages]
|
||||
pricing: { input: 0.0, output: 0.0 }</code></pre>
|
||||
<p>配好 reload 一下,<code>GET /models</code> 就能看到它。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══════════ 关于 ══════════ -->
|
||||
<section id="about" class="sec-gray">
|
||||
<div class="wrap">
|
||||
<div class="sec-head">
|
||||
<h2>关于<em>小银网关</em></h2>
|
||||
<p>
|
||||
一家人用的模型入口。不对外卖额度、不做 SaaS —— 代码在你自己机器上跑,
|
||||
密钥在你自己手里,日志在你自己盘上。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="plat">
|
||||
<div class="plat-row">
|
||||
<b>技术栈</b>
|
||||
<span>
|
||||
<span class="plat-chip">FastAPI</span>
|
||||
<span class="plat-chip">Python 3.10+</span>
|
||||
<span class="plat-chip">配置驱动 YAML</span>
|
||||
<span class="plat-chip">Vue 管理台</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="plat-row">
|
||||
<b>供应商</b>
|
||||
<span>1min.ai(43 个模型)· OpenCode Go(27)· Agnes AI(10)· Dots AI 小红书(1,512K 上下文)</span>
|
||||
</div>
|
||||
<div class="plat-row">
|
||||
<b>部署方式</b>
|
||||
<span>源码 <code>python run.py</code> 或 Docker;单进程,无数据库、无 Redis、无消息队列。</span>
|
||||
</div>
|
||||
<div class="plat-row">
|
||||
<b>许可</b>
|
||||
<span>MIT License,可自由使用、修改、分发。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<div class="card"><h3><span class="ico">⛨</span>隐私</h3><p>数据不出你的机器。网关只在上游调用时刻才连外网,其余时间全是本地。</p></div>
|
||||
<div class="card"><h3><span class="ico">§</span>许可</h3><p>MIT。改完自己用、给朋友用、拿去二次开发都行。</p></div>
|
||||
<div class="card"><h3><span class="ico">↻</span>自己改</h3><p>2 万行 Python,一个 <code>app/main.py</code> 就是全部后端;前端 Vue 单独构建,产物直接塞进 <code>frontend/dist</code>。</p></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer class="foot">
|
||||
<div class="wrap">
|
||||
<span>© 2026 小银网关 · <span data-ver>2.9.16</span></span>
|
||||
<span class="sep">·</span>
|
||||
<a href="https://git.wangjinding.com/Jidekin/xiaoyin-gateway" target="_blank" rel="noopener">Gitea</a>
|
||||
<span class="sep">·</span>
|
||||
<a href="https://github.com/wangjinding/xiaoyin-gateway" target="_blank" rel="noopener">GitHub</a>
|
||||
<span class="sep">·</span>
|
||||
<span>MIT License</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<style>
|
||||
.term{margin:0;padding:20px 22px;background:#1c1f26;color:#d7dbe4;border-radius:0 0 14px 14px;
|
||||
font:13.5px/1.85 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow-x:auto}
|
||||
.term code{background:none;padding:0;color:inherit}
|
||||
.c-com{color:#6f7a8d}.c-p{color:#64d2a0}.c-s{color:#e5c07b}
|
||||
.c-ok{color:#64d2a0;font-weight:700}.c-dim{color:#8b95a8}
|
||||
.code{margin:0 0 12px;padding:16px 18px;background:#f6f8fb;border:1px solid var(--line);
|
||||
border-radius:12px;font:13.5px/1.8 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
|
||||
color:#37404f;overflow-x:auto}
|
||||
.code code{background:none;padding:0;color:inherit}
|
||||
|
||||
.gal2{display:grid;grid-template-columns:1fr 1fr;gap:22px}
|
||||
.shot2{margin:0;background:#fff;border:1px solid var(--line);border-radius:14px;overflow:hidden;
|
||||
box-shadow:0 10px 40px -18px rgba(20,30,60,.22);transition:transform .18s ease, box-shadow .18s ease}
|
||||
.shot2:hover{transform:translateY(-3px);box-shadow:0 18px 50px -20px rgba(20,30,60,.3)}
|
||||
.shot2 img{display:block;width:100%;height:auto}
|
||||
@media(max-width:860px){.gal2{grid-template-columns:1fr}}
|
||||
.api-list{background:#fff;border:1px solid var(--line);border-radius:16px;overflow:hidden}
|
||||
.api-row{display:flex;align-items:center;gap:16px;padding:13px 22px;border-bottom:1px solid var(--line);font-size:14.5px}
|
||||
.api-row:last-child{border-bottom:0}
|
||||
.api-m{flex:none;width:52px;font:700 11px/1 ui-monospace,monospace;color:#fff;border-radius:6px;
|
||||
padding:5px 0;text-align:center;letter-spacing:.5px}
|
||||
.api-m.post{background:#2f6feb}.api-m.get{background:#0f9d6b}
|
||||
.api-row b{flex:none;min-width:300px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:14px;color:var(--ink)}
|
||||
.api-row i{color:var(--ink-3);font-style:normal}
|
||||
@media(max-width:720px){.api-row{flex-wrap:wrap;gap:8px}.api-row b{min-width:0;flex:1 1 100%}}
|
||||
.dark-shot-tip{margin-top:22px;color:rgba(255,255,255,.55);font-size:14px}
|
||||
.dark-shot-tip code{background:rgba(255,255,255,.1);color:#9fc0ff}
|
||||
@media(max-width:720px){
|
||||
.key-row{flex-wrap:wrap;gap:8px}
|
||||
.key-row b{min-width:0;flex:1 1 100%}
|
||||
}
|
||||
</style>
|
||||
</body>
|
||||
</html>
|
||||
+1
-1
@@ -30,7 +30,7 @@ def _explain(r: httpx.Response) -> str:
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="API Gateway 冒烟测试")
|
||||
parser = argparse.ArgumentParser(description="小银网关 冒烟测试")
|
||||
parser.add_argument("--url", default="http://localhost:8808", help="网关地址")
|
||||
parser.add_argument("--api-key", default="", help="可选 Bearer key(网关开了鉴权时用)")
|
||||
parser.add_argument("--model", default="agnes-3.0-flash", help="测试用文本模型")
|
||||
|
||||
+14
-1
@@ -61,6 +61,16 @@ if _TC is not None:
|
||||
_AUTOBEARER = ""
|
||||
try:
|
||||
import app.main as _m
|
||||
# 2026-11-19:测试会**故意**制造大量鉴权失败,而 2026-11-06 起的「鉴权失败自动封禁」
|
||||
# 会在同一进程内把 testclient 这个 IP 拉黑 60 分钟 → 后半场测试全变 429。
|
||||
# 这是测试隔离问题,不是被测行为:测试里关掉封禁(限流仍生效),生产逻辑不动。
|
||||
try:
|
||||
_m._cfg().server.auth_fail_ban_seconds = 0
|
||||
_m._BANNED.clear()
|
||||
_m._BANNED_FOREVER.clear()
|
||||
_m._AUTH_FAILS.clear()
|
||||
except Exception:
|
||||
pass
|
||||
_c = _TC(_m.app)
|
||||
_r = _c.post("/auth/login", json={"username": "admin", "password": "admin"})
|
||||
if _r.status_code == 200:
|
||||
@@ -1716,7 +1726,10 @@ def test_models_payload_marks_free_models():
|
||||
# 2026-10-12:样本从 space-bunny-free 换成 longcat-2.5-preview-free —— 前者已于
|
||||
# 2026-10-07 被官方改名成 space-bunny 并转收费(价格表 $0.15/$0.60),
|
||||
# 每日同步据此去掉了它的 free 标记(现网免费位=longcat-2.5-preview-free / step-5-preview-free)。
|
||||
assert "longcat-2.5-preview-free" in free_ids, f"免费模型没标出来:{free_ids}"
|
||||
# 2026-11-19:官方把 longcat-2.5-preview-free 改名为 longcat-2.5-free(每日同步已跟进),
|
||||
# 样本改成「现网确实免费的那几个之一」,避免上游改名再把测试打红。
|
||||
assert any(x in free_ids for x in ("longcat-2.5-free", "hy4-flash-free",
|
||||
"iceman-contributor-free")), f"免费模型没标出来:{free_ids}"
|
||||
# 反向:付费模型必须是 free=false(不能因为字段缺失而误标)
|
||||
paid = next(x for x in data if x["id"] == "deepseek-v4.1-flash")
|
||||
assert paid["free"] is False, paid
|
||||
|
||||
Reference in new issue
Block a user