Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 5 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
CMD python -c "import os,urllib.request;urllib.request.urlopen(f\"http://127.0.0.1:{os.environ.get('PORT','8000')}/health\")"

# 一个容器两个进程:Python 服务 + zen 出站桥(Bun)。`exec` 让 Python 接管
# PID 1 并接收 docker stop 的 SIGTERM;桥随容器退出(孤儿进程由内核回收)。
# 桥失败不拖垮主服务——zen 只是其中一条渠道,其余渠道必须照常可用。
CMD ["sh", "-c", "bun /app/bridge/zen/bridge.ts & exec python -m src.main"]
# PID 1 并接收 docker stop 的 SIGTERM。桥外面套一层看守循环:侧车被 OOM kill
# 后 2s 内自动重启(后面有 `/health` 的 zen_bridge 状态与 `coding2api_zen_bridge_up`
# 指标,探测周期内能看到抖动);不加看守时侧车一死,免费档 zen 会静默失效而
# 主服务仍然「健康」。桥失败不拖垮主服务——zen 只是其中一条渠道。
CMD ["sh", "-c", "while :; do bun /app/bridge/zen/bridge.ts; echo \"zen bridge exited ($?), restarting\" >&2; sleep 2; done & exec python -m src.main"]
2 changes: 1 addition & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ The authoritative list is `src/config.py`; every item is passed through `docker-
| `ZEN_GATE_TOOLS` | `bash,read` | Gate tools; may switch to `bash,glob,grep,read` (v2 needs only `read`) |
| `ZEN_USER_AGENT` | empty | UA template (`{version}` substituted); empty = legacy `opencode/<version>`, v2 `opencode/latest/<version>/cli` |
| `ZEN_PROBE_ENABLED` | `false` | Free-tier model probing switch. Probing really runs one inference per model and burns upstream free quota (counted per request), so enabling it makes real chats hit a permanent 429; unnecessary when the catalog carries `type`/`cost` |
| `ZEN_BRIDGE_URL` | `http://127.0.0.1:18799` | Free-tier outbound bridge (Bun sidecar) base URL. Upstream buckets the free tier by outbound TLS/HTTP stack fingerprint, Python/OpenSSL is a permanent 429, so the Bun sidecar is mandatory; empty = free tier goes direct (paid tier only) |
| `ZEN_BRIDGE_URL` | `http://127.0.0.1:18799` | Free-tier outbound bridge (Bun sidecar) base URL. Upstream buckets the free tier by outbound TLS/HTTP stack fingerprint, Python/OpenSSL is a permanent 429, so the Bun sidecar is mandatory; empty = free tier goes direct (paid tier only). Sidecar liveness is observable: `zen_bridge.status` in `/health` (`degraded` when `down`, still HTTP 200 for liveness), `coding2api_zen_bridge_up` in `/metrics`, and the "zen sidecar" item in `python3 scripts/doctor.py`; the image CMD restarts it within 2s of exit |
| `ZEN_BRIDGE_PROXY` | empty | Sidecar outbound proxy (e.g. `http://host.docker.internal:7897`). Free quota is also bucketed by **egress IP**: when the local IP is drained, switching egress continues to work |
| `KILO_API_ENDPOINT` | `https://api.kilo.ai/api/gateway` | Kilo upstream |
| `KILO_ALLOWED_ENDPOINTS` | `https://api.kilo.ai/api/gateway` | Kilo allowlist |
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ python3 scripts/restore_db.py data/backups/coding2api-20261014-030000.sqlite3 --
| `ZEN_GATE_TOOLS` | `bash,read` | 门禁 tools 集合;可切 `bash,glob,grep,read`(v2 实测只需 `read`) |
| `ZEN_USER_AGENT` | 空 | UA 模板(`{version}` 代入);空 = legacy `opencode/<version>`、v2 `opencode/latest/<version>/cli` |
| `ZEN_PROBE_ENABLED` | `false` | 免费档模型探活开关。探活每模型真发一次推理、吃上游免费额度(按请求计),开启会让真实对话恒 429;清单带 `type`/`cost` 时无需探活 |
| `ZEN_BRIDGE_URL` | `http://127.0.0.1:18799` | 免费档出站桥(Bun 侧车)基址。上游按出站 TLS/HTTP 栈指纹分桶免费层,Python/OpenSSL 恒 429,必须经 Bun 侧车;空 = 免费档直连(仅付费档可用) |
| `ZEN_BRIDGE_URL` | `http://127.0.0.1:18799` | 免费档出站桥(Bun 侧车)基址。上游按出站 TLS/HTTP 栈指纹分桶免费层,Python/OpenSSL 恒 429,必须经 Bun 侧车;空 = 免费档直连(仅付费档可用)。侧车存活出进程:`/health` 的 `zen_bridge.status`(`down` 时整体 `degraded`,HTTP 仍 200 存活语义)、`/metrics` 的 `coding2api_zen_bridge_up`、`python3 scripts/doctor.py` 的「zen 侧车」项;镜像 CMD 看守循环在侧车退出后 2s 内重启 |
| `ZEN_BRIDGE_PROXY` | 空 | 侧车出站代理(如 `http://host.docker.internal:7897`)。免费额度还按**出口 IP** 分桶:本机 IP 耗尽时换出口即可继续 |
| `KILO_API_ENDPOINT` | `https://api.kilo.ai/api/gateway` | Kilo 上游地址 |
| `KILO_ALLOWED_ENDPOINTS` | `https://api.kilo.ai/api/gateway` | Kilo 白名单 |
Expand Down
2 changes: 1 addition & 1 deletion TECHNICAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ class Provider(Protocol):
- 实测 2026-12-01:匿名额度耗尽时 `429 FreeUsageLimitError` 在**身份校验之前**返回,缺失门禁头也一样——门禁伪装当前不是瓶颈,仍保留以兼容额度恢复后的形态要求。详见 `docs/zen-console-scan-2026-12-01.md`。
- **403 FreeTierError 客户端内消化**:退避 `GATE_403_RETRY_DELAY`(1s)换新 session id 重发,`GATE_403_RETRIES=1`,仍 403 才上抛。**注入空壳 + 改写 / 过滤**:有同义工具(`bash`→`shell`/`execute`、`read`→`read_file`)→ 注入名改写透传;无同义工具 → 整块丢弃 + WARNING;按 `index` 跟踪分片。
- **免费清单口径 + 探活默认关**:清单本身带 `type`/`cost`,`type=chat` + 零价/`-free` 即权威,默认按目录直接返回(`ZEN_PROBE_ENABLED=false`)。探活会对每个免费模型真发一次推理,而上游免费额度**按请求计**——每次刷新清单就把额度打光,真实对话因此恒 429(2026-12-01 实测:官方 CLI 直连 200,本仓同 key 同请求 429)。需要验真时才开;开启后只剔除 `PROBE_DEAD_STATUSES`(400/401/403/404),429 / 5xx / 超时保留,判活缓存 30 分钟。
- **免费档出站桥(Bun 侧车,必需)**:2026-12-01 实测上游免费层按**出站 TLS/HTTP 栈指纹**分桶——同 IP、同 body、同 header 下,Bun `fetch` 200,Python(OpenSSL) 与 Node(undici) 恒 `429 FreeUsageLimitError`(GitHub 同类反代项目一致:`zen-proxy`/`opencode-free-provider` 都要求 Bun,Node 直接判超额)。故 `ZEN_BRIDGE_URL` 非空时,免费档的对话与清单转发给容器内的 `bridge/zen/bridge.ts`(`bun` 启动,与 Python 同容器),由它出站;侧车补齐官方 harness 形态:`stream:true`、system 首条以 `You are an AI agent running in OpenCode` 开头的 preamble(`bridge/zen/agent-preamble.txt`)、`bash/glob/grep/read` 四件套 tools、`x-opencode-session` 等四个同名头、`Bearer public`。付费档不受影响(仍直连 `/inference/openai/v1`)。侧车默认**不透传**上游 Key(`ZEN_BRIDGE_PASSTHROUGH_KEY` 才开):匿名免费凭证里残留的失效 `oc_sk_` 不应把免费层连累判死。虚拟凭证 `credential_data={}`、`added_by="system"`,`probe_quota` 恒 `probe_failed=True`;删除后重启复活,永久停用用「暂停」。
- **免费档出站桥(Bun 侧车,必需)**:2026-12-01 实测上游免费层按**出站 TLS/HTTP 栈指纹**分桶——同 IP、同 body、同 header 下,Bun `fetch` 200,Python(OpenSSL) 与 Node(undici) 恒 `429 FreeUsageLimitError`(GitHub 同类反代项目一致:`zen-proxy`/`opencode-free-provider` 都要求 Bun,Node 直接判超额)。故 `ZEN_BRIDGE_URL` 非空时,免费档的对话与清单转发给容器内的 `bridge/zen/bridge.ts`(`bun` 启动,与 Python 同容器),由它出站;侧车补齐官方 harness 形态:`stream:true`、system 首条以 `You are an AI agent running in OpenCode` 开头的 preamble(`bridge/zen/agent-preamble.txt`)、`bash/glob/grep/read` 四件套 tools、`x-opencode-session` 等四个同名头、`Bearer public`。付费档不受影响(仍直连 `/inference/openai/v1`)。侧车由镜像 CMD 的看守循环拉起(退出后 2s 重启),收到 SIGTERM/SIGINT 先 `server.stop()` 再以 0 退出;存活状态经 `GET /healthz` 出进程(`/health` 的 `zen_bridge` 字段、`/metrics` 的 `coding2api_zen_bridge_up`、doctor 的「zen 侧车」项),否则侧车被 OOM kill 后免费档静默失效而主服务照常健康。侧车默认**不透传**上游 Key(`ZEN_BRIDGE_PASSTHROUGH_KEY` 才开):匿名免费凭证里残留的失效 `oc_sk_` 不应把免费层连累判死。虚拟凭证 `credential_data={}`、`added_by="system"`,`probe_quota` 恒 `probe_failed=True`;删除后重启复活,永久停用用「暂停」。

