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
2 changes: 1 addition & 1 deletion PROPOSAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ Provider 只管上游私有部分(发请求、解析事件、分类错误、

判据:本仓解析边界是「HTTP + 文本信封(JSON / SSE)」,fixture 契约测试也只覆盖这一层。传输换 gRPC / protobuf、或签名算法随客户端版本漂移的渠道,接入成本不在协议适配而在**持续逆向**,故一律不进首批。

### 8.3 首批接入范围(`qwen_code` + `copilot`,两条,下一轮实现)
### 8.3 首批接入范围(`qwen_code` + `copilot`,两条,已实现)

- **协议**:两家都是 OpenAI 兼容 HTTP + 设备码登录,吞掉现有 `provider/base.py` 的凭证生命周期 / `probe_quota` / 错误分类三类接口即可;**不需要侧车**,不新增二进制协议。
- **登录轨**:设备码走现有 `poll` 轨;`copilot` 多一层「GitHub token → 短期 Copilot token」的定时预刷新,复用 `token_expiry.py` 的预刷新框架;同一 GitHub 账号重登按稳定身份就地合并。
Expand Down
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,41 @@ curl http://127.0.0.1:8000/v1/embeddings \
- **`PermissionDenied`(`403` / `403000001` / 文案「无权限」)→ `RESTRICTED`,不是瞬时**:这是**账号对话通路权限被收回**,与限流/凭证失效都不同——cookie 完全有效(账号面 `profile` / `balance` / `tasks` / `plans` 全 200、额度也在),只有对话面被拒。处置是账号级长冷却(6h 起、按命中翻倍、封顶 3 天),当前请求不再换号,管理台标「上游拒绝该账号的对话通路(换号/重贴无效)」。2026-12-01 实测三个账号 × 四条通路(agent-runtime HTTP / `cowork_web` WS / `cowork_client` WS / `ai-gateway`)× 10 个 `X-Client-Type` 枚举值**全部命中**,故 `magpie-wps-lingxi` 那条「403 回落 `cowork_web`」在本渠道**不成立**。判据见 `provider/lingxi/events.py` 的 `_PERMISSION_DENIED`。
- **ToS 灰区**:复用登录态并伪装桌面客户端(`X-Client-Type: lingxi_claw` + `x-kso-app-name/app-version/device-id`),见 `provider/tos.py`。

### GitHub Copilot(`copilot`)

GitHub Copilot 个人订阅(PROPOSAL §8.3 首批)。**两层凭证**:用户持长期 GitHub
token(`gho_…`),上游只认约 30 分钟的**短期 Copilot token**——后者由
`provider/copilot/client.exchange` 现换现用,聊天回 401 且尚未吐帧时强制重换一次,
预刷新任务按 `expires_at - 5min` 提前换。落库只有 GitHub token,故凭证能自愈。

- **登录**:GitHub OAuth 设备码(`poll` 轨,`app.state.upstream_auth["copilot"]`)。
手工导入贴 `{"github_token": "gho_…"}` 也可(没有 GitHub token 时短期票过期只能重登)。
- **端点**:聊天 `api.githubcopilot.com`(带 `Copilot-Integration-Id` +
`Editor-Version` 伪装),换票 / 额度 `api.github.com`;两者都在
`COPILOT_ALLOWED_ENDPOINTS` 白名单里。
- **额度**:`copilot_internal/user` 的 `quota_snapshots.premium_interactions`
(剩余 / 权益条数),无该快照判「未知」而非「耗尽」。
- **错误分类**:401/403 → `DEAD`(换票即恢复);402 → `CREDIT`;400/404/422 →
`INVALID`;429 → `SOFT`;5xx → `OTHER`。不新增冷却逻辑。
- **ToS 灰区**:个人订阅条款禁止转售 / 共享席位,见 `provider/tos.py`。

### Qwen Code(`qwen_code`)

Qwen Code 免费 OAuth 档(PROPOSAL §8.3 首批)。标准 OpenAI SSE
(`/api/v2/chat/completions`)+ 设备码登录,无私有签名、无设备指纹。

- **登录**:设备码 `poll` 轨(`app.state.upstream_auth["qwen_code"]`);手工导入贴
`{"access_token": "…"}`。
- **刷新**:标准 `grant_type=refresh_token`,**refresh_token 一次性轮转** → 整份
写回;上游点名 `invalid_grant` 等废票标记时抛 `UpstreamReloginRequired`,由刷新
任务标成「需重新登录」,不反复重试。
- **网关地址**:凭证里的 `resource_url` 优先(上游换集群不必改部署配置),缺失回落
`chat.qwen.ai`。
- **额度**:`/api/v2/me` 的 `quota`;无该字段判「未知」(免费档照样能聊天)。
- **错误分类**:401/403 → `DEAD`;402 → `CREDIT`;400/404/422 → `INVALID`;
429 → `SOFT`;5xx → `OTHER`。
- **ToS 灰区**:条款禁止自动化与共享,风控按账号 + IP,见 `provider/tos.py`。

### 通用上游(`generic`,可选)

接**标准 OpenAI 兼容端点**(Command Code、Kimi Code、MiniMax、智谱免费档、自建 vLLM / LiteLLM 等):无逆向、无私有协议,端点自填,凭证是本部署持有的真实 key。
Expand Down Expand Up @@ -701,6 +736,14 @@ python3 scripts/restore_db.py data/backups/coding2api-20261014-030000.sqlite3 --
| `LINGXI_API_ENDPOINT` | `https://lingxi.wps.cn` | 灵犀上游地址 |
| `LINGXI_ALLOWED_ENDPOINTS` | `https://lingxi.wps.cn,https://lingxi.kdocs.cn` | 灵犀白名单(对话面按两域顺序回落) |
| `LINGXI_CHAT_MIN_INTERVAL` | `0` | 灵犀聊天最小间隔;可热更 |
| `COPILOT_API_ENDPOINT` | `https://api.githubcopilot.com` | Copilot 聊天地址 |
| `COPILOT_GITHUB_ENDPOINT` | `https://api.github.com` | 换短期 token / 读额度地址 |
| `COPILOT_ALLOWED_ENDPOINTS` | `https://api.githubcopilot.com,https://api.github.com` | Copilot 白名单 |
| `COPILOT_GITHUB_CLIENT_ID` | `Iv1.b507a08c87ecfe98` | 设备码登录的 OAuth App client id(官方 VS Code 扩展公开值,可换成自注册的) |
| `COPILOT_CHAT_MIN_INTERVAL` | `0` | Copilot 聊天最小间隔;可热更 |
| `QWEN_CODE_API_ENDPOINT` | `https://chat.qwen.ai` | Qwen Code 上游地址 |
| `QWEN_CODE_ALLOWED_ENDPOINTS` | `https://chat.qwen.ai` | Qwen Code 白名单 |
| `QWEN_CODE_CHAT_MIN_INTERVAL` | `0` | Qwen Code 聊天最小间隔;可热更 |
| `QODER_CHAT_MIN_INTERVAL` | `5` | Qoder 节流;可热更 |
| `CODEARTS_CHAT_MIN_INTERVAL` | `5` | CodeArts 节流;可热更 |
| `CODEARTS_MAX_CONCURRENCY` | `3` | CodeArts 每账号在途并发上限;`0` 关闭;可热更 |
Expand Down
13 changes: 13 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,16 @@ services:
# 白名单必须同时含主域与 kdocs 回落域(对话面按这两个域顺序回落)。
LINGXI_API_ENDPOINT: ${LINGXI_API_ENDPOINT:-https://lingxi.wps.cn}
LINGXI_ALLOWED_ENDPOINTS: ${LINGXI_ALLOWED_ENDPOINTS:-https://lingxi.wps.cn,https://lingxi.kdocs.cn}
# GitHub Copilot:聊天走 api.githubcopilot.com,换短期 token / 读额度走
# api.github.com(两者都必须在白名单里)。COPILOT_GITHUB_CLIENT_ID 默认
# 官方 VS Code 扩展的公开值,可换成本部署自注册的 OAuth App。
COPILOT_API_ENDPOINT: ${COPILOT_API_ENDPOINT:-https://api.githubcopilot.com}
COPILOT_GITHUB_ENDPOINT: ${COPILOT_GITHUB_ENDPOINT:-https://api.github.com}
COPILOT_ALLOWED_ENDPOINTS: ${COPILOT_ALLOWED_ENDPOINTS:-https://api.githubcopilot.com,https://api.github.com}
COPILOT_GITHUB_CLIENT_ID: ${COPILOT_GITHUB_CLIENT_ID:-Iv1.b507a08c87ecfe98}
# Qwen Code(阿里,免费 OAuth 档):聊天 / 刷新 / 额度都在 chat.qwen.ai
QWEN_CODE_API_ENDPOINT: ${QWEN_CODE_API_ENDPOINT:-https://chat.qwen.ai}
QWEN_CODE_ALLOWED_ENDPOINTS: ${QWEN_CODE_ALLOWED_ENDPOINTS:-https://chat.qwen.ai}
# Qoder(阿里,COSY 私有协议):真实账号渠道。默认国内 openapi 网关;
# 国际版改 QODER_API_ENDPOINT=https://openapi.qoder.sh 并把国际版域名
# 保留在白名单里。推理走 gateway.*,额度/登录走 openapi.*。白名单防把
Expand All @@ -228,6 +238,9 @@ services:
RACCOON_AUTO_LOGIN: ${RACCOON_AUTO_LOGIN:-false}
# 灵犀聊天最小间隔(秒):独立节流器,0(默认)关闭
LINGXI_CHAT_MIN_INTERVAL: ${LINGXI_CHAT_MIN_INTERVAL:-0}
# Copilot / Qwen Code 聊天最小间隔(秒):真实订阅渠道,独立节流器
COPILOT_CHAT_MIN_INTERVAL: ${COPILOT_CHAT_MIN_INTERVAL:-0}
QWEN_CODE_CHAT_MIN_INTERVAL: ${QWEN_CODE_CHAT_MIN_INTERVAL:-0}
# Qoder / CodeArts 聊天最小间隔(秒):真实账号渠道,独立节流器
QODER_CHAT_MIN_INTERVAL: ${QODER_CHAT_MIN_INTERVAL:-5}
CODEARTS_CHAT_MIN_INTERVAL: ${CODEARTS_CHAT_MIN_INTERVAL:-5}
Expand Down
38 changes: 38 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,20 @@ class Settings(BaseSettings):
lingxi_allowed_endpoints: str = (
"https://lingxi.wps.cn,https://lingxi.kdocs.cn"
)
# GitHub Copilot:聊天走 api.githubcopilot.com,换短期 token / 读额度走
# api.github.com。两个主机都进白名单(防把 GitHub token 发往未授权主机)。
copilot_api_endpoint: str = "https://api.githubcopilot.com"
copilot_github_endpoint: str = "https://api.github.com"
copilot_allowed_endpoints: str = (
"https://api.githubcopilot.com,https://api.github.com"
)
# 设备码登录用的 GitHub OAuth App client id(默认官方 VS Code 扩展的公开
# 值;部署者可用自己注册的 App 覆盖,设备码流程里它不是机密)。
copilot_github_client_id: str = "Iv1.b507a08c87ecfe98"
# Qwen Code(阿里,免费 OAuth 档):聊天 / 刷新 / 额度都在 chat.qwen.ai;
# 白名单只为防误配(上游登录会下发 resource_url,默认同域)。
qwen_code_api_endpoint: str = "https://chat.qwen.ai"
qwen_code_allowed_endpoints: str = "https://chat.qwen.ai"
# Qoder(阿里,COSY 私有协议):真实账号渠道,端点白名单防止误把带 COSY
# 签名的请求发往未授权主机。默认取国内版;国际版改这两个值并把国际版域名
# 一并加入白名单。推理走 gateway.*,额度/登录走 openapi.*。
Expand Down Expand Up @@ -440,6 +454,10 @@ class Settings(BaseSettings):
# 小浣熊每账号并发上限:实测 5 并发放行、第 6 个 429。取 2 留余量,避免
# 与用户其它客户端抢同一账号的并发额度。0 关闭上限。
raccoon_max_concurrency: int = 2
# Copilot / Qwen Code 聊天最小间隔:真实订阅渠道,默认 0(不节流)。
# 前者按订阅席位、后者按账号 + IP 风控;各自独立节流器,与其余渠道互不排队。
copilot_chat_min_interval: float = 0
qwen_code_chat_min_interval: float = 0
# Qoder 聊天最小间隔:真实账号渠道,上游有账号级频率风控,默认 5s
# (对齐 CodeBuddy)。与 CB/TRAE/zen/kilo 各自独立,互不排队。
qoder_chat_min_interval: float = 5
Expand Down Expand Up @@ -803,6 +821,16 @@ def lingxi_allowed(self) -> tuple[str, ...]:
return tuple(e.strip().rstrip("/")
for e in self.lingxi_allowed_endpoints.split(",") if e.strip())

@cached_property
def copilot_allowed(self) -> tuple[str, ...]:
return tuple(e.strip().rstrip("/")
for e in self.copilot_allowed_endpoints.split(",") if e.strip())

@cached_property
def qwen_code_allowed(self) -> tuple[str, ...]:
return tuple(e.strip().rstrip("/")
for e in self.qwen_code_allowed_endpoints.split(",") if e.strip())

@cached_property
def qoder_allowed(self) -> tuple[str, ...]:
return tuple(e.strip().rstrip("/") for e in self.qoder_allowed_endpoints.split(",")
Expand Down Expand Up @@ -947,6 +975,16 @@ def validate_lingxi_endpoint_allowed(endpoint: str, settings: Settings) -> bool:
return endpoint.strip().rstrip("/") in settings.lingxi_allowed


def validate_copilot_endpoint_allowed(endpoint: str, settings: Settings) -> bool:
"""Copilot 端点白名单校验(防把 GitHub token 发往未授权主机)。"""
return endpoint.strip().rstrip("/") in settings.copilot_allowed


def validate_qwen_code_endpoint_allowed(endpoint: str, settings: Settings) -> bool:
"""Qwen Code 端点白名单校验(防把 token 发往未授权主机)。"""
return endpoint.strip().rstrip("/") in settings.qwen_code_allowed


def validate_qoder_endpoint_allowed(endpoint: str, settings: Settings) -> bool:
"""Qoder 端点白名单校验(防把带 COSY 签名的请求发往未授权主机)。"""
return endpoint.strip().rstrip("/") in settings.qoder_allowed
Expand Down
3 changes: 2 additions & 1 deletion src/engine/model_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
from dataclasses import dataclass

KNOWN_PROVIDERS = ("codebuddy", "codebuddy_intl", "trae", "zen", "kilo", "qoder",
"codearts", "officeace", "raccoon", "lingxi", "generic")
"codearts", "officeace", "raccoon", "lingxi", "copilot",
"qwen_code", "generic")


@dataclass(frozen=True, slots=True)
Expand Down
61 changes: 61 additions & 0 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,14 @@
trusted_proxies_problem,
validate_codearts_endpoint_allowed,
validate_codebuddy_intl_endpoint_allowed,
validate_copilot_endpoint_allowed,
validate_endpoint_allowed,
validate_generic_endpoint_allowed,
validate_kilo_endpoint_allowed,
validate_lingxi_endpoint_allowed,
validate_officeace_endpoint_allowed,
validate_qoder_endpoint_allowed,
validate_qwen_code_endpoint_allowed,
validate_raccoon_endpoint_allowed,
validate_zen_endpoint_allowed,
)
Expand Down Expand Up @@ -132,6 +134,9 @@
cache_path as model_access_cache_path,
)
from .provider.codebuddy.oauth import CodeBuddyOAuth
from .provider.copilot import CopilotProvider
from .provider.copilot.client import CopilotClient
from .provider.copilot.oauth import DEFAULT_CLIENT_ID, CopilotOAuth
from .provider.generic.client import GenericClient, GenericProvider, split_models
from .provider.kilo.client import KiloClient, KiloProvider
from .provider.lingxi import LingxiProvider
Expand All @@ -150,6 +155,9 @@
from .provider.qoder.auth import QoderOAuth
from .provider.qoder.client import QoderClient
from .provider.qoder.events import detect_realm_from_domain
from .provider.qwen_code import QwenCodeProvider
from .provider.qwen_code.client import QwenClient
from .provider.qwen_code.oauth import QwenCodeOAuth
from .provider.raccoon.client import RaccoonClient, RaccoonProvider
from .provider.trae.client import TraeClient, TraeProvider
from .provider.zen.client import ZenClient, ZenProvider
Expand Down Expand Up @@ -328,6 +336,30 @@ def _lingxi_endpoint(config: Settings) -> str:
strip_slash=True)


def _copilot_endpoints(config: Settings) -> tuple[str, str]:
"""解析 Copilot 的 (聊天主机, GitHub API 主机),两者都强制白名单校验。"""
host = _resolve_endpoint(config, attr="copilot_api_endpoint",
validator=validate_copilot_endpoint_allowed,
env_name="COPILOT_API_ENDPOINT",
allowed_name="COPILOT_ALLOWED_ENDPOINTS",
strip_slash=True)
github = _resolve_endpoint(config, attr="copilot_github_endpoint",
validator=validate_copilot_endpoint_allowed,
env_name="COPILOT_GITHUB_ENDPOINT",
allowed_name="COPILOT_ALLOWED_ENDPOINTS",
strip_slash=True)
return host, github


def _qwen_code_endpoint(config: Settings) -> str:
"""解析 Qwen Code 端点并强制白名单校验(防把 token 发往未授权主机)。"""
return _resolve_endpoint(config, attr="qwen_code_api_endpoint",
validator=validate_qwen_code_endpoint_allowed,
env_name="QWEN_CODE_API_ENDPOINT",
allowed_name="QWEN_CODE_ALLOWED_ENDPOINTS",
strip_slash=True)


def _qoder_host(config: Settings) -> str:
"""解析 Qoder openapi 端点并强制白名单校验。"""
return _resolve_endpoint(config, attr="qoder_api_endpoint",
Expand Down Expand Up @@ -568,6 +600,14 @@ def build_app(settings: Settings | None = None, *, providers: dict | None = None
lingxi_pacer = Pacer(lambda: runtime.lingxi_chat_min_interval,
lambda: runtime.lingxi_chat_min_interval,
allow_concurrent=True)
# Copilot / Qwen Code 各独立一个 pacer:前者按订阅席位、后者按账号 + IP
# 风控,与其余渠道互不排队(共享只会让一条渠道的间隔拖住另一条)。
copilot_pacer = Pacer(lambda: runtime.copilot_chat_min_interval,
lambda: runtime.copilot_chat_min_interval,
allow_concurrent=True)
qwen_code_pacer = Pacer(lambda: runtime.qwen_code_chat_min_interval,
lambda: runtime.qwen_code_chat_min_interval,
allow_concurrent=True)
# Qoder / CodeArts 是真实账号渠道,上游按账号频控;各自独立 pacer,
# 与其余渠道互不排队(同渠道同凭证共桶、桶内允许并发)。
qoder_pacer = Pacer(lambda: runtime.qoder_chat_min_interval,
Expand Down Expand Up @@ -658,6 +698,15 @@ def build_app(settings: Settings | None = None, *, providers: dict | None = None
client=KiloClient(host=_kilo_endpoint(config),
proxy=proxies.get("kilo")),
pacer=kilo_pacer),
"copilot": CopilotProvider(
client=CopilotClient(host=_copilot_endpoints(config)[0],
github_host=_copilot_endpoints(config)[1],
proxy=proxies.get("copilot")),
pacer=copilot_pacer),
"qwen_code": QwenCodeProvider(
client=QwenClient(host=_qwen_code_endpoint(config),
proxy=proxies.get("qwen_code")),
pacer=qwen_code_pacer),
"qoder": QoderProvider(
client=QoderClient(host=_qoder_host(config),
gateway=_qoder_gateway(config),
Expand Down Expand Up @@ -1321,6 +1370,18 @@ def _upstream_auth(registry: dict, settings: Settings,
endpoint = getattr(getattr(provider, "client", None), "endpoint", None)
if endpoint is not None:
flows[channel] = CodeBuddyOAuth(endpoint, proxy=proxies.get(channel))
copilot = registry.get("copilot")
copilot_client = getattr(copilot, "client", None)
if copilot_client is not None:
flows["copilot"] = CopilotOAuth(
client_id=getattr(settings, "copilot_github_client_id", "")
or DEFAULT_CLIENT_ID,
token_client=copilot_client, proxy=proxies.get("copilot"))
qwen_code = registry.get("qwen_code")
qwen_host = getattr(getattr(qwen_code, "client", None), "host", None)
if qwen_host is not None:
flows["qwen_code"] = QwenCodeOAuth(host=qwen_host,
proxy=proxies.get("qwen_code"))
qoder = registry.get("qoder")
host = getattr(getattr(qoder, "client", None), "host", None)
if host is not None:
Expand Down
Loading