Skip to content
This repository was archived by the owner on Nov 6, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
c99d1ad
feat(proxypool): 订阅地址懒加载为内存 IP 池(POC,未接线)
Oct 28, 2026
0fa1de4
feat: 内置订阅代理池(PROXY_SUBSCRIPTION_URL),懒加载 + 每请求轮换 + 429 自动换出口
Oct 28, 2026
05b45a1
fix(proxypool): 订阅拉取失败不缓存,下一次请求重试
Oct 28, 2026
bdb3346
feat(proxypool): 内置 mihomo 内核解析全协议节点 + 启动健康探测 + 健康节点优先轮换
Oct 28, 2026
800002d
fix(proxypool): 错误信息与日志中脱敏订阅地址
Oct 28, 2026
36494d8
feat: Vercel 无内核/本地 Docker 带内核双构建 + 定时健康检查
Oct 28, 2026
772ac32
docs: 把 PROXY_* 说明提到部署方式后的独立章节(Docker/本地通用)
Oct 28, 2026
09f433d
feat: 启动时即加载订阅并开始健康探测,不再等第一次请求
Oct 28, 2026
e3f8279
feat: 新增 PROXY_STRATEGY(sticky 填充 / round_robin 轮询)
Oct 28, 2026
a2fe158
feat: /health 返回健康节点列表(Vercel 无内核构建不返回)
Oct 28, 2026
a1a3ab0
feat: /ip 默认走节点池,?direct=1 才查直连
Oct 28, 2026
d1f2ab3
feat: /ip 同时返回 direct 与 proxy 两个出口
Oct 28, 2026
29d0e1f
feat: /ip 增加 1.1.1.1 trace 检测,三来源并发竞速先回先得
Oct 28, 2026
9358f50
docs: 同步节点池/双构建/健康检查与 /ip 说明
Oct 28, 2026
f8217ee
docs: 订阅章节改为更通用的「代理订阅与节点池」
Oct 28, 2026
8e8617b
fix: /ip 保留顶层 ip/source 兼容旧版,避免影响无内核调用方
Oct 28, 2026
a88d2f9
chore: /ip 去掉顶层 ip/source 兼容字段
Oct 28, 2026
8aeaaec
chore: 版本号升到 4.4.0
Oct 28, 2026
755572c
feat: 定时刷新订阅(PROXY_SUBSCRIPTION_REFRESH_SECONDS),失败保留旧节点池
Oct 28, 2026
16f2867
feat: 订阅刷新改为先探测新节点再整体切换
Oct 28, 2026
575c721
fix: 修复 golangci-lint errcheck 报告
Oct 28, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 40 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,26 @@ cmd/oc2api/ 入口:默认 HTTP 服务;-stdio 起 stdio JSON-RPC(Ver
internal/config 环境变量与版本号:Load() 读一次并校验,之后靠注入传下去
internal/zen uTLS 传输(Bun ClientHello)、上游路径与超时、ses_ 会话、模型列表
internal/shape 官方 system 提示词 + 工具集整形(oc2api_ 改名、32k 上限)
internal/chat 整形 → 上游 → 非流式聚合与兜底重试(Service 持有注入的 client)
internal/proxypool 订阅节点池:Clash/mihomo 解析、启动健康探测、sticky/round_robin 轮换
internal/ipinfo 出口 IP 查询(ipquery / ip-api / 1.1.1.1 trace 并发竞速)
internal/chat 整形 → 上游 → 非流式聚合;带节点池时按策略轮换、失败换节点
internal/protocol SSE 解析、聚合、[DONE]/错误语义、内置工具过滤
internal/httpapi 本地/Docker HTTP 入口(/、/health、/ip、/v1/*)
internal/rpc JSON-RPC 2.0 over stdio(Vercel 薄层用)
api/index.js Vercel 薄层:路由、鉴权、SSE 翻译、spawn Go 二进制
scripts/build-go.sh Vercel 构建期交叉编译 linux/amd64 到 bin/
scripts/build-go.sh Vercel 构建期交叉编译 linux/amd64 到 bin/(加 -tags nomihomo)
```

依赖方向单向:`config → zen/shape → chat → protocol → httpapi/rpc`。
依赖方向:`config → zen/shape → chat → protocol → httpapi/rpc`;`proxypool` 独立,
被 `chat` / `httpapi` 引用,不反向依赖它们。

## 配置怎么传

`internal/config` 是唯一读 `os.Getenv` 的地方(`Load()`,无缓存、无单例)。`main` 启动时
调一次 `config.Load()`,再把 `config.Config` 注入 `zen.New`、`chat.New`、`httpapi.New`、
`rpc.New`;其它包不许再自己读环境变量。校验失败直接 `log.Fatalf`,不要静默回落。
`rpc.New`;配置了 `PROXY_SUBSCRIPTION_URL` 时还会构造 `proxypool.Pool` 并调 `Pool.Start()`
(启动即拉订阅 + 后台健康探测)。其它包不许再自己读环境变量。校验失败直接 `log.Fatalf`,
不要静默回落。

`ZEN_API_BASE_URL` 只填**站点根**(默认 `https://opencode.ai`),接口路径写在
`internal/zen` 的 `chatPath` / `modelsPath` 常量里(`/inference/v1/chat/completions`、
Expand All @@ -34,6 +39,28 @@ TLS 握手和等响应头;正文流式读取不设上限。注意:自定义
`http.Transport.TLSHandshakeTimeout` 不生效,握手超时是在 dial 里自己加 deadline 兜的,
改这里别把 `handshakeCtx` 删了。

## 订阅节点池与双构建

订阅相关逻辑全在 `internal/proxypool`:

- `Pool.Start(ctx)` 在启动阶段拉订阅并后台健康探测(不再等第一次请求);`PROXY_STRATEGY`
决定 `sticky`(默认填充,用到不可用才换)或 `round_robin`(轮询);
- Clash YAML 由 `github.com/metacubex/mihomo/adapter.ParseProxy` 解析,支持
ss/vmess/vless/trojan/hysteria2/http/socks5;带 `dialer-proxy` 的链式节点会跳过;
- 健康探测只做真实 TLS 握手(`1.1.1.1:443` + `opencode.ai:443`),不消耗上游额度;
`PROXY_HEALTH_INTERVAL_SECONDS` 定时重试死节点、复检健康节点;
- `PROXY_SUBSCRIPTION_REFRESH_SECONDS` 定时重拉订阅;**新节点先在旧池外探测完再整体切换**,
失败/为空/新池无健康节点都保留旧池;节点状态按 `Dialer.Key()`(协议+地址+凭据哈希)跨刷新保留;
- `/health` 返回统计与健康节点列表(`?state=` 可切),`/ip` 同时返回直连与代理出口,
两个出口都由 ipquery / ip-api / 1.1.1.1 trace 并发竞速。

双构建用 `nomihomo` 标签:

- `mihomo.go` 是 `//go:build !nomihomo`,`mihomo_stub.go` 是 `//go:build nomihomo`;
- Vercel `scripts/build-go.sh` 固定 `-tags nomihomo`,二进制约 8MB,只能吃 http/socks5 代理列表;
- 本地 / Docker 默认不加 tag,带内核约 46MB,支持 Clash 全协议;
- Dockerfile 有 `ARG GO_TAGS`,`--build-arg GO_TAGS=nomihomo` 可瘦身。

## 为什么必须用 uTLS

免费层按**传输层指纹**识别客户端。同一份请求体、同一个出口 IP 下实测:
Expand Down Expand Up @@ -89,7 +116,8 @@ TLS 握手和等响应头;正文流式读取不设上限。注意:自定义
Vercel 的 Go runtime 会**缓冲整段响应**:用 700ms 间隔 flush 的测试函数,客户端 5 帧在
同一秒到达(服务端时间戳跨了 3 秒)。SSE 出不来,所以:

- `scripts/build-go.sh` 构建期下载 Go 工具链、交叉编译 `linux/amd64` 到 `bin/`;
- `scripts/build-go.sh` 构建期下载 Go 工具链、交叉编译 `linux/amd64` 到 `bin/`,并加
`-tags nomihomo`(不打包 mihomo 内核,二进制约 8MB);
- `api/index.js` 首个请求把二进制拷到 `/tmp`、`chmod +x`、`spawn -stdio` 后常驻;
- 每条请求带自增 `id`,Go 侧按 id 回通知,Node 用 `Map<id, handler>` 分发,并发流不串;
- `vercel.json` 用 `includeFiles: bin/**` 把二进制打进函数。
Expand All @@ -104,10 +132,12 @@ JSON。仓库里没有 `public/`,`.gitignore` 和 `.vercelignore` 都排除它
## 测试

```bash
go test ./... # 单元测试(整形、响应过滤、错误语义)
go test ./... # 单元测试(整形、响应过滤、错误语义、节点池/策略)
go test -tags nomihomo ./... # 无内核构建也必须能编译并过测
go vet ./...
golangci-lint run ./... # 配置见 .golangci.yml
golangci-lint run ./... # 配置见 .golangci.yml
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build ./cmd/oc2api
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags nomihomo ./cmd/oc2api
```

改动之后跑一次真实冒烟(`internal/chat/live_test.go`):一次流式 + 自定义工具的请求,
Expand All @@ -127,4 +157,7 @@ OC2API_LIVE_TEST=1 go test ./internal/chat -run Live -v
(`chat.UpstreamWithSession` 已经支持复用,只差按对话做种子 + TTL)。
- **流式没有空闲超时**:只有建连和响应头超时,上游半死不活时会挂到平台上限。
- **薄层没有 RPC 超时**:Go 子进程卡住时 Node 会一起等。
- **Vercel 无内核**:`-tags nomihomo` 构建只能解析纯文本/URI 的 http/socks5,Clash 多协议订阅
用不了,`/health` 也不返回节点列表;需要全协议请用 Docker / 本地版本。
- **节点健康状态只在内存**:进程重启会重新探测,不做持久化。
- **测试覆盖**:`internal/httpapi`、`internal/rpc` 和 `api/index.js` 还没有测试。
73 changes: 69 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ flowchart TD
首次部署大概 1–2 分钟。Vercel 的 Go runtime 会缓冲整段响应,所以 Vercel 上的流式由
`api/index.js` 这层薄 Node 转发实现,业务逻辑仍然全在 Go 二进制里。

Vercel 版用 `-tags nomihomo` 构建,**不打包 mihomo 内核**(二进制约 8 MB),所以只能使用
纯文本 / URI / base64 里的 http、socks5 代理;Clash 多协议订阅需要 Docker 或本地版本。

你也可以 Fork 后部署多个 Vercel Project 做轮询、负载分摊;多个项目不保证出口 IP 不同,
需通过各自实例的 `/ip` 核对。

Expand All @@ -77,6 +80,8 @@ docker run -d --name oc2api --restart unless-stopped \
`latest` 跟着最新版本走;要固定版本就用具体的版本 tag。

容器监听 `PORT`,默认 `8080`。镜像基于 `scratch`,里面只有静态二进制和 CA 证书。
当前镜像带 mihomo 内核(约 47 MB);想要轻量镜像可构建时加
`--build-arg GO_TAGS=nomihomo`(约 9 MB,仅 http/socks5)。
云函数环境建议把超时调到 300 秒,否则长回答的流式响应会被提前截断。

**本地构建**
Expand Down Expand Up @@ -107,6 +112,7 @@ API_KEY=your-key PORT=8080 go run ./cmd/oc2api
自建中继只填根地址即可
- `ZEN_CONNECT_TIMEOUT_MS`:建连、TLS 握手与等响应头的超时,默认 `60000`,允许 `1`–`600000`
- `DEBUG`:设为 `true` 输出调试日志
- 代理订阅相关环境变量(`PROXY_*`)见下方「[代理订阅与节点池](#代理订阅与节点池)」。

健康检查:

Expand All @@ -116,6 +122,62 @@ curl http://localhost:8080/health

</details>

## 代理订阅与节点池

**Docker 部署和本地运行都适用**:这两种构建内置 mihomo 内核,可以把一个代理订阅转成程序内的节点池——
**启动时即拉取订阅并开始健康探测**,之后按 `PROXY_STRATEGY` 选节点(默认 `sticky` 固定一个用到不可用,
`round_robin` 则每次轮询),并定时刷新订阅、失败自动换下一个。

订阅格式不限于 Clash:支持 Clash / Mihomo 的 YAML(`proxies:`)、纯文本 `IP:PORT[:USER:PASS]`、
`http://` / `socks5://` 等 URI 行、base64 包裹;其中 Clash YAML 的多协议节点
(ss / vmess / vless / trojan / hysteria2 等)由内置 mihomo 解析并拨号。
Vercel 函数版为了控制包体积不含内核,限制见本节末尾「构建变体」。

### 环境变量

| 变量 | 默认 | 说明 |
| --- | --- | --- |
| `PROXY_SUBSCRIPTION_URL` | 空(直连) | 订阅地址(http/https)。支持 Clash/Mihomo YAML(`proxies:`)、纯文本 `IP:PORT[(:USER:PASS)]`、`http://` / `socks5://` URI 行、base64 包裹;Clash YAML 里的多协议节点(ss / vmess / vless / trojan / hysteria2 等)由内置 mihomo 解析,带 `dialer-proxy` 的链式节点会跳过。 |
| `PROXY_MAX_ATTEMPTS` | `5` | 遇到 429/403/5xx 或节点不通时最多尝试几个节点,允许 `1`–`10` |
| `PROXY_STRATEGY` | `sticky` | 节点选择策略:`sticky`(填充,默认)——一个节点一直用到不可用(429/403/传输失败)才换下一个;`round_robin`——每次请求都轮询下一个健康节点 |
| `PROXY_HEALTH_INTERVAL_SECONDS` | `600` | 定时健康检查间隔秒数,允许 `60`–`86400`;`0` 关闭。定时检查会重试所有死节点,并每 30 分钟复检健康节点 |
| `PROXY_SUBSCRIPTION_REFRESH_SECONDS` | `1800` | 定时重新拉取订阅的间隔,允许 `300`–`86400`;`0` 关闭。只有拉取成功、解析出节点、且新节点探测后至少有一个健康节点才替换;失败/为空/全不健康都会**保留旧节点池**,未变节点保留健康与冷却状态 |

Docker 示例:

```bash
docker run -d --name oc2api --restart unless-stopped \
-p 8080:8080 \
-e API_KEY=your-key \
-e PROXY_SUBSCRIPTION_URL='https://你的订阅地址' \
ghcr.io/zhuweiyou/oc2api:latest
```

### 运行行为

- 加载后后台并发探测节点(真实 TLS 握手,不消耗上游额度),只把健康节点投入轮换;
- 默认每 30 分钟重新拉取订阅;**新节点先在旧池之外探测完,再整体切换**,刷新期间旧节点一直可用;
拉取失败、解析为空、或新池探测后没有健康节点时完整保留旧节点池;未变节点按稳定 key 保留健康/冷却状态;
- 默认 `sticky` 填充:固定用一个健康节点,直到它 429/403/传输失败才换下一个;`round_robin` 则每次请求轮询下一个;
- 每个请求新建连接;429/403/5xx 或节点不通时自动切换;
- `GET /ip` 同时返回 `{"direct": {...}, "proxy": {...}}`:直连出口与节点池出口各一份,
proxy 那份带实际节点名。每个出口由 `api.ipquery.io`、`ip-api.com`、`1.1.1.1/cdn-cgi/trace`
三个来源并发竞速,**谁先返回有效 IP 用谁**;trace 命中时额外返回 `warp/loc/colo`。
- `GET /health` 返回 `proxy.total / healthy / cooling / unknown`,并默认附带**健康节点列表**
(`proxy.nodes`);可用 `?state=healthy|unhealthy|cooling|all` 切换。节点名不算敏感信息,公开可见;
Vercel 无内核构建只返回统计,不返回节点列表。

### 构建变体(内核体积)

| 构建 | 命令 | 二进制约 | 订阅能力 |
| --- | --- | --- | --- |
| 无内核(Vercel) | `go build -tags nomihomo ...` | **8.4 MB** | 仅 http/socks5(纯文本、URI、base64);Clash 多协议不可用 |
| 带内核(本地 / Docker) | 不加 tag | **46.4 MB** | Clash YAML 全协议:ss/vmess/vless/trojan/hysteria2 等 |

- Vercel 的 `scripts/build-go.sh` 固定加 `-tags nomihomo`;
- Docker 默认带内核;想要瘦身镜像可 `docker build --build-arg GO_TAGS=nomihomo ...`;
- 本地 `go run ./cmd/oc2api` 默认带内核。

## API

兼容 OpenAI 格式,路径均支持带 `/v1` 前缀或不带:
Expand All @@ -124,8 +186,8 @@ curl http://localhost:8080/health
| --------------------------------------------- | ---- | ------------------------------------- |
| `/v1/chat/completions` 或 `/chat/completions` | POST | Chat 补全(支持 `stream: true` 流式) |
| `/v1/models` 或 `/models` | GET | 模型列表 |
| `/` 或 `/health` | GET | 健康检查 |
| `/ip` | GET | 查询出口 IP |
| `/` 或 `/health` | GET | 健康检查(带订阅池时含健康节点列表) |
| `/ip` | GET | 同时查询直连与节点池出口 IP(多来源竞速) |

配置 API Key 后,请求携带:

Expand Down Expand Up @@ -164,9 +226,12 @@ Authorization: Bearer <api-key>
## 开发

```bash
go test ./... # 离线单元测试
go test ./... # 离线单元测试
go test -tags nomihomo ./... # 无内核构建(Vercel 用)也要过
go vet ./...
golangci-lint run ./... # lint(配置见 .golangci.yml)
golangci-lint run ./... # lint(配置见 .golangci.yml)
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags nomihomo ./cmd/oc2api # ~8MB
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build ./cmd/oc2api # ~46MB,带内核
```

实现细节(为什么用 uTLS、免费层的形状要求、Vercel 为什么是薄 Node 层)见 [AGENTS.md](AGENTS.md)。
25 changes: 21 additions & 4 deletions cmd/oc2api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package main

import (
"context"
"flag"
"log"
"net/http"
Expand All @@ -10,6 +11,7 @@ import (
"oc2api/internal/chat"
"oc2api/internal/config"
"oc2api/internal/httpapi"
"oc2api/internal/proxypool"
"oc2api/internal/rpc"
"oc2api/internal/zen"
)
Expand All @@ -26,10 +28,25 @@ func main() {
}

client := zen.New(cfg)
chats := chat.New(cfg, client)
// 配置了订阅地址:启动阶段就加载订阅并开始健康探测,不等第一次请求。
var proxies *proxypool.Pool
if cfg.ProxySubscriptionURL != "" {
proxies = proxypool.New(cfg.ProxySubscriptionURL, cfg.ProxyHealthInterval, cfg.ProxyRefreshInterval, proxypool.Strategy(cfg.ProxyStrategy))
if err := proxies.Start(context.Background()); err != nil {
log.Printf("代理池加载失败: %v(服务继续启动,后续请求会重试)", err)
} else {
log.Printf("代理池已加载: %d 个节点,健康探测进行中", proxies.Size())
}
}
chats := chat.New(cfg, client, proxies)

proxyState := "off"
if proxies != nil {
proxyState = "on"
}

if *stdio {
log.Printf("oc2api go (stdio rpc) v%s upstream=%s timeout=%s", config.Version, cfg.ZenAPIBaseURL, cfg.ZenConnectTimeout)
log.Printf("oc2api go (stdio rpc) v%s upstream=%s timeout=%s proxy=%s", config.Version, cfg.ZenAPIBaseURL, cfg.ZenConnectTimeout, proxyState)
if err := rpc.New(cfg, client, chats).ServeStdio(); err != nil {
log.Fatal(err)
}
Expand All @@ -43,10 +60,10 @@ func main() {

server := &http.Server{
Addr: addr,
Handler: httpapi.New(cfg, client, chats),
Handler: httpapi.New(cfg, client, chats, proxies),
ReadHeaderTimeout: 15 * time.Second,
}
log.Printf("oc2api go (http) v%s listening on %s upstream=%s timeout=%s", config.Version, addr, cfg.ZenAPIBaseURL, cfg.ZenConnectTimeout)
log.Printf("oc2api go (http) v%s listening on %s upstream=%s timeout=%s proxy=%s", config.Version, addr, cfg.ZenAPIBaseURL, cfg.ZenConnectTimeout, proxyState)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
Expand Down
3 changes: 2 additions & 1 deletion docker/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# 纯 Go 运行时:编译成静态二进制,镜像里只有这个二进制和 CA 证书。
FROM golang:1.24-alpine AS build
ARG GO_TAGS=""
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -buildvcs=false -ldflags "-s -w" -o /out/oc2api ./cmd/oc2api
RUN CGO_ENABLED=0 GOOS=linux go build -tags "$GO_TAGS" -trimpath -buildvcs=false -ldflags "-s -w" -o /out/oc2api ./cmd/oc2api

FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
Expand Down
Loading
Loading