feat: attach hif leim header upstream

This commit is contained in:
highkay committed 2026-05-25 12:12:43 +08:00
1 parent 2b4e2afe9e
commit e0bc9949b8
10 files changed
+557 -20

No files matched your search

+57 -14
View File
@@ -2,21 +2,22 @@
本文记录需要定期跟踪的 DS2API 上游和活跃 fork,用于复查可吸收的实现、规避重复调研,并给出当前处理建议。
最近复查时间:2026-05-18。
最近复查时间:2026-05-25。
## 本地引用
所有监控分支统一拉到 `refs/remotes/review/*`,避免污染正式 remote。
```bash
git fetch https://github.com/CJackHwang/ds2api refs/heads/main:refs/remotes/review/cjack-main
git fetch https://github.com/qingdeng888/ds2api refs/heads/main:refs/remotes/review/qingdeng888-main
git fetch https://github.com/fuwei99/ds2api refs/heads/main:refs/remotes/review/fuwei99-main
git fetch https://github.com/ricardosantis/ds2api refs/heads/main:refs/remotes/review/ricardosantis-main
git fetch https://github.com/tempppw01/ds2api refs/heads/main:refs/remotes/review/tempppw01-main
git fetch https://github.com/TonyWu2333/ds2api refs/heads/main:refs/remotes/review/TonyWu2333-main
git fetch https://github.com/1cyberlangke1/dsp refs/heads/main:refs/remotes/review/1cyberlangke1-dsp-main
git fetch https://github.com/emptysuns/ds2api refs/heads/main:refs/remotes/review/emptysuns-main
git fetch https://github.com/CJackHwang/ds2api +refs/heads/main:refs/remotes/review/cjack-main
git fetch https://github.com/qingdeng888/ds2api +refs/heads/main:refs/remotes/review/qingdeng888-main
git fetch https://github.com/fuwei99/ds2api +refs/heads/main:refs/remotes/review/fuwei99-main
git fetch https://github.com/ricardosantis/ds2api +refs/heads/main:refs/remotes/review/ricardosantis-main
git fetch https://github.com/tempppw01/ds2api +refs/heads/main:refs/remotes/review/tempppw01-main
git fetch https://github.com/TonyWu2333/ds2api +refs/heads/main:refs/remotes/review/TonyWu2333-main
git fetch https://github.com/1cyberlangke1/dsp +refs/heads/main:refs/remotes/review/1cyberlangke1-dsp-main
git fetch https://github.com/emptysuns/ds2api +refs/heads/main:refs/remotes/review/emptysuns-main
git fetch https://github.com/hefengfan0615/ds2api +refs/heads/main:refs/remotes/review/hefengfan0615-main
```
对比新增提交:
@@ -32,22 +33,64 @@ git diff --stat refs/remotes/review/cjack-main..refs/remotes/review/<name>
| --- | --- | --- | --- | --- |
| `CJackHwang/ds2api:main` | `review/cjack-main` | `8316cf8` | 官方基线 | 作为 fork diff 的比较基准。 |
| `qingdeng888/ds2api:main` | `review/qingdeng888-main` | `42bc1ed` | 账号健康权重、冷却、P2C 选择、Docker config 挂载修正 | 核心账号健康能力已吸收;后续只看是否有新的调度/冷却实测修正。 |
| `fuwei99/ds2api:main` | `review/fuwei99-main` | `08b4aa5` | muted 账号检测、账号 active/muted 字段、GHCR workflow、容器配置 bootstrap、新模型映射 | muted 检测与 GHCR 核心已吸收;模型映射和 bootstrap 需按本仓库配置语义逐项复核,不整分支合并。 |
| `fuwei99/ds2api:main` | `review/fuwei99-main` | `5ee2a1f` | muted 账号检测、账号 active/muted 字段、GHCR workflow、容器配置 bootstrap、新模型映射;2026-05-25 新增 `x-hif-leim` 查询、中文 prompt marker、current-input-file 包装/改名、Docker buildx workflow | `x-hif-leim` 有单点研究价值,但只能按小块验证后引入;中文 prompt marker、`invaild-file*` 包装/改名和测试批量改写风险高,不建议合入。 |
| `ricardosantis/ds2api:main` | `review/ricardosantis-main` | `dc1a76c` | Heroku/Procfile/runtime/env 示例、本地部署文档 | 主要是部署文档和平台样板,价值较低;仅在需要 Heroku 文档时参考。 |
| `tempppw01/ds2api:main` | `review/tempppw01-main` | `9aaa8b4` | 默认禁用上游上传、移除默认 prompt 注入、latest user text prompts、DockerHub workflow | 上游上传禁用已作为可选 runtime 开关吸收;不采用“默认关闭”和 prompt 形状大改,除非有真实回归证据。 |
| `TonyWu2333/ds2api:main` | `review/TonyWu2333-main` | `6dbdcec` | 128k prompt 限制、模型别名微调、prompt role marker 中文化 | 128k 限制已吸收;`6dbdcec` 仅把 DeepSeek marker 换成中文文本,不建议合入,除非动态验证证明更稳。 |
| `1cyberlangke1/dsp:main` | `review/1cyberlangke1-dsp-main` | `10f0ca3` | DeepSeek 指纹、device id、x-rangers-id、TLS/transport 调整;同时大规模删除 Vercel/文档/JS 桥 | 只监控上游指纹相关小块;已吸收兼容子集。该 fork 范围偏离 DS2API,不可整合。 |
| `1cyberlangke1/dsp:main` | `review/1cyberlangke1-dsp-main` | `0759d7f` | DeepSeek 指纹、device id、x-rangers-id、TLS/transport 调整;同时大规模删除 Vercel/文档/JS 桥 | 只监控上游指纹相关小块;已吸收兼容子集。该 fork 范围偏离 DS2API,不可整合。2026-05-25 复查时 GitHub fetch 返回 repository not found,当前 ref 只能视为本地旧快照。 |
| `emptysuns/ds2api:main` | `review/emptysuns-main` | `2f87937` | prompt 默认策略、response replacements、tool interception 统一、SSE/stream 边界清洗、late thinking 抑制、WebUI 设置面板 | 有研究价值但改动面很大。建议作为单独专题审查:先用 raw SSE/协议测试证明具体问题,再按 `responserewrite`、`toolpolicy`、`sse normalizer` 等小块拆分引入。 |
| `hefengfan0615/ds2api:main` | `review/hefengfan0615-main` | `37f6206` | 随机 device_id、随机 DeepSeek header/TLS 指纹;后续继续发散为 Qwen2API 改造、Qwen SSE 解析、忽略 PoW、账号相关 `/v1/models` 和 WebUI 模型加载调整 | 不整合。新增 Qwen2API 方向已偏离 DS2API 的 DeepSeek upstream owner,并替换/绕过 DeepSeek SSE、PoW、登录和模型契约;账号相关模型列表 UI 可以作为独立需求重新设计,但不能从该分支直接搬。详见 [hefengfan0615 上游评估报告](./upstream-hefengfan0615-evaluation.md)。 |
## 当前高价值候选
1. `emptysuns` 的 stream/SSE 边界修复:包括 UTF-8 replacement 边界、Claude SSE charset、late thinking 抑制、response replacement 在 SSE 边界归一。这些直接影响流式输出质量,但必须用样本回放和三协议测试验证。
2. `emptysuns` 的 tool interception policy:有助于收敛 OpenAI/Claude/Gemini 工具拦截策略,不过会触碰现有 canonical XML tool-call 语义,不能整块搬。
3. `fuwei99` 的容器配置 bootstrap 和模型映射:可能改善容器首次启动体验和模型覆盖,但要先和本仓库 `config`/`model_aliases` 语义对齐。
1. `fuwei99` 的 `x-hif-leim` 查询:2026-05-25 多次无凭证探针确认 `https://hif-leim.deepseek.com/query` 稳定返回 `code=0` 和 `biz_data.value`。已按 best-effort 方式重新实现到 Go completion/continue 和 Vercel Node streaming:成功则带 `x-hif-leim`,失败则软降级,且有短超时和失败退避。仍缺少真实账号 A/B 数据,后续应验证加 header 前后的 403/429/空回复分布。
2. `emptysuns` 的 stream/SSE 边界修复:包括 UTF-8 replacement 边界、Claude SSE charset、late thinking 抑制、response replacement 在 SSE 边界归一。这些直接影响流式输出质量,但必须用样本回放和三协议测试验证。
3. `emptysuns` 的 tool interception policy:有助于收敛 OpenAI/Claude/Gemini 工具拦截策略,不过会触碰现有 canonical XML tool-call 语义,不能整块搬。
4. `hefengfan0615` 早期请求外形/指纹方向:可能对 DeepSeek 上游风控有帮助,但必须先用真实登录、建会话、PoW、completion 四段探针验证成功率和错误分布;不要直接引入 `math/rand` 全局随机、不稳定 TLS 指纹,或后续 Qwen2API 改造。
5. `fuwei99` 的容器配置 bootstrap 和模型映射:可能改善容器首次启动体验和模型覆盖,但要先和本仓库 `config`/`model_aliases` 语义对齐。
## 当前不建议合入
1. `TonyWu2333` 的中文 prompt marker:修改核心 prompt 形状,缺少动态证据时风险高。
2. `tempppw01` 的默认禁用上游上传:本仓库已保留为可选开关,默认关闭会改变兼容行为。
3. `1cyberlangke1/dsp` 的大范围删减:删除 Vercel、文档和 Node stream 桥,不符合本仓库架构边界。
4. `hefengfan0615` 的工具调用禁用链路:会让 `tools` 注入、OpenAI `tool_calls`、Responses function-call 事件和 `DS2API_TOOLS.txt` 上传退化为纯文本,和当前协议兼容目标冲突。
5. `hefengfan0615` 删除 Output integrity guard:属于 prompt 形状削弱,只有在动态样本证明 guard 本身导致稳定回归时才考虑开关化,而不是直接删除。
6. `hefengfan0615` 的 Qwen2API 改造:包括登录 payload、session payload、completion payload、忽略 PoW、Qwen SSE 分支和模型目录的成套替换。它是另一个上游服务适配,不是 DS2API 的 DeepSeek upstream 修复。
7. `fuwei99` 的中文 prompt marker 和 `invaild-file*` current-input-file 包装/改名:会改变核心 prompt 形状和 file-reference 语义,且分支通过批量测试改写适配自身实现,不能证明对本仓库有效。
8. 未记录 fork 中的个人配置/凭证提交:`lamthien8x` 和 `dangtai2710` 当前仍主要是 `config.json` / `config.example.json` 中的个人配置或明文凭据改动,不能吸收。
## 2026-05-25 增量复查
已刷新长期监控 ref:
- 未变化:`CJackHwang` `8316cf8`、`qingdeng888` `42bc1ed`、`ricardosantis` `dc1a76c`、`tempppw01` `9aaa8b4`、`TonyWu2333` `6dbdcec`、`emptysuns` `2f87937`。
- 有更新:`fuwei99` 从 `08b4aa5` 到 `5ee2a1f`;`hefengfan0615` 从本地旧 ref `2fd3c0d` 到 `37f6206`。
- 无法刷新:`1cyberlangke1/dsp` 远端返回 repository not found,本地 `0759d7f` 保留为旧快照。
`fuwei99` 增量结论:
- `x-hif-leim` endpoint 本身有效,返回可用于 header 的 token 字符串;12 次连续探针均成功,首个请求约 225ms,后续约 31-41ms。
- 本仓库已重新实现该小块,但没有照搬上游:只在 completion/continue 路径 best-effort 查询,失败不会阻断请求;Go 和 Vercel Node runtime 保持对齐。
- 中文 role marker、清洗 `[system]`/`[user]`/`[assistant]` 文本、`invaild-file*` 文件名和 wrapper 均会改变 prompt/file contract;没有 live 证据前不采纳。
- Docker workflow 改为 buildx/cache 属于 CI 便利项;本仓库已有 release/quality gate 工作流,价值低于业务兼容候选。
`hefengfan0615` 增量结论:
- 新增 Qwen2API 方向已经不是 DeepSeek Web upstream 的小修,而是把登录、session、completion、PoW、模型目录、SSE parser 一起改成 Qwen 假设。
- `internal/sse/parser.go` 的 Qwen 分支替换了 DeepSeek `p/v` 解析路径,按本仓库目标会直接破坏现有 DeepSeek SSE。
- `/v1/models` 按账号返回模型和 WebUI 根据 key/account 重拉模型的想法可以单独立项,但该实现绑定 Qwen、绕开 `authFetch`,不能直接搬。
未记录 fork 复查:
- `lamthien8x/ds2api`:`61723a6`,主要提交个人 `config.json`,且取消忽略本地配置文件;不纳入监控。
- `kingleykin/ds2api`:`e8eea7d`,主要是越南语 `START_HERE` 和示例配置;不纳入监控。
- `dangtai2710/ds2api`:`dd730aa`,只改 `config.example.json` 中示例账号字段;不纳入监控。
- `leeamkim/ds2api`:`379d85a`,是 Synology/NAS 私有客户端骨架和 timeout 调整,和本仓库 DeepSeek/OpenAI/Claude/Gemini 适配主线无关;不纳入监控。
- `6um6n7qu/ds2api`、`maple323/ds2api`、`zzz449/ds2api`:GitHub API rate limit 后,本机 `git ls-remote` 多次返回 TLS EOF,本次未能确认远端 HEAD;保持“不纳入长期监控”的旧结论,但下次可从 GitHub forks API 重新拉取。
## 2026-05-19 其他上游快扫
已记录监控对象中,除 `1cyberlangke1/dsp` 从 `10f0ca3` 非快进更新到 `0759d7f` 外,`CJackHwang`、`qingdeng888`、`fuwei99`、`ricardosantis`、`tempppw01`、`TonyWu2333`、`emptysuns` 的 HEAD 均未变化。
GitHub forks API 按近期 push 快扫到的未记录 fork:`6um6n7qu/ds2api`、`maple323/ds2api`、`zzz449/ds2api`、`lamthien8x/ds2api`、`dangtai2710/ds2api`、`kingleykin/ds2api`、`leeamkim/ds2api`。这些分支主要是个人配置文件、占位 `main.go`/`config` 包、Synology 私有客户端、README/START_HERE 文档或同样删除 Output integrity guard;未发现比当前监控清单更值得吸收的通用 DS2API 实现,暂不纳入长期监控。
+152
View File
@@ -0,0 +1,152 @@
# hefengfan0615/ds2api 上游评估报告
评估日期:2026-05-19
评估对象:
- `CJackHwang/ds2api:main`:`8316cf8`
- `hefengfan0615/ds2api:main`:`28cad19`
- 本地当前分支:`2b4e2af`
- GitHub compare:`https://github.com/CJackHwang/ds2api/compare/main...hefengfan0615:ds2api:main`
2026-05-25 增量复查:`hefengfan0615/ds2api:main` 已更新到 `37f6206`。新增提交继续扩大 Qwen2API 改造范围,包括 Qwen 模型目录、Qwen SSE `choices[].delta` 解析、忽略 PoW、WebUI 模型加载和账号相关 `/v1/models`。这些变化进一步证明该分支已偏离本仓库的 DeepSeek Web upstream owner,不适合作为 DS2API 上游修复整体吸收。
## 结论
`hefengfan0615` 分支不适合整体合入。它混合了两类完全不同的改动:
1. 请求外形/指纹实验:随机 `device_id`、随机 DeepSeek header、随机 TLS ClientHello。
2. 协议兼容削弱:禁用工具提示词注入、禁用 OpenAI/Responses 工具调用提取、取消 `DS2API_TOOLS.txt` 上传、删除 Output integrity guard。
第一类可以保留为“需要真实账号 A/B 验证”的候选,但目前无证据显示它优于本仓库当前请求外形。第二类已经被目标包测试证明会破坏现有 XML-first tool-call 协议契约,应明确拒绝。
## 变更拆解
### 1. 请求外形/指纹
该分支在 `1371e10` 中做了这些改动:
- `Login` 的 `device_id` 从固定 `"deepseek_to_api"` 改为每次登录随机 UUID-like 字符串。
- 登录和鉴权请求从 `BaseHeaders` 改为 `GetRandomizedHeaders()`。
- header 增加或随机化 `User-Agent`、`Accept-Language`、`Accept-Encoding`、`Connection`、`Cache-Control`、`Pragma`、`DNT`、`Upgrade-Insecure-Requests`,并概率性加入 `X-Requested-With`。
- TLS ClientHello 从固定 Safari 指纹改为在 Chrome、Firefox、Safari、`HelloRandomized*` 之间随机。
这个方向的动机是规避上游把请求识别为自动化客户端,但实现方式偏粗糙:
- 每次登录随机 `device_id` 会让同一账号看起来像持续换设备,不一定比稳定设备 ID 更安全。
- TLS 指纹跨浏览器和随机模板跳变,和 Android DeepSeek app header 不一致,反而可能增加异常特征。
- `math/rand` 全局随机不可复现,失败后难以定位是哪组 header/TLS 组合触发。
- 该分支没有提供真实登录、建会话、PoW、completion 成功率数据。
本地当前分支已经有一部分更稳的请求外形改造:
- `DeviceID(accountIdentifier)` 基于账号标识稳定生成,而不是所有账号共享固定字符串,也不是每次随机。
- `BaseHeaders` 已包含 `x-rangers-id` 和 `x-client-timezone-offset`。
- transport 使用 Chrome uTLS、强制 HTTP/1.1、OkHttp-like `OkHttp-Preemptive` header,并带 cookie jar。
因此,如果要继续吸收请求指纹方向,建议从“稳定 profile”开始,而不是照搬随机化。
### 2. 工具调用链路
该分支在 `3fd5f8e`、`b038dbd` 中删除或绕过了核心工具链路:
- `promptcompat.BuildOpenAIPrompt` 不再注入工具说明,直接返回空 `toolNames`。
- OpenAI non-stream formatter 不再输出 `tool_calls`,即使模型输出了可解析工具调用。
- OpenAI chat stream 不再通过 `toolstream.ProcessChunk`/`Flush` 产生 tool call delta。
- OpenAI Responses stream 不再产生 function-call item 和 arguments events。
- `current_input_file` 模式不再上传 `DS2API_TOOLS.txt`,只上传历史正文。
这不是“优化 AI 响应”,而是把工具调用能力降级为纯文本输出。更严重的是,部分路径仍可能给出 `finish_reason=tool_calls`,但缺少对应 `tool_calls` delta 或 function-call events,形成协议不一致。
本仓库的协议契约是 XML-first:
- prompt 只把 canonical XML 作为可执行工具调用格式。
- Go 和 Node/Vercel stream 必须保持工具筛分语义一致。
- 历史 assistant `tool_calls` 会转成 XML 保留在 prompt 中。
`hefengfan0615` 没有修改 Node/Vercel streaming 实现,因此如果只合入 Go 侧禁用工具链路,还会制造本地 Go runtime 和 Vercel Node runtime 的行为漂移。
### 3. Output integrity guard
该分支在 `2a314f4` 删除了 `Output integrity guard` 系统提示注入。
该 guard 的目标是降低上游上下文、工具输出或解析残片出现乱码、重复、半截结构时被模型继续模仿的概率。删除它可能减少一点 prompt 干扰,但分支没有提供样本证明它导致了稳定回归。
如果后续确实发现 guard 在某些模型/任务中污染输出,合理方案是做 runtime/config 开关和样本回放测试,而不是直接删除默认保护。
## 动态验证
### 目标包测试
命令:
```bash
go test ./internal/promptcompat ./internal/format/openai ./internal/httpapi/openai/chat ./internal/httpapi/openai/responses ./internal/deepseek/protocol ./internal/deepseek/client ./internal/deepseek/transport
```
本地当前分支结果:通过。
`hefengfan0615` 临时 worktree 结果:失败,失败点集中在协议兼容链路:
- `internal/promptcompat`
- 工具名为空。
- 缺少最终 tool-call anchor instruction。
- 缺少 Output integrity guard。
- 缺少 read-like tool cache guard。
- `internal/format/openai`
- schema-declared string 参数保护测试 panic,因为 expected `tool_calls` 被删除。
- `internal/httpapi/openai/chat`
- thinking 中工具调用无法提升为 structured `tool_calls`。
- stream finalize fallback 缺少 tool call delta。
- Vercel prepare 缺少 DSML/XML 工具提示。
- `current_input_file` 只上传 1 个文件,缺少 tools 文件。
- `internal/httpapi/openai/responses`
- stream 不再发 function-call item / arguments done events。
- thinking/hidden-thinking 工具调用无法提升。
- schema-declared string 参数保护失效。
这组测试足以证明:禁用工具调用和删除 guard 不是可接受 backport。
### 无凭证网络探针
由于当前工作区没有 `config.json`,无法执行真实账号四段探针。为验证网络/TLS/header 层是否至少能打到 DeepSeek login endpoint,使用临时测试对三个 profile 发送无效账号登录请求,只观察 HTTP 状态和上游错误分类。
结果:
| Profile | 结果 |
| --- | --- |
| 本地当前分支,`DeepSeek/1.8.0 Android/35` + `x-rangers-id` + Chrome uTLS/OkHttp 外形 | HTTP 200,上游返回 `PASSWORD_OR_USER_NAME_IS_WRONG` |
| `CJackHwang/main`,`DeepSeek/2.0.4 Android/35` + Safari uTLS | HTTP 200,上游返回 `PASSWORD_OR_USER_NAME_IS_WRONG` |
| `hefengfan0615`,随机 UA/header/TLS,8 次无效登录 | 前 4 次 HTTP 200 + `PASSWORD_OR_USER_NAME_IS_WRONG`,后 4 次 HTTP 200 + `TOO_MANY_REQUESTS` |
这个探针只能说明三种外形都能通过网络/TLS 层到达 login endpoint;不能证明 `hefengfan0615` 的随机化提高真实账号成功率。相反,连续随机登录仍会触发上游限流,说明它不是绕过风控的充分条件。
## 证据缺口
目前未完成真实四段业务验证,原因是本地无可用 `config.json` 账号凭证。
需要补齐的探针:
1. `Login`:真实 email/mobile + password,记录 HTTP status、`code`、`biz_code`、`biz_msg`,不打印 token。
2. `CreateSession`:用登录 token 建会话,记录 session id 是否返回、错误分类和耗时。
3. `GetPow`:请求 completion target 的 PoW,记录 challenge 是否可解、错误分类和耗时。
4. `CallCompletion`:发送最小 prompt,记录 SSE 是否开始、首包耗时、最终 stop/error、403/429/空回复/静默账号分类。
对比 profile 至少应包括:
- 当前本地稳定 profile。
- 官方 `CJackHwang/main` profile。
- 候选稳定 profile:更新 app version/header,但保持 per-account stable device id。
- `hefengfan0615` 原始随机 profile,仅作为负面对照。
## 建议
1. 不合入 `hefengfan0615` 分支。
2. 不合入禁用工具调用、删除 `DS2API_TOOLS.txt`、删除 Output integrity guard 的改动。
3. 请求指纹方向只保留为实验题,不直接照搬:
- 保留 per-account stable `device_id`。
- 不使用跨浏览器随机 TLS。
- 不每次请求随机 header;如果要多 profile,应按账号或进程稳定选择。
- 用真实四段探针证明成功率提升后,再做 config/runtime 开关。
4. 如果优先级足够,下一步应写一个可复用的 live fingerprint A/B harness,而不是在业务代码里直接试错。
5. 2026-05-25 新增的 Qwen2API 改造不应纳入 DS2API 主线。账号感知模型列表可以作为独立 WebUI/接口需求重新设计,但必须保留 DeepSeek `p/v` SSE 解析、PoW、Go/Node stream 对齐和当前模型别名契约。
@@ -25,6 +25,7 @@ func (c *Client) CallCompletion(ctx context.Context, a *auth.RequestAuth, payloa
captureSession := c.capture.Start("deepseek_completion", dsprotocol.DeepSeekCompletionURL, a.AccountID, payload)
attempts := 0
for attempts < maxAttempts {
c.attachHifLeimHeader(ctx, a, headers)
resp, err := c.streamPost(ctx, clients.stream, dsprotocol.DeepSeekCompletionURL, headers, payload)
if err != nil {
if a.UseConfigToken && c.Auth.SwitchAccountWithPenalty(ctx, a, account.PenaltyNetwork) {
@@ -55,6 +55,7 @@ func (c *Client) callContinue(ctx context.Context, a *auth.RequestAuth, sessionI
clients := c.requestClientsForAuth(ctx, a)
headers := c.authHeaders(a.DeepSeekToken)
headers["x-ds-pow-response"] = powResp
c.attachHifLeimHeader(ctx, a, headers)
payload := map[string]any{
"chat_session_id": sessionID,
"message_id": responseMessageID,
+3
View File
@@ -28,6 +28,9 @@ type Client struct {
proxyClientsMu sync.RWMutex
proxyClients map[string]requestClients
hifLeimMu sync.Mutex
hifLeimSkipUntil time.Time
}
func NewClient(store *config.Store, resolver *auth.Resolver) *Client {
+160
View File
@@ -0,0 +1,160 @@
package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"ds2api/internal/auth"
"ds2api/internal/config"
dsprotocol "ds2api/internal/deepseek/protocol"
trans "ds2api/internal/deepseek/transport"
)
const (
hifLeimTimeout = 800 * time.Millisecond
hifLeimFailureBackoff = 30 * time.Second
)
var errHifLeimBackoff = errors.New("hif-leim lookup is in temporary failure backoff")
func (c *Client) attachHifLeimHeader(ctx context.Context, a *auth.RequestAuth, headers map[string]string) {
if headers == nil {
return
}
delete(headers, "x-hif-leim")
value, err := c.GetHifLeim(ctx, a)
if err != nil {
if !errors.Is(err, errHifLeimBackoff) {
accountID := ""
if a != nil {
accountID = a.AccountID
}
config.Logger.Warn("[deepseek] failed to get hif-leim token", "error", err, "account", accountID)
}
return
}
headers["x-hif-leim"] = value
}
// GetHifLeim fetches the short-lived x-hif-leim header value used by the
// DeepSeek Web completion path. Failures are non-fatal for callers.
func (c *Client) GetHifLeim(ctx context.Context, a *auth.RequestAuth) (string, error) {
if c == nil {
return "", errors.New("nil client")
}
if c.hifLeimBackoffActive(time.Now()) {
return "", errHifLeimBackoff
}
clients := c.requestClientsForAuth(ctx, a)
primary, fallback, ok := hifLeimDoers(clients)
if !ok {
return "", errors.New("no hif-leim http client available")
}
reqCtx, cancel := context.WithTimeout(ctx, hifLeimTimeout)
defer cancel()
value, err := c.fetchHifLeim(reqCtx, primary, fallback)
if err != nil {
c.markHifLeimFailure(time.Now())
return "", err
}
return value, nil
}
func hifLeimDoers(clients requestClients) (trans.Doer, trans.Doer, bool) {
if clients.regular == nil && clients.fallback == nil {
return nil, nil, false
}
primary := clients.regular
if primary == nil {
primary = clients.fallback
}
var fallback trans.Doer
if clients.fallback != nil {
fallback = clients.fallback
} else {
fallback = primary
}
return primary, fallback, true
}
func (c *Client) fetchHifLeim(ctx context.Context, primary trans.Doer, fallback trans.Doer) (string, error) {
headers := map[string]string{
"Accept": "application/json",
"User-Agent": "DeepSeek/1.8.0 Android/35",
}
resp, status, err := c.getJSONWithFallback(ctx, primary, fallback, dsprotocol.DeepSeekHifLeimURL, headers)
if err != nil {
return "", err
}
if status != http.StatusOK {
return "", fmt.Errorf("hif-leim query returned status %d", status)
}
code, bizCode, msg, bizMsg := extractResponseStatus(resp)
if code != 0 || bizCode != 0 {
return "", fmt.Errorf("hif-leim query failed: code=%d biz_code=%d msg=%q biz_msg=%q", code, bizCode, msg, bizMsg)
}
data, _ := resp["data"].(map[string]any)
bizData, _ := data["biz_data"].(map[string]any)
value, _ := bizData["value"].(string)
value = strings.TrimSpace(value)
if value == "" {
return "", errors.New("hif-leim response missing value")
}
return value, nil
}
func (c *Client) getJSONWithFallback(ctx context.Context, primary trans.Doer, fallback trans.Doer, url string, headers map[string]string) (map[string]any, int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, 0, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := primary.Do(req)
if err != nil {
config.Logger.Warn("[deepseek] hif-leim request failed, fallback to std transport", "url", url, "error", err)
req2, reqErr := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if reqErr != nil {
return nil, 0, reqErr
}
for k, v := range headers {
req2.Header.Set(k, v)
}
resp, err = fallback.Do(req2)
if err != nil {
return nil, 0, err
}
}
defer func() { _ = resp.Body.Close() }()
payloadBytes, err := readResponseBody(resp)
if err != nil {
return nil, resp.StatusCode, err
}
out := map[string]any{}
if len(payloadBytes) > 0 {
if err := json.Unmarshal(payloadBytes, &out); err != nil {
config.Logger.Warn("[deepseek] hif-leim json parse failed", "url", url, "status", resp.StatusCode, "content_encoding", resp.Header.Get("Content-Encoding"), "preview", preview(payloadBytes))
}
}
return out, resp.StatusCode, nil
}
func (c *Client) hifLeimBackoffActive(now time.Time) bool {
c.hifLeimMu.Lock()
defer c.hifLeimMu.Unlock()
return now.Before(c.hifLeimSkipUntil)
}
func (c *Client) markHifLeimFailure(now time.Time) {
c.hifLeimMu.Lock()
c.hifLeimSkipUntil = now.Add(hifLeimFailureBackoff)
c.hifLeimMu.Unlock()
}
+116
View File
@@ -0,0 +1,116 @@
package client
import (
"context"
"errors"
"io"
"net/http"
"strings"
"testing"
"ds2api/internal/auth"
dsprotocol "ds2api/internal/deepseek/protocol"
)
func hifLeimResponse(value string) *http.Response {
body := `{"code":0,"msg":"","data":{"biz_code":0,"biz_msg":"","biz_data":{"value":"` + value + `"}}}`
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(body)),
}
}
func TestGetHifLeimUsesFallbackAndParsesValue(t *testing.T) {
var fallbackURL string
var fallbackAccept string
client := &Client{
regular: failingDoer{err: errors.New("primary failed")},
fallback: &http.Client{Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
fallbackURL = req.URL.String()
fallbackAccept = req.Header.Get("Accept")
return hifLeimResponse("hif-value"), nil
})},
}
got, err := client.GetHifLeim(context.Background(), &auth.RequestAuth{DeepSeekToken: "token"})
if err != nil {
t.Fatalf("GetHifLeim returned error: %v", err)
}
if got != "hif-value" {
t.Fatalf("GetHifLeim value=%q want %q", got, "hif-value")
}
if fallbackURL != dsprotocol.DeepSeekHifLeimURL {
t.Fatalf("fallback url=%q want %q", fallbackURL, dsprotocol.DeepSeekHifLeimURL)
}
if fallbackAccept != "application/json" {
t.Fatalf("fallback Accept=%q want application/json", fallbackAccept)
}
}
func TestCallCompletionAddsHifLeimHeader(t *testing.T) {
var seenHifLeim string
client := &Client{
regular: doerFunc(func(req *http.Request) (*http.Response, error) {
if req.URL.String() != dsprotocol.DeepSeekHifLeimURL {
t.Fatalf("unexpected regular request url %s", req.URL.String())
}
return hifLeimResponse("hif-completion"), nil
}),
stream: doerFunc(func(req *http.Request) (*http.Response, error) {
seenHifLeim = req.Header.Get("x-hif-leim")
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`data: {"p":"response/content","v":"ok"}` + "\n" + `data: [DONE]` + "\n")),
Request: req,
}, nil
}),
maxRetries: 1,
}
resp, err := client.CallCompletion(context.Background(), &auth.RequestAuth{
DeepSeekToken: "token",
AccountID: "acct",
}, map[string]any{}, "pow-response", 1)
if err != nil {
t.Fatalf("CallCompletion returned error: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if seenHifLeim != "hif-completion" {
t.Fatalf("completion x-hif-leim=%q want %q", seenHifLeim, "hif-completion")
}
}
func TestCallContinueAddsHifLeimHeader(t *testing.T) {
var seenHifLeim string
client := &Client{
regular: doerFunc(func(req *http.Request) (*http.Response, error) {
if req.URL.String() != dsprotocol.DeepSeekHifLeimURL {
t.Fatalf("unexpected regular request url %s", req.URL.String())
}
return hifLeimResponse("hif-continue"), nil
}),
stream: doerFunc(func(req *http.Request) (*http.Response, error) {
seenHifLeim = req.Header.Get("x-hif-leim")
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`data: {"p":"response/content","v":"continued"}` + "\n" + `data: [DONE]` + "\n")),
Request: req,
}, nil
}),
}
resp, err := client.callContinue(context.Background(), &auth.RequestAuth{
DeepSeekToken: "token",
AccountID: "acct",
}, "session-123", 99, "pow-response")
if err != nil {
t.Fatalf("callContinue returned error: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if seenHifLeim != "hif-continue" {
t.Fatalf("continue x-hif-leim=%q want %q", seenHifLeim, "hif-continue")
}
}
+1
View File
@@ -14,6 +14,7 @@ const (
DeepSeekLoginURL = "https://chat.deepseek.com/api/v0/users/login"
DeepSeekCreateSessionURL = "https://chat.deepseek.com/api/v0/chat_session/create"
DeepSeekCreatePowURL = "https://chat.deepseek.com/api/v0/chat/create_pow_challenge"
DeepSeekHifLeimURL = "https://hif-leim.deepseek.com/query"
DeepSeekCompletionURL = "https://chat.deepseek.com/api/v0/chat/completion"
DeepSeekContinueURL = "https://chat.deepseek.com/api/v0/chat/continue"
DeepSeekUploadFileURL = "https://chat.deepseek.com/api/v0/file/upload_file"
+49 -4
View File
@@ -33,6 +33,11 @@ const {
} = require('./dedupe');
const DEEPSEEK_COMPLETION_URL = 'https://chat.deepseek.com/api/v0/chat/completion';
const DEEPSEEK_HIF_LEIM_URL = 'https://hif-leim.deepseek.com/query';
const HIF_LEIM_TIMEOUT_MS = 800;
const HIF_LEIM_FAILURE_BACKOFF_MS = 30_000;
let hifLeimSkipUntil = 0;
async function handleVercelStream(req, res, rawBody, payload) {
const prep = await fetchStreamPrepare(req, rawBody);
@@ -86,13 +91,18 @@ async function handleVercelStream(req, res, rawBody, payload) {
try {
let completionRes;
try {
completionRes = await fetch(DEEPSEEK_COMPLETION_URL, {
method: 'POST',
headers: {
const hifLeim = await fetchHifLeimHeader();
const upstreamHeaders = {
...BASE_HEADERS,
authorization: `Bearer ${deepseekToken}`,
'x-ds-pow-response': powHeader,
},
};
if (hifLeim) {
upstreamHeaders['x-hif-leim'] = hifLeim;
}
completionRes = await fetch(DEEPSEEK_COMPLETION_URL, {
method: 'POST',
headers: upstreamHeaders,
body: JSON.stringify(completionPayload),
signal: upstreamController.signal,
});
@@ -328,6 +338,41 @@ function toBool(v) {
return v === true;
}
async function fetchHifLeimHeader() {
const now = Date.now();
if (now < hifLeimSkipUntil) {
return '';
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), HIF_LEIM_TIMEOUT_MS);
try {
const response = await fetch(DEEPSEEK_HIF_LEIM_URL, {
method: 'GET',
headers: {
Accept: 'application/json',
'User-Agent': 'DeepSeek/1.8.0 Android/35',
},
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`hif-leim status ${response.status}`);
}
const body = await response.json();
const value = asString(body && body.data && body.data.biz_data && body.data.biz_data.value);
const code = Number(body && body.code);
const bizCode = Number(body && body.data && body.data.biz_code);
if (code !== 0 || bizCode !== 0 || !value) {
throw new Error('hif-leim response missing successful value');
}
return value;
} catch (_err) {
hifLeimSkipUntil = Date.now() + HIF_LEIM_FAILURE_BACKOFF_MS;
return '';
} finally {
clearTimeout(timer);
}
}
function upstreamEmptyOutputDetail(contentFilter, _text, thinking) {
if (contentFilter) {
return {
+17 -2
View File
@@ -123,6 +123,7 @@ function parseSSEDataFrames(body) {
async function runMockVercelStream(upstreamLines, prepareOverrides = {}) {
const originalFetch = global.fetch;
const fetchURLs = [];
const fetchCalls = [];
const prepareBody = {
session_id: 'chatcmpl-test',
lease_id: 'lease-test',
@@ -137,15 +138,19 @@ async function runMockVercelStream(upstreamLines, prepareOverrides = {}) {
payload: { prompt: 'hello' },
...prepareOverrides,
};
global.fetch = async (url) => {
global.fetch = async (url, options = {}) => {
const textURL = String(url);
fetchURLs.push(textURL);
fetchCalls.push({ url: textURL, options });
if (textURL.includes('__stream_prepare=1')) {
return jsonResponse(prepareBody);
}
if (textURL.includes('__stream_release=1')) {
return jsonResponse({ success: true });
}
if (textURL.includes('hif-leim.deepseek.com/query')) {
return jsonResponse({ code: 0, data: { biz_code: 0, biz_data: { value: 'node-hif-value' } } });
}
return sseResponse(upstreamLines);
};
try {
@@ -153,7 +158,7 @@ async function runMockVercelStream(upstreamLines, prepareOverrides = {}) {
const res = new MockStreamResponse();
const payload = { model: 'gpt-test', stream: true };
await handleVercelStream(req, res, Buffer.from(JSON.stringify(payload)), payload);
return { res, frames: parseSSEDataFrames(res.bodyText()), fetchURLs };
return { res, frames: parseSSEDataFrames(res.bodyText()), fetchURLs, fetchCalls };
} finally {
global.fetch = originalFetch;
}
@@ -195,6 +200,16 @@ test('vercel stream keeps stop finish when content_filter arrives after visible
assert.equal(parsed[1].usage.completion_tokens, 1);
});
test('vercel stream adds hif-leim header to DeepSeek completion request', async () => {
const { fetchCalls } = await runMockVercelStream([
'data: {"p":"response/content","v":"hello"}\n\n',
'data: [DONE]\n\n',
]);
const completionCall = fetchCalls.find((call) => call.url.includes('/api/v0/chat/completion'));
assert.ok(completionCall);
assert.equal(completionCall.options.headers['x-hif-leim'], 'node-hif-value');
});
test('resolveToolcallPolicy defaults to feature-match + early emit when prepare flags missing', () => {
const policy = resolveToolcallPolicy(
{},