### 5.2 Kilo(`kilo`,虚拟凭证)

Expand Down
7 changes: 6 additions & 1 deletion bridge/zen/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,14 @@ coding2api 的 zen **免费档**出站通道。Python 进程只把 OpenAI 形状
容器内由 `Dockerfile` 的 `CMD` 与 Python 一起启动:

```
bun /app/bridge/zen/bridge.ts & exec python -m src.main
while :; do bun /app/bridge/zen/bridge.ts; sleep 2; done & exec python -m src.main
```

侧车被 OOM kill 后由看守循环自动拉起(2s 后重试);本进程收到
`SIGTERM`/`SIGINT` 时先 `server.stop()` 关监听再以 0 退出,3 秒兜底强制退出,
不留残留进程。存活状态由后端探测 `GET /healthz` 出进程:`/health` 的
`zen_bridge` 字段、`/metrics` 的 `coding2api_zen_bridge_up`、doctor 的「zen 侧车」。

本地:

```bash
Expand Down
18 changes: 18 additions & 0 deletions bridge/zen/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,3 +318,21 @@ const server = Bun.serve({
console.log(`zen bridge listening on http://${server.hostname}:${server.port}`);
if (PROXY) console.log(`zen bridge egress proxy: ${PROXY}`);
else console.log("zen bridge egress: direct (no proxy)");

/**
* 优雅收尾:`docker stop` / 看守循环结束时先关监听再退出,不留残留进程。
*
* 没有这段时 Bun 收到 SIGTERM 直接死,正在透传的 SSE 被硬切断;3 秒兜底:
* `server.stop()` 卡住(还有长连接)也必须以 0 退出,否则看守循环把它当崩溃
* 重启,容器停机变成「关不掉」。
*/
for (const signal of ["SIGTERM", "SIGINT"] as const) {
process.on(signal, () => {
console.log(`zen bridge received ${signal}, closing listener`);
const force = setTimeout(() => process.exit(0), 3000);
server.stop(true).then(() => {
clearTimeout(force);
process.exit(0);
});
});
}
3 changes: 3 additions & 0 deletions scripts/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ def collect(settings: Settings, *, port: int | None = None,
doctor.check_database(settings),
doctor.check_port(settings.host, settings.port if port is None else port),
doctor.check_frontend(frontend_dist()),
# 本地侧车(非上游域名):不受 --skip-upstream 影响——它不联网,
# 且侧车挂掉时免费档 zen 静默失效,必须留下一条告警。
doctor.check_zen_bridge(settings),
]
if not skip_upstream:
checks.extend(doctor.check_upstreams(upstream_endpoints(settings)))
Expand Down
16 changes: 15 additions & 1 deletion src/api/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,14 @@ def render_metrics(
compress: dict[str, int] | None = None,
stats_write_failures: int | None = None,
model_list_degraded: list[str] | None = None,
zen_bridge_up: int | None = None,
) -> str:
"""把各数据源的聚合结果渲染成 Prometheus text 格式(纯函数)。

每个指标家族输出 `# HELP` + `# TYPE` + 样本行;样本次序由调用方保证稳定
(数据源查询已排序),这里不再重排,保持输出可复现。

`latency` / `inflight` / `compress` / `model_list_degraded` 为后加的可选
`latency` / `inflight` / `compress` / `model_list_degraded` / `zen_bridge_up` 为后加的可选
输入:缺省时不输出对应家族(旧调用方与测试逐字节不变)。
"""
lines: list[str] = []
Expand Down Expand Up @@ -149,6 +150,14 @@ def render_metrics(
lines.append(_sample(f"{PREFIX}model_list_degraded",
[("provider", provider)], 1))

if zen_bridge_up is not None:
# 侧车被 OOM kill 后免费档 zen 静默失效,而其余渠道照常,进程内没有任何
# 信号能出进程——这条 gauge 是运维唯一能告警的数值(1=存活,0=不可达)。
lines.append(f"# HELP {PREFIX}zen_bridge_up zen 免费档 Bun 侧车存活"
"(1=健康,0=不可达;杀掉侧车后一个探测周期内变 0)。")
lines.append(f"# TYPE {PREFIX}zen_bridge_up gauge")
lines.append(_sample(f"{PREFIX}zen_bridge_up", [], int(zen_bridge_up)))

if stats_write_failures is not None:
# 统计写入失败是**看得见**的静默故障:`record()` 把异常吞掉以免拖垮
# 聊天响应,没有这个计数器时「用量丢了」在进程外完全不可见。
Expand Down Expand Up @@ -257,6 +266,8 @@ async def metrics(request: Request):
[(item["key"], runner.status.failures(item["key"]))
for item in runner.task_status()]
if runner is not None else [])
# zen 免费档侧车存活:与 `/health` 同一个探测实例(TTL 缓存)
bridge = await request.app.state.zen_bridge.state()
text = render_metrics(
requests=services.stats_query.metrics_provider_model(),
tokens=services.stats_query.metrics_provider_tokens(),
Expand All @@ -276,6 +287,9 @@ async def metrics(request: Request):
# 不出这个 gauge 时外部完全看不到(issue #56 第三条)。
model_list_degraded=sorted(
pid for pid, flag in services.model_list_degraded.items() if flag),
# zen 免费档侧车(Bun):未配置桥时不出这一家族(免费档本就关着)。
zen_bridge_up=(None if bridge.status == "disabled"
else int(bridge.up)),
)
return Response(content=text, headers={"Content-Type": CONTENT_TYPE})

Expand Down
22 changes: 22 additions & 0 deletions src/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,28 @@ def probe_upstream(url: str, client: object | None = None) -> tuple[str, str]:
return PASS, f"HTTP {response.status_code}"


def check_zen_bridge(
settings: Settings,
prober: Callable[[str], tuple[str, str]] = probe_upstream,
) -> Check:
"""zen 免费档 Bun 侧车(`bridge/zen/bridge.ts`)是否还活着。

侧车与 Python 同容器启动,被 OOM kill 后没人重启:免费档 zen 从此静默
失效,而其余九条渠道照常、`/healthz` 也照常——doctor 不探这里就等于
宣称「全绿」。用 WARN 而不是 FAIL:zen 只是一条渠道,把它判死会挡住整个
部署(其余渠道与付费档都还可用)。`ZEN_BRIDGE_URL` 未配置 = 免费档本就
关着,按 PASS 处理,不制造噪声。
"""
url = settings.zen_bridge_url.strip()
if not url:
return Check("zen 侧车", PASS, "未配置 ZEN_BRIDGE_URL(免费档关闭)")
status, detail = prober(url.rstrip("/") + "/healthz")
if status == PASS:
return Check("zen 侧车", PASS, f"{url} {detail}")
return Check("zen 侧车", WARN,
f"{url} {detail};免费档 zen 将失效(其余渠道与付费档不受影响)")


def check_upstreams(
endpoints: list[tuple[str, str]],
prober: Callable[[str], tuple[str, str]] = probe_upstream,
Expand Down
19 changes: 16 additions & 3 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from pathlib import Path
from typing import Any

from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

from .api import (
Expand Down Expand Up @@ -117,6 +117,7 @@
from .instance_lock import AlreadyRunning, hold_instance_lock
from .key_quota import KeyQuotaGuard
from .observability.otlp import OtlpExporter, metrics_snapshot
from .observability.zen_bridge import ZenBridgeMonitor
from .persistence.compress_buckets import snapshot_path as compress_buckets_path
from .platform_support import require_supported_platform
from .provider.codearts import CodeArtsProvider
Expand Down Expand Up @@ -1096,6 +1097,9 @@ async def _refresh_model_catalog() -> dict[str, int]:
app.state.login_throttle = LoginThrottle()
# 上游状态页快照(纯内存):任务就地替换,路由每请求现读。
app.state.upstream_status = upstream_status_store
# zen 免费档 Bun 侧车存活探测(`/health`、`/metrics` 共用同一个实例,
# 内部 TTL 缓存;重启由镜像 CMD 的看守循环负责,见 Dockerfile)。
app.state.zen_bridge = ZenBridgeMonitor(config.zen_bridge_url)

# 路由层共享依赖容器(TECHNICAL §2 deps.py)
services = Services(
Expand Down Expand Up @@ -1151,8 +1155,17 @@ async def _refresh_model_catalog() -> dict[str, int]:
# 协议丢弃,处理函数照常返回同一份内容即可。
@app.get("/health")
@app.head("/health", include_in_schema=False)
async def health():
return {"status": "ok"}
async def health(request: Request):
"""存活探针(HTTP 恒 200)+ zen 免费档侧车存活。

HTTP 状态码不随侧车变化:容器 healthcheck 是**存活**语义,重启修不好
一个死掉的侧车,而侧车只影响 zen 一条渠道(其余九条必须照常可用)。
故障通过 `status="degraded"` 与 `zen_bridge.status="down"` 出进程,
外部监控据此报警。
"""
bridge = await request.app.state.zen_bridge.state()
return {"status": "degraded" if bridge.status == "down" else "ok",
"zen_bridge": {"status": bridge.status, "detail": bridge.detail}}

@app.get("/healthz")
@app.head("/healthz", include_in_schema=False)
Expand Down
Loading