From 26030797fdeecb96079aabc5651f86d910500b9a Mon Sep 17 00:00:00 2001 From: Robbs Luo Date: Thu, 3 Dec 2026 09:47:58 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat=20COD-53=EF=BC=9A=E8=90=BD=E5=9C=B0=20?= =?UTF-8?q?copilot=20/=20qwen=5Fcode=20=E4=B8=A4=E6=9D=A1=20P0=20=E6=B8=A0?= =?UTF-8?q?=E9=81=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PROPOSAL.md | 2 +- README.md | 43 +++ docker-compose.yml | 13 + src/config.py | 38 +++ src/engine/model_resolver.py | 3 +- src/main.py | 61 ++++ src/provider/copilot/__init__.py | 98 ++++++ src/provider/copilot/client.py | 278 +++++++++++++++++ src/provider/copilot/credential.py | 121 ++++++++ src/provider/copilot/events.py | 56 ++++ src/provider/copilot/oauth.py | 182 +++++++++++ src/provider/login_identity.py | 48 +++ src/provider/qwen_code/__init__.py | 98 ++++++ src/provider/qwen_code/client.py | 261 ++++++++++++++++ src/provider/qwen_code/credential.py | 119 ++++++++ src/provider/qwen_code/events.py | 55 ++++ src/provider/qwen_code/oauth.py | 163 ++++++++++ src/provider/tos.py | 10 + src/runtime_settings.py | 14 + tests/config/test_copilot_qwen_wiring.py | 153 ++++++++++ tests/provider/copilot/__init__.py | 0 tests/provider/copilot/_support.py | 21 ++ tests/provider/copilot/test_client.py | 323 ++++++++++++++++++++ tests/provider/copilot/test_credential.py | 67 ++++ tests/provider/copilot/test_oauth.py | 282 +++++++++++++++++ tests/provider/copilot/test_provider.py | 117 +++++++ tests/provider/qwen_code/__init__.py | 0 tests/provider/qwen_code/_support.py | 20 ++ tests/provider/qwen_code/test_client.py | 281 +++++++++++++++++ tests/provider/qwen_code/test_credential.py | 68 +++++ tests/provider/qwen_code/test_oauth.py | 267 ++++++++++++++++ tests/provider/qwen_code/test_provider.py | 128 ++++++++ tests/provider/test_login_identity.py | 3 +- tests/provider/trae/test_client.py | 3 +- web/src/api/__tests__/providers.test.ts | 4 +- web/src/api/providers.ts | 8 + web/src/api/types.ts | 4 +- web/src/components/AddCredentialDialog.tsx | 4 + web/src/lib/credentialImport.ts | 2 + web/src/styles.css | 6 + 40 files changed, 3417 insertions(+), 7 deletions(-) create mode 100644 src/provider/copilot/__init__.py create mode 100644 src/provider/copilot/client.py create mode 100644 src/provider/copilot/credential.py create mode 100644 src/provider/copilot/events.py create mode 100644 src/provider/copilot/oauth.py create mode 100644 src/provider/qwen_code/__init__.py create mode 100644 src/provider/qwen_code/client.py create mode 100644 src/provider/qwen_code/credential.py create mode 100644 src/provider/qwen_code/events.py create mode 100644 src/provider/qwen_code/oauth.py create mode 100644 tests/config/test_copilot_qwen_wiring.py create mode 100644 tests/provider/copilot/__init__.py create mode 100644 tests/provider/copilot/_support.py create mode 100644 tests/provider/copilot/test_client.py create mode 100644 tests/provider/copilot/test_credential.py create mode 100644 tests/provider/copilot/test_oauth.py create mode 100644 tests/provider/copilot/test_provider.py create mode 100644 tests/provider/qwen_code/__init__.py create mode 100644 tests/provider/qwen_code/_support.py create mode 100644 tests/provider/qwen_code/test_client.py create mode 100644 tests/provider/qwen_code/test_credential.py create mode 100644 tests/provider/qwen_code/test_oauth.py create mode 100644 tests/provider/qwen_code/test_provider.py diff --git a/PROPOSAL.md b/PROPOSAL.md index d4e3216a..dda57367 100644 --- a/PROPOSAL.md +++ b/PROPOSAL.md @@ -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 账号重登按稳定身份就地合并。 diff --git a/README.md b/README.md index 7e57a437..7e4307ce 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,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。 @@ -699,6 +734,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` 关闭;可热更 | diff --git a/docker-compose.yml b/docker-compose.yml index 5c51f2a4..b0c7306b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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.*。白名单防把 @@ -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} diff --git a/src/config.py b/src/config.py index 197b5585..0f19d472 100644 --- a/src/config.py +++ b/src/config.py @@ -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.*。 @@ -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 @@ -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(",") @@ -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 diff --git a/src/engine/model_resolver.py b/src/engine/model_resolver.py index c266df77..346ff95f 100644 --- a/src/engine/model_resolver.py +++ b/src/engine/model_resolver.py @@ -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) diff --git a/src/main.py b/src/main.py index 94f91df6..824e0593 100644 --- a/src/main.py +++ b/src/main.py @@ -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, ) @@ -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 @@ -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 @@ -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", @@ -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, @@ -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), @@ -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: diff --git a/src/provider/copilot/__init__.py b/src/provider/copilot/__init__.py new file mode 100644 index 00000000..eb896250 --- /dev/null +++ b/src/provider/copilot/__init__.py @@ -0,0 +1,98 @@ +"""GitHub Copilot 渠道(PROPOSAL §8.3 首批两条之一)。 + +与其余渠道的差异(决定了本包这样切): + +1. **两层凭证**:用户持长期 GitHub token,上游只认约 30 分钟的短期 Copilot + token(见 `credential.py`)。短期票由 `client.ensure_token` 现换现用, + 401 时再强制换一次;落库的只有 GitHub token,故凭证能自愈。 +2. **标准 OpenAI 协议**:`/chat/completions` 是标准 SSE(含 `[DONE]`), + 帧解析直接复用 `provider/openai_chunk`,本包只补状态码分类。 +3. **额度只在账号面**:聊天端点不报额度,`probe_quota` 读 + `copilot_internal/user` 的 `quota_snapshots`;读不到判「未知」而非「耗尽」。 + +登录轨是 GitHub OAuth 设备码(`oauth.CopilotOAuth`,挂到 +`app.state.upstream_auth["copilot"]`);手工导入也支持,贴 `github_token` 即可。 +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from typing import Any + +from ...tasks.pacer import paced +from ..base import ErrKind, Event, Model, Quota, UpstreamProtocolViolation +from ..login_identity import login_identity_for +from . import events as copilot_events +from .client import CopilotClient +from .credential import CopilotCredential + + +@dataclass(slots=True) +class CopilotProvider: + """Provider 协议实现(细接口)。只依赖注入的 client,不 import config。""" + + client: CopilotClient = field(default_factory=CopilotClient) + pacer: Any | None = None + + id: str = "copilot" + + # ------------------------------------------------------ 凭证生命周期 + + def import_credential(self, raw: dict) -> dict: + """手工导入:`{"github_token": "gho_…"}`(或裸 token 字符串包装)。""" + return CopilotCredential.from_import(raw).to_dict() + + def credential_from(self, credential_data: dict) -> CopilotCredential: + """供 RefreshTask 判断是否进入预刷新窗口。""" + return CopilotCredential.from_dict(credential_data) + + async def refresh(self, credential_data: dict) -> dict: + """预刷新:GitHub token → 新的短期 Copilot token。 + + 没有 GitHub token(手工只贴了短期票)时原样返回:换不出来,只能重登。 + """ + credential = CopilotCredential.from_dict(credential_data) + if not credential.github_token: + return credential_data + refreshed = await self.client.exchange( + credential.github_token, username=credential.username) + # 保留导入时可能带上的自定义字段(导出/再导入可逆) + data = dict(credential_data) + data.update(refreshed.to_dict()) + return data + + def login_identity(self, credential_data: dict) -> str: + """重新登录合并键:GitHub 用户名(缺省用 GitHub token 哈希)。""" + return login_identity_for(self.id, credential_data) + + # ---------------------------------------------------------------- 执行 + + def classify(self, status: int, body: bytes) -> ErrKind: + return copilot_events.classify_status(status, body) + + async def probe_quota(self, credential_data: dict) -> Quota: + return await self.client.probe_quota( + CopilotCredential.from_dict(credential_data)) + + async def list_models(self, credential_data: dict) -> list[Model]: + credential = CopilotCredential.from_dict(credential_data) + if not credential.github_token and not credential.copilot_token: + raise UpstreamProtocolViolation("copilot credential missing token") + resolved = await self.client.ensure_token(credential) + return await self.client.fetch_models(resolved.copilot_token) + + async def stream_chat(self, credential_data: dict, payload: dict, + model: str) -> AsyncIterator[Event]: + credential = CopilotCredential.from_dict(credential_data) + if not credential.github_token and not credential.copilot_token: + raise UpstreamProtocolViolation("copilot credential missing token") + async with paced(self.pacer, credential.identity()): + async for event in self.client.stream_chat(credential, payload, model): + yield event + + async def aclose(self) -> None: + await self.client.aclose() + + +__all__ = ["CopilotProvider"] diff --git a/src/provider/copilot/client.py b/src/provider/copilot/client.py new file mode 100644 index 00000000..1fecca79 --- /dev/null +++ b/src/provider/copilot/client.py @@ -0,0 +1,278 @@ +"""GitHub Copilot 上游客户端:短期 token 预刷新 + 标准 OpenAI 流 + 额度探测。 + +链路(PROPOSAL §8.2 / §8.3,均为公开文档与实测口径): + +1. `GET https://api.github.com/copilot_internal/v2/token`(`Authorization: Bearer + `)→ `{"token": …, "expires_at": …}`,寿命约 30 分钟; +2. `POST https://api.githubcopilot.com/chat/completions`,头里带短期 token 与 + `Copilot-Integration-Id` / `Editor-Version` 伪装(缺这两个头上游直接 400); +3. `GET https://api.github.com/copilot_internal/user` → `quota_snapshots`, + 额度探测只读这一处(聊天端点不报额度)。 + +**刷新策略**:短期 token 过期(含提前 `REFRESH_SKEW_SECONDS`)才换,聊天请求 +回 401 且**尚未下发任何内容**时强制重换一次。401 判定在读完响应头、开始吐帧 +之前,故重试不会重放已下发的片段。 +""" + +from __future__ import annotations + +import copy +import time +from collections.abc import AsyncIterator +from typing import Any + +import httpx + +from ...engine.sse import iter_frames +from .. import base +from ..base import Event, Model, Quota, UpstreamProtocolViolation +from ..credential_fields import expiration_from_raw +from ..http_json import json_or_raise +from ..lazy_clients import LazyClients +from . import events as copilot_events +from .credential import CopilotCredential + +#: 聊天端点(公开事实,非用户可配置输入) +COPILOT_HOST = "https://api.githubcopilot.com" +#: 换短期 token / 读额度的 GitHub 端点 +GITHUB_HOST = "https://api.github.com" +EP_CHAT = "/chat/completions" +EP_MODELS = "/models" +EP_TOKEN = "/copilot_internal/v2/token" +EP_USER = "/copilot_internal/user" + +#: 伪装成官方 VS Code 插件(上游按这两个头放行) +INTEGRATION_ID = "vscode-chat" +EDITOR_VERSION = "vscode/1.99.0" + + +def prepare_body(payload: dict[str, Any], model: str) -> dict[str, Any]: + """上游请求体:深拷 messages、强制 stream、写死 model。 + + deepcopy 的必要性与其它渠道相同:下游可能原地改写 messages,不能穿透回 + 引擎持有的 `request.raw`(会话粘性指纹与续写都读它)。 + """ + body = dict(payload) + body["messages"] = copy.deepcopy(payload.get("messages")) + base.normalize_developer_role(body["messages"]) + body["model"] = model + body["stream"] = True + return body + + +def chat_headers(copilot_token: str) -> dict[str, str]: + """聊天请求头:短期 token + 官方插件伪装。""" + return { + "Authorization": f"Bearer {copilot_token}", + "Content-Type": "application/json", + "Accept": "text/event-stream", + "Copilot-Integration-Id": INTEGRATION_ID, + "Editor-Version": EDITOR_VERSION, + } + + +def github_headers(github_token: str) -> dict[str, str]: + """GitHub API 请求头(换 token / 读额度共用)。""" + return { + "Authorization": f"Bearer {github_token}", + "Accept": "application/json", + "Editor-Version": EDITOR_VERSION, + "Copilot-Integration-Id": INTEGRATION_ID, + } + + +class UpstreamHTTPError(base.UpstreamHTTPError): + """上游非 2xx;kind() 走本渠道的状态码规则。""" + + classify_status = staticmethod(copilot_events.classify_status) + + +class CopilotClient(LazyClients): + """上游 HTTP 客户端;两个 host 均可覆盖,便于测试与灰度。""" + + def __init__( + self, + *, + host: str = COPILOT_HOST, + github_host: str = GITHUB_HOST, + stream_client: httpx.AsyncClient | None = None, + short_client: httpx.AsyncClient | None = None, + proxy: str | None = None, + ) -> None: + self.host = host.rstrip("/") + self.github_host = github_host.rstrip("/") + self._stream_client = stream_client + self._short_client = short_client + self._proxy = proxy + + # ------------------------------------------------------ 凭证生命周期 + + async def exchange(self, github_token: str, *, + username: str = "") -> CopilotCredential: + """GitHub token → 短期 Copilot token(每次现换,不猜 TTL)。""" + response = await self._short.get(f"{self.github_host}{EP_TOKEN}", + headers=github_headers(github_token)) + data = await json_or_raise( + response, UpstreamHTTPError, EP_TOKEN, + message="non-JSON copilot token response") + if not isinstance(data, dict): + raise UpstreamProtocolViolation("copilot token response is not an object") + token = data.get("token") + if not isinstance(token, str) or not token: + raise UpstreamProtocolViolation("copilot token response missing token") + return CopilotCredential( + github_token=github_token, + copilot_token=token, + expires_at=expiration_from_raw(data.get("expires_at")), + username=username, + ) + + async def ensure_token(self, credential: CopilotCredential) -> CopilotCredential: + """短期 token 仍可用则原样返回,过期则换一张。 + + 没有 GitHub token(手工只贴了短期票)时保持原凭证:过期后上游回 401 + → 判 DEAD,只能重新登录。这里不猜「也许还能用」。 + """ + if not credential.expired() or not credential.github_token: + return credential + return await self.exchange(credential.github_token, username=credential.username) + + # ---------------------------------------------------------- 聊天 + + async def stream_chat(self, credential: CopilotCredential, + payload: dict[str, Any], model: str) -> AsyncIterator[Event]: + """聊天:短期 token 被上游轮换时强制重换一次(401 且尚未吐帧)。""" + credential = await self.ensure_token(credential) + body = prepare_body(payload, model) + # 两轮要么 return 要么 raise,循环不会自然耗尽(按构造不可达分支) + for attempt in (0, 1): # pragma: no branch + try: + async for event in self._stream_once(credential, body): + yield event + return + except UpstreamHTTPError as error: + # 401 的判定发生在读完响应头之后、产出任何事件之前(见 + # `_stream_once`),所以这里重试不会重放已下发的片段。 + if attempt or error.status != 401 or not credential.github_token: + raise + credential = await self.exchange( + credential.github_token, username=credential.username) + + async def _stream_once(self, credential: CopilotCredential, + body: dict[str, Any]) -> AsyncIterator[Event]: + async with self._stream.stream( + "POST", f"{self.host}{EP_CHAT}", json=body, + headers=chat_headers(credential.copilot_token), + ) as response: + if response.status_code >= 400: + raw = await base.read_body_bounded(response) + raise UpstreamHTTPError(response.status_code, raw, + **base.retry_hints(response.headers)) + async for frame in iter_frames(response.aiter_bytes()): + for event in copilot_events.parse_events(frame): + yield event + + # ---------------------------------------------------------- 模型 + + async def fetch_models(self, copilot_token: str) -> list[Model]: + """GET /models → 中立模型表(能力与上限有则透传)。""" + response = await self._short.get( + f"{self.host}{EP_MODELS}", headers=chat_headers(copilot_token)) + data = await json_or_raise(response, UpstreamHTTPError, EP_MODELS, + message="non-JSON models response") + items = data.get("data") if isinstance(data, dict) else None + if not isinstance(items, list): + raise UpstreamProtocolViolation("models response missing data list") + models: list[Model] = [] + for item in items: + if not isinstance(item, dict): + continue + model_id = item.get("id") + if not (isinstance(model_id, str) and model_id): + continue + models.append(_model_from_item(item, model_id)) + return models + + # ---------------------------------------------------------- 额度 + + async def probe_quota(self, credential: CopilotCredential) -> Quota: + """`copilot_internal/user` 的 `quota_snapshots` → 中立额度。 + + 只取 `premium_interactions`(免费档可能没有该快照 → 未知而不是「耗尽」)。 + 上游给的是「剩余条数 / 权益条数」,不做积分换算。 + """ + now = int(time.time()) + if not credential.github_token: + return Quota(probe_failed=True, probed_at=now) + try: + response = await self._short.get(f"{self.github_host}{EP_USER}", + headers=github_headers(credential.github_token)) + data = await json_or_raise(response, UpstreamHTTPError, EP_USER, + message="non-JSON copilot user response") + except (UpstreamHTTPError, UpstreamProtocolViolation): + return Quota(probe_failed=True, probed_at=now) + snapshot = _premium_snapshot(data) + remaining = _num(snapshot.get("remaining")) + total = _num(snapshot.get("entitlement")) + if remaining is None and total is None: + return Quota(probe_failed=True, probed_at=now) + return Quota(remaining=remaining, total=total, probed_at=now) + + +def _premium_snapshot(data: Any) -> dict[str, Any]: + """取 `quota_snapshots.premium_interactions`(缺失/畸形返回空 dict)。""" + if not isinstance(data, dict): + return {} + snapshots = data.get("quota_snapshots") + if not isinstance(snapshots, dict): + return {} + premium = snapshots.get("premium_interactions") + return premium if isinstance(premium, dict) else {} + + +def _num(value: Any) -> float | None: + """数值字段:非数字 / bool 一律 None(不把「未上报」量化成 0)。""" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + return float(value) + + +def _model_from_item(item: dict[str, Any], model_id: str) -> Model: + """`/models` 条目 → 中立 Model(`capabilities` / `limits` 有则透传)。""" + name = item.get("name") + capabilities = item.get("capabilities") + capabilities = capabilities if isinstance(capabilities, dict) else {} + limits = item.get("limits") + limits = limits if isinstance(limits, dict) else {} + + def as_int(value: Any) -> int | None: + return value if isinstance(value, int) and not isinstance(value, bool) else None + + def as_bool(value: Any) -> bool | None: + return value if isinstance(value, bool) else None + + return Model( + id=model_id, + name=name if isinstance(name, str) else "", + max_input_tokens=as_int(limits.get("max_context_window_tokens")), + max_output_tokens=as_int(limits.get("max_output_tokens")), + supports_images=as_bool(capabilities.get("supports_vision")), + supports_tool_call=as_bool(capabilities.get("supports_tool_calls")), + ) + + +__all__ = [ + "COPILOT_HOST", + "EP_CHAT", + "EP_MODELS", + "EP_TOKEN", + "EP_USER", + "GITHUB_HOST", + "CopilotClient", + "UpstreamHTTPError", + "chat_headers", + "github_headers", + "prepare_body", +] + + diff --git a/src/provider/copilot/credential.py b/src/provider/copilot/credential.py new file mode 100644 index 00000000..7083314c --- /dev/null +++ b/src/provider/copilot/credential.py @@ -0,0 +1,121 @@ +"""GitHub Copilot 凭证:一张长期 GitHub token + 一张约 30 分钟的短期 Copilot token。 + +为什么是两层(PROPOSAL §8.3): + +* 用户只持有 **GitHub token**(`gho_…` / `ghu_…`,OAuth 设备码换出来的), + 它不会因为上游轮换而失效,是唯一需要落库的长期凭据; +* 真正发给 `api.githubcopilot.com` 的是 `GET /copilot_internal/v2/token` + 换回来的**短期 token**(实测约 30 分钟)。它必须由 `client.exchange` + 现换,过期就重换——不落库、不猜 TTL。 + +`needs_refresh` 因此只看 `copilot_token` 是否临近过期(提前 +`REFRESH_SKEW_SECONDS` 换),有 GitHub token 就能自愈;没有 GitHub token +(手工只贴了短期票)的凭证判 DEAD 后只能重新登录。 +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from typing import Any + +from ..base import UpstreamProtocolViolation +from ..credential_fields import sanitize_header_value, text_field + +#: 落库字段(导出 / 导入的权威形状) +GITHUB_TOKEN_KEY = "github_token" +COPILOT_TOKEN_KEY = "copilot_token" +EXPIRES_AT_KEY = "expires_at" +USERNAME_KEY = "username" + +#: 预刷新提前量:token 寿命约 30 分钟,提前 5 分钟换,避免请求临界失败 +REFRESH_SKEW_SECONDS = 300 + + +@dataclass(slots=True) +class CopilotCredential: + """归一后的 Copilot 凭证。""" + + #: 空串 = 手工只贴了短期票(换不出新票,过期只能重新登录) + github_token: str = "" + copilot_token: str = "" + expires_at: int = 0 + username: str = "" + + @classmethod + def from_dict(cls, raw: Any) -> CopilotCredential: + """落库 JSON → 凭证;缺 GitHub token 返回空凭证(调用方据此报错)。""" + if not isinstance(raw, dict): + return cls(github_token="") + expires = raw.get(EXPIRES_AT_KEY) + # 布尔是 int 的子类,必须显式排除,否则 `true` 会被当成 epoch 1 + expires_at = (expires if isinstance(expires, int) and not isinstance(expires, bool) + else 0) + return cls( + github_token=text_field(raw, GITHUB_TOKEN_KEY, "token", "access_token"), + copilot_token=text_field(raw, COPILOT_TOKEN_KEY, "bearer_token"), + expires_at=expires_at, + username=text_field(raw, USERNAME_KEY, "login"), + ) + + @classmethod + def from_import(cls, raw: Any) -> CopilotCredential: + """导入入口:形态非法(不是对象 / 没有 token)直接拒绝,不落空凭证。""" + if not isinstance(raw, dict): + raise UpstreamProtocolViolation( + "credential is not an object: paste {\"github_token\": \"gho_…\"}") + credential = cls.from_dict(raw) + if not credential.github_token: + raise UpstreamProtocolViolation( + "missing github_token: paste the GitHub OAuth token " + "({\"github_token\": \"gho_…\"}) or finish the device-code login") + return credential + + def to_dict(self) -> dict[str, Any]: + """落库形态:只留非空字段(空串回写会让界面显示一个空 token 行)。""" + out: dict[str, Any] = {GITHUB_TOKEN_KEY: self.github_token} + if self.copilot_token: + out[COPILOT_TOKEN_KEY] = self.copilot_token + if self.expires_at: + out[EXPIRES_AT_KEY] = self.expires_at + if self.username: + out[USERNAME_KEY] = self.username + return out + + def expired(self, skew_seconds: int = REFRESH_SKEW_SECONDS, + now: int | None = None) -> bool: + """短期 token 是否已过期 / 临近过期(没有 token 视为过期)。""" + if not self.copilot_token or not self.expires_at: + return True + import time + + current = int(time.time()) if now is None else now + return self.expires_at - skew_seconds <= current + + def needs_refresh(self, skew_seconds: int = REFRESH_SKEW_SECONDS, + now: int | None = None) -> bool: + """预刷新任务判定:有 GitHub token 且短期票该换了。""" + return bool(self.github_token) and self.expired(skew_seconds, now) + + def identity(self) -> str: + """稳定身份:GitHub 用户名优先,缺省用 GitHub token 的哈希前 16 位。 + + **不落 token 原文**:这个值会进运行缓存键与登录合并键。用户名在 + 手工导入时常常没有(用户只贴 token),此时退回哈希,保证「同一张 + token 重复登录」仍就地合并。 + """ + if self.username: + return self.username + if not self.github_token: + return "" + digest = hashlib.sha256(self.github_token.encode("utf-8")).hexdigest() + return f"gh-{digest[:16]}" + + def sanitized(self) -> CopilotCredential: + """清掉会破坏 HTTP 头的裸控制字符(换回来的 token 也可能带脏字节)。""" + return CopilotCredential( + github_token=sanitize_header_value(self.github_token), + copilot_token=sanitize_header_value(self.copilot_token), + expires_at=self.expires_at, + username=sanitize_header_value(self.username), + ) diff --git a/src/provider/copilot/events.py b/src/provider/copilot/events.py new file mode 100644 index 00000000..c4265160 --- /dev/null +++ b/src/provider/copilot/events.py @@ -0,0 +1,56 @@ +"""GitHub Copilot 上游 SSE 帧 → 中立事件 + 状态码分类。 + +上游是**标准 OpenAI 形状**(`choices[].delta`、`[DONE]` 收尾),故帧解析直接 +复用 `provider/openai_chunk.openai_events`;本模块只放本渠道私有的部分: + +* 状态码分类(`classify_status`):Copilot 的 401/403 是「短期 token 过期或 + GitHub 订阅不再覆盖」,判 DEAD 让预刷新 / 人工重登处理;402/429 是额度与 + 限流;5xx 是上游自身故障。 +* 流内错误信封(`_error_event`):Copilot 会把上游拒绝塞进 200 帧的 + `{"error": {...}}`,没有 HTTP 状态码可分类,保留原文供归因。 +""" + +from __future__ import annotations + +from typing import Any + +from ...engine.sse import SSEFrame +from ...provider.base import ErrKind, Event, EventKind +from ...provider.openai_chunk import openai_events + +LABEL = "GitHub Copilot" + + +def classify_status(status: int, body: bytes = b"") -> ErrKind: + """HTTP 状态码分类(不猜 body 语义:Copilot 的错误信封没有稳定码表)。 + + * 401/403 → DEAD(短期 token 过期 / 订阅不再覆盖;重换 token 即恢复) + * 402 → CREDIT(额度不足) + * 400/404/422 → INVALID(模型不存在 / 请求写错,换号无意义) + * 429 → SOFT(限流,短冷却后换号重试) + * 5xx / 其余 → OTHER(累计后冷却) + """ + if status in (401, 403): + return ErrKind.DEAD + if status == 402: + return ErrKind.CREDIT + if status in (400, 404, 422): + return ErrKind.INVALID + if status == 429: + return ErrKind.SOFT + return ErrKind.OTHER + + +def error_event(error: dict[str, Any]) -> Event: + """流内 `{"error": {...}}` 信封 → 中立 ERROR 事件(不猜账号级冷却)。""" + raw_code = error.get("code") + code = (raw_code if isinstance(raw_code, int) and not isinstance(raw_code, bool) + else None) + message = error.get("message") + return Event(kind=EventKind.ERROR, error_code=code, + error_message=str(message) if message is not None else "") + + +def parse_events(frame: SSEFrame) -> list[Event]: + """一帧 → 中立事件(标准 OpenAI chunk,含 error 信封)。""" + return openai_events(frame, LABEL, error_event=error_event) diff --git a/src/provider/copilot/oauth.py b/src/provider/copilot/oauth.py new file mode 100644 index 00000000..aeac511e --- /dev/null +++ b/src/provider/copilot/oauth.py @@ -0,0 +1,182 @@ +"""GitHub Copilot 登录轨:GitHub OAuth 设备码(`poll` 轨)。 + +三步(GitHub 官方设备码流程): + +1. `POST https://github.com/login/device/code` → `device_code` / `user_code` / + `verification_uri` / `interval`,`AuthSession` 把 `device_code` 塞进本地 + reservation 的载荷(浏览器只看到本地 reservation,看不到 device_code); +2. 前端轮询 `poll`:服务端用 `device_code` 打 + `POST https://github.com/login/oauth/access_token`, + `authorization_pending` / `slow_down` = **还在等**(不是错误), + `expired_token` / `access_denied` = 登录结束(显式报错,不无限等); +3. 拿到 GitHub token 后立刻换一张短期 Copilot token 一并落库,并尽力读 + `copilot_internal/user` 补用户名(合并键与昵称都靠它)。 + +`client_id` 是官方 VS Code 扩展的公开值(设备码流程里它不是机密), +部署者可用 `COPILOT_GITHUB_CLIENT_ID` 覆盖成自己注册的 OAuth App。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from urllib.parse import urlencode + +import httpx + +from ..auth_state import AuthStateStore +from ..base import AuthFlow, AuthResult, AuthSession, UpstreamProtocolViolation +from ..credential_fields import text_field +from ..proxy import build_client +from .client import CopilotClient + +GITHUB_LOGIN = "https://github.com" +EP_DEVICE_CODE = "/login/device/code" +EP_ACCESS_TOKEN = "/login/oauth/access_token" +#: 官方 VS Code Copilot 扩展的公开 OAuth client id(设备码流程允许公开) +DEFAULT_CLIENT_ID = "Iv1.b507a08c87ecfe98" +#: 申请设备码时声明的 scope:只要读 GitHub 身份(Copilot 订阅由服务端判) +SCOPE = "read:user" +#: 本地 pending 会话的 TTL(GitHub 的 device_code 本身 15 分钟有效) +AUTH_STATE_TTL_SECONDS = 900 +#: 上游 `slow_down` 要求的最长退避(秒) +MAX_INTERVAL = 30 +#: 「还在等用户授权」的错误码(RFC 8628):不是失败,继续轮询 +PENDING_ERRORS = ("authorization_pending", "slow_down") + + +@dataclass(slots=True) +class _Pending: + """一条 pending 登录的渠道私有载荷。""" + + device_code: str + interval: int + + +class CopilotOAuth: + """设备码登录轨(`AuthFlow.POLL`)。""" + + def __init__(self, *, client_id: str = DEFAULT_CLIENT_ID, + client: httpx.AsyncClient | None = None, + token_client: CopilotClient | None = None, + store: AuthStateStore | None = None, + proxy: str | None = None) -> None: + self.client_id = client_id + self.store: AuthStateStore = store if store is not None else AuthStateStore( + AUTH_STATE_TTL_SECONDS) + self._client = client + self._tokens = token_client if token_client is not None else CopilotClient( + proxy=proxy) + self._proxy = proxy + + @property + def _http(self) -> httpx.AsyncClient: + if self._client is None: + self._client = build_client(timeout=httpx.Timeout(30.0), proxy=self._proxy) + return self._client + + async def aclose(self) -> None: + if self._client is not None: + await self._client.aclose() + await self._tokens.aclose() + + async def start(self, username: str) -> AuthSession: + """申请设备码并登记 pending;校验通过前不让前端导航。""" + response = await self._http.post( + f"{GITHUB_LOGIN}{EP_DEVICE_CODE}", + data={"client_id": self.client_id, "scope": SCOPE}, + headers={"Accept": "application/json"}) + if response.status_code != 200: + raise UpstreamProtocolViolation("GitHub device code request rejected") + body = _json_body(response) + if body is None: + raise UpstreamProtocolViolation("GitHub device code response is not JSON") + device_code = text_field(body, "device_code") + user_code = text_field(body, "user_code") + verification_uri = text_field(body, "verification_uri") + if not device_code or not user_code or not verification_uri: + raise UpstreamProtocolViolation("GitHub device code response incomplete") + raw_interval = body.get("interval") + interval = (raw_interval if isinstance(raw_interval, int) + and not isinstance(raw_interval, bool) and raw_interval > 0 else 5) + reservation = self.store.begin( + username, _Pending(device_code=device_code, interval=interval)) + # 带上 user_code 的完整授权页:用户点开就能直接输码,不必自己抄 + auth_url = f"{verification_uri}?{urlencode({'user_code': user_code})}" + return AuthSession(flow=AuthFlow.POLL, state=reservation, auth_url=auth_url, + interval=interval, callback_url=None) + + async def poll(self, auth_state: str, username: str) -> AuthResult | None: + """返回 None 表示仍在等授权;成功后 state 被消费。""" + payload = self.store.payload(auth_state, username) + if payload is None: + raise UpstreamProtocolViolation("unknown or consumed auth state") + response = await self._http.post( + f"{GITHUB_LOGIN}{EP_ACCESS_TOKEN}", + data={"client_id": self.client_id, "device_code": payload.device_code, + "grant_type": "urn:ietf:params:oauth:grant-type:device_code"}, + headers={"Accept": "application/json"}) + # 上游默认回表单编码;只有显式要 JSON 且解析出非对象才算协议损坏。 + # 表单编码 / 空 body = 用户还没授权,按「在等」处理(不能让前端看到 + # 一条「响应格式异常」,那会把「点一下授权」误报成故障)。 + body = _json_body(response) + if body is None: + return None # 还没授权(表单编码 / 空 body) + error = text_field(body, "error") + if error in PENDING_ERRORS: + # 上游要求降频:把 interval 拉长(封顶 MAX_INTERVAL),仍算「在等」 + payload.interval = min(payload.interval + 5, MAX_INTERVAL) + return None + if error: + # expired_token / access_denied / 配置错误:登录已结束,别让前端 + # 一直转圈——消费掉 reservation 并显式报错。 + self.store.cancel(auth_state, username) + raise UpstreamProtocolViolation(f"GitHub device login ended: {error}") + github_token = text_field(body, "access_token") + if not github_token: + return None # 用户还没完成授权 + credential = await self._tokens.exchange(github_token) + credential.username = await self._fetch_login(github_token) or "" + if not self.store.consume(auth_state, username): + raise UpstreamProtocolViolation("auth state was consumed concurrently") + return AuthResult(credential_data=credential.to_dict(), + nickname=credential.username or "GitHub Copilot") + + async def _fetch_login(self, github_token: str) -> str: + """尽力补 GitHub 用户名(合并键与昵称):读不到不算登录失败。""" + try: + response = await self._http.get( + "https://api.github.com/user", + headers={"Authorization": f"Bearer {github_token}", + "Accept": "application/json"}) + except httpx.TransportError: + return "" + if response.status_code != 200 or not _is_json(response): + return "" + body = response.json() + return text_field(body, "login") if isinstance(body, dict) else "" + + +def _json_body(response: httpx.Response) -> dict | None: + """响应体 → JSON 对象;非 JSON 视为「还没授权」(返回 None)。 + + JSON 解析成功但不是对象属于协议损坏,必须显式失败。 + """ + if not _is_json(response): + return None + payload = response.json() + if not isinstance(payload, dict): + raise UpstreamProtocolViolation("GitHub response is not an object") + return payload + + +def _is_json(response: httpx.Response) -> bool: + """GitHub 的 token 端点默认回表单编码;只有显式要 JSON 时才可解析。 + + 这里用 Content-Type 判而不是直接 `response.json()`:上游把错误也回成 + `application/x-www-form-urlencoded` 时,硬解析会抛 ValueError 把「用户还 + 没授权」错报成协议损坏。 + """ + return "json" in response.headers.get("content-type", "").lower() + + +__all__ = ["AUTH_STATE_TTL_SECONDS", "CopilotOAuth", "DEFAULT_CLIENT_ID"] diff --git a/src/provider/login_identity.py b/src/provider/login_identity.py index 5f2e42a2..1f5dca88 100644 --- a/src/provider/login_identity.py +++ b/src/provider/login_identity.py @@ -99,6 +99,48 @@ def lingxi_login_identities(credential_data: dict[str, Any]) -> IdentitySet: return frozenset(alias for alias in aliases if alias) +def _token_hash_identity(raw: dict[str, Any], keys: tuple[str, ...], + prefix: str) -> str: + """token 哈希身份:`-`(与各渠道 identity 同口径)。 + + 刻意不 import 子包(门面反向 import 本模块,会成环),故在这里复制同一段 + 纯函数;两处改口径必须同步(有测试钉住)。**不落 token 原文**。 + """ + for key in keys: + value = _text(raw, key) + if value: + return f"{prefix}-{hashlib.sha256(value.encode('utf-8')).hexdigest()[:16]}" + return "" + + +def copilot_login_identity(credential_data: dict[str, Any]) -> str: + """Copilot 首选身份:GitHub 用户名;缺则 GitHub token 哈希。""" + return (_text(credential_data, "username", "login") + or _token_hash_identity(credential_data, ("github_token", "token"), "gh")) + + +def copilot_login_identities(credential_data: dict[str, Any]) -> IdentitySet: + """Copilot 全部别名:用户名与 token 哈希(老行只有 token 时靠它合并)。""" + aliases = {_text(credential_data, "username", "login"), + _token_hash_identity(credential_data, ("github_token", "token"), "gh")} + return frozenset(alias for alias in aliases if alias) + + +def qwen_code_login_identity(credential_data: dict[str, Any]) -> str: + """Qwen Code 首选身份:账号(邮箱);缺则 refresh/access token 哈希。""" + return (_text(credential_data, "account", "email", "username") + or _token_hash_identity( + credential_data, ("refresh_token", "access_token"), "qw")) + + +def qwen_code_login_identities(credential_data: dict[str, Any]) -> IdentitySet: + """Qwen Code 全部别名:账号与 token 哈希(老行只有 token 时靠它合并)。""" + aliases = {_text(credential_data, "account", "email", "username"), + _token_hash_identity( + credential_data, ("refresh_token", "access_token"), "qw")} + return frozenset(alias for alias in aliases if alias) + + def raccoon_login_identity(credential_data: dict[str, Any]) -> str: """小浣熊首选身份:JWT `sub` 解出的 `uid`(同一账号的会话会轮换)。""" return _text(credential_data, "uid", "user_id") @@ -114,6 +156,10 @@ def raccoon_login_identities(credential_data: dict[str, Any]) -> IdentitySet: #: 首选身份(展示 / 门面转发用);只有声明了身份的渠道才参与重新登录合并。 LOGIN_IDENTITIES: dict[str, Callable[[dict[str, Any]], str]] = { + # copilot / qwen_code 的身份就是各自 `credential.identity()`:GitHub 用户名 / + # 账号邮箱,缺省回落 token 哈希。刻意不 import 子包(门面反向 import 本模块)。 + "copilot": copilot_login_identity, + "qwen_code": qwen_code_login_identity, "codearts": codearts_login_identity, "officeace": officeace_login_identity, "lingxi": lingxi_login_identity, @@ -122,6 +168,8 @@ def raccoon_login_identities(credential_data: dict[str, Any]) -> IdentitySet: #: 别名集合(合并匹配用):与 `LOGIN_IDENTITIES` 必须覆盖同一批渠道。 LOGIN_IDENTITY_SETS: dict[str, Callable[[dict[str, Any]], IdentitySet]] = { + "copilot": copilot_login_identities, + "qwen_code": qwen_code_login_identities, "codearts": codearts_login_identities, "officeace": officeace_login_identities, "lingxi": lingxi_login_identities, diff --git a/src/provider/qwen_code/__init__.py b/src/provider/qwen_code/__init__.py new file mode 100644 index 00000000..081b9450 --- /dev/null +++ b/src/provider/qwen_code/__init__.py @@ -0,0 +1,98 @@ +"""Qwen Code 渠道(PROPOSAL §8.3 首批两条之一)。 + +与其余渠道的差异(决定了本包这样切): + +1. **标准 OpenAI 协议 + 设备码 OAuth**:`/api/v2/chat/completions` 是标准 + SSE(`delta` / `[DONE]`),帧解析复用 `provider/openai_chunk`;登录轨是 + 设备码轮询(`oauth.QwenCodeOAuth`,挂到 `app.state.upstream_auth`)。 +2. **一次性 refresh_token**:刷新会轮转,必须整份写回凭证,否则下一次刷新 + 拿废票(`client.refresh` 抛 `UpstreamReloginRequired`,由刷新任务标成需重登)。 +3. **网关地址由凭证下发**:`resource_url` 存在时所有请求打到它上面;缺失回落 + 默认主机。这样上游换集群时不必改部署配置。 +4. **额度可能没有接口**:`/me` 拿不到额度就判「未知」,不判「耗尽」——免费档 + 账号照样能聊天。 + +手工导入也支持:贴 `{"access_token": "…"}`(没有 refresh token 时不可自愈)。 +""" + +from __future__ import annotations + +import time +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from typing import Any + +from ...tasks.pacer import paced +from ..base import ErrKind, Event, Model, Quota, UpstreamProtocolViolation +from ..login_identity import login_identity_for +from . import events as qwen_events +from .client import QwenClient +from .credential import QwenCredential + + +@dataclass(slots=True) +class QwenCodeProvider: + """Provider 协议实现(细接口)。只依赖注入的 client,不 import config。""" + + client: QwenClient = field(default_factory=QwenClient) + pacer: Any | None = None + + id: str = "qwen_code" + + # ------------------------------------------------------ 凭证生命周期 + + def import_credential(self, raw: dict) -> dict: + """手工导入:`{"access_token": "…"}`(可选 refresh_token / resource_url)。""" + return QwenCredential.from_import(raw).to_dict() + + def credential_from(self, credential_data: dict) -> QwenCredential: + """供 RefreshTask 判断是否进入预刷新窗口。""" + return QwenCredential.from_dict(credential_data) + + async def refresh(self, credential_data: dict) -> dict: + """OAuth 预刷新;没有 refresh token 时原样返回(只能重登)。""" + credential = QwenCredential.from_dict(credential_data) + if not credential.refresh_token: + return credential_data + refreshed = await self.client.refresh(credential) + # 保留导入时可能带上的自定义字段(导出/再导入可逆) + data = dict(credential_data) + data.update(refreshed.to_dict()) + return data + + def login_identity(self, credential_data: dict) -> str: + """重新登录合并键:账号(邮箱),缺省用 token 哈希。""" + return login_identity_for(self.id, credential_data) + + # ---------------------------------------------------------------- 执行 + + def classify(self, status: int, body: bytes) -> ErrKind: + return qwen_events.classify_status(status, body) + + async def probe_quota(self, credential_data: dict) -> Quota: + credential = QwenCredential.from_dict(credential_data) + if not credential.access_token: + return Quota(probe_failed=True, probed_at=int(time.time())) + return await self.client.probe_quota(credential) + + async def list_models(self, credential_data: dict) -> list[Model]: + credential = QwenCredential.from_dict(credential_data) + if not credential.access_token: + raise UpstreamProtocolViolation("qwen_code credential missing access_token") + return await self.client.fetch_models( + credential.access_token, self.client.base_of(credential)) + + async def stream_chat(self, credential_data: dict, payload: dict, + model: str) -> AsyncIterator[Event]: + credential = QwenCredential.from_dict(credential_data) + if not credential.access_token: + raise UpstreamProtocolViolation("qwen_code credential missing access_token") + async with paced(self.pacer, credential.identity()): + async for event in self.client.stream_chat(credential, payload, model): + yield event + + async def aclose(self) -> None: + await self.client.aclose() + + +__all__ = ["QwenCodeProvider"] diff --git a/src/provider/qwen_code/client.py b/src/provider/qwen_code/client.py new file mode 100644 index 00000000..24b8b68f --- /dev/null +++ b/src/provider/qwen_code/client.py @@ -0,0 +1,261 @@ +"""Qwen Code 上游客户端:标准 OpenAI 流 + OAuth 刷新 + 额度探测。 + +链路(PROPOSAL §8.2 / §8.3): + +* 聊天:`POST {resource_url}/api/v2/chat/completions`,标准 OpenAI 请求体, + 仅流式;带 `Authorization: Bearer ` 与 `X-DashScope-CacheControl` + 之外不加私有签名(无 COSY / 无设备指纹)。 +* 刷新:`POST https://chat.qwen.ai/api/v2/oauth/token`, + `grant_type=refresh_token`;**refresh_token 一次性轮转**,响应里的新值必须 + 整份写回凭证,否则下一次刷新拿废票(`UpstreamReloginRequired`)。 +* 额度:`GET {resource_url}/api/v2/me` 的 `quota`(免费档按日给量);读不到判 + 「未知」而不是「耗尽」——没有额度接口的账号照样能聊天。 + +`resource_url` 由凭证提供(上游登录时下发),缺失回落 `DEFAULT_HOST`。 +""" + +from __future__ import annotations + +import copy +import json +import time +from collections.abc import AsyncIterator +from typing import Any + +import httpx + +from ...engine.sse import iter_frames +from .. import base +from ..base import ( + Event, + Model, + Quota, + UpstreamProtocolViolation, + UpstreamReloginRequired, +) +from ..credential_fields import text_field +from ..http_json import json_or_raise +from ..lazy_clients import LazyClients +from . import events as qwen_events +from .credential import QwenCredential + +#: 登录 / 刷新 / 额度都在这个主机上(公开事实,非用户可配置输入) +DEFAULT_HOST = "https://chat.qwen.ai" +EP_CHAT = "/api/v2/chat/completions" +EP_TOKEN = "/api/v2/oauth/token" +EP_MODELS = "/api/v2/models" +EP_ME = "/api/v2/me" + +#: 上游点名的「refresh token 已作废」标记:只能重新登录,重试是废票 +RELOGIN_MARKERS = ("invalid_grant", "invalid_refresh_token", "refresh token expired") + + +def prepare_body(payload: dict[str, Any], model: str) -> dict[str, Any]: + """上游请求体:深拷 messages、强制 stream、写死 model。 + + 与其它渠道同理:`stream` 无条件置 true——上游只有流式,非流式由引擎聚合; + deepcopy 防止下游原地改写穿透回引擎持有的 `request.raw`。 + """ + body = dict(payload) + body["messages"] = copy.deepcopy(payload.get("messages")) + base.normalize_developer_role(body["messages"]) + body["model"] = model + body["stream"] = True + return body + + +def chat_headers(access_token: str) -> dict[str, str]: + """聊天请求头:Bearer + SSE 接受。""" + return { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + "Accept": "text/event-stream", + } + + +class UpstreamHTTPError(base.UpstreamHTTPError): + """上游非 2xx;kind() 走本渠道的状态码规则。""" + + classify_status = staticmethod(qwen_events.classify_status) + + +class QwenClient(LazyClients): + """上游 HTTP 客户端;host 可覆盖,便于测试与灰度。""" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + stream_client: httpx.AsyncClient | None = None, + short_client: httpx.AsyncClient | None = None, + proxy: str | None = None, + ) -> None: + self.host = host.rstrip("/") + self._stream_client = stream_client + self._short_client = short_client + self._proxy = proxy + + def base_of(self, credential: QwenCredential) -> str: + """本账号的网关根:凭证里下发的 `resource_url` 优先。""" + return credential.resource_url or self.host + + # ------------------------------------------------------ 凭证生命周期 + + async def refresh(self, credential: QwenCredential) -> QwenCredential: + """refresh_token → 新 token 对;废票抛 `UpstreamReloginRequired`。 + + 上游轮转 refresh_token,故**整份**返回新凭证(`credential.to_dict()` + 由调用方落库);只换 access token 会让下一次刷新用废票。 + """ + response = await self._short.post( + f"{self.base_of(credential)}{EP_TOKEN}", + json={"grant_type": "refresh_token", + "refresh_token": credential.refresh_token, + "client_id": "qwen-code"}, + headers={"Content-Type": "application/json", + "Accept": "application/json"}) + body = await base.read_body_bounded(response) + if response.status_code >= 400: + text = body.decode("utf-8", errors="replace").lower() + if response.status_code in (400, 401, 403) and any( + marker in text for marker in RELOGIN_MARKERS): + raise UpstreamReloginRequired("refresh token 已作废,需重新登录") + raise UpstreamHTTPError(response.status_code, body, + **base.retry_hints(response.headers)) + data = _json_object(body, EP_TOKEN) + access_token = text_field(data, "access_token") + if not access_token: + raise UpstreamProtocolViolation("refresh response missing access_token") + return _credential_from_token(data, credential, access_token) + + # ---------------------------------------------------------- 聊天 + + async def stream_chat(self, credential: QwenCredential, + payload: dict[str, Any], model: str) -> AsyncIterator[Event]: + """POST chat/completions 并逐事件产出中立 Event。非 2xx 抛 UpstreamHTTPError。""" + body = prepare_body(payload, model) + async with self._stream.stream( + "POST", f"{self.base_of(credential)}{EP_CHAT}", json=body, + headers=chat_headers(credential.access_token), + ) as response: + if response.status_code >= 400: + raw = await base.read_body_bounded(response) + raise UpstreamHTTPError(response.status_code, raw, + **base.retry_hints(response.headers)) + async for frame in iter_frames(response.aiter_bytes()): + for event in qwen_events.parse_events(frame): + yield event + + # ---------------------------------------------------------- 模型 + + async def fetch_models(self, access_token: str, + base_url: str | None = None) -> list[Model]: + """GET /models → 中立模型表(能力与上限有则透传)。""" + response = await self._short.get( + f"{(base_url or self.host).rstrip('/')}{EP_MODELS}", + headers=chat_headers(access_token)) + data = await json_or_raise(response, UpstreamHTTPError, EP_MODELS, + message="non-JSON models response") + items = data.get("data") if isinstance(data, dict) else None + if not isinstance(items, list): + raise UpstreamProtocolViolation("models response missing data list") + models: list[Model] = [] + for item in items: + if not isinstance(item, dict): + continue + model_id = item.get("id") + if not (isinstance(model_id, str) and model_id): + continue + models.append(_model_from_item(item, model_id)) + return models + + # ---------------------------------------------------------- 额度 + + async def probe_quota(self, credential: QwenCredential) -> Quota: + """`/me` 的额度字段 → 中立额度;无该接口时判「未知」。""" + now = int(time.time()) + try: + response = await self._short.get( + f"{self.base_of(credential)}{EP_ME}", + headers=chat_headers(credential.access_token)) + data = await json_or_raise(response, UpstreamHTTPError, EP_ME, + message="non-JSON qwen me response") + except (UpstreamHTTPError, UpstreamProtocolViolation): + return Quota(probe_failed=True, probed_at=now) + quota = data.get("quota") if isinstance(data, dict) else None + quota = quota if isinstance(quota, dict) else {} + remaining = _num(quota.get("remaining")) + total = _num(quota.get("total")) + if remaining is None and total is None: + return Quota(probe_failed=True, probed_at=now) + return Quota(remaining=remaining, total=total, probed_at=now) + + +def _json_object(body: bytes, label: str) -> dict[str, Any]: + """有界 body → JSON 对象(非 JSON / 非对象都按协议违规)。""" + try: + data = json.loads(body.decode("utf-8")) + except (ValueError, UnicodeDecodeError) as error: + raise UpstreamProtocolViolation(f"non-JSON response from {label}") from error + if not isinstance(data, dict): + raise UpstreamProtocolViolation(f"response from {label} is not an object") + return data + + +def _credential_from_token(data: dict[str, Any], old: QwenCredential, + access_token: str) -> QwenCredential: + """刷新响应 → 新凭证:轮转的 refresh_token 优先,缺失时保留旧值。""" + expires_in = data.get("expires_in") + expires_at = (int(time.time()) + expires_in + if isinstance(expires_in, int) and not isinstance(expires_in, bool) + and expires_in > 0 else 0) + return QwenCredential( + access_token=access_token, + refresh_token=text_field(data, "refresh_token") or old.refresh_token, + expires_at=expires_at, + resource_url=text_field(data, "resource_url").rstrip("/") or old.resource_url, + account=old.account, + ) + + +def _num(value: Any) -> float | None: + """数值字段:非数字 / bool 一律 None(不把「未上报」量化成 0)。""" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + return float(value) + + +def _model_from_item(item: dict[str, Any], model_id: str) -> Model: + """`/models` 条目 → 中立 Model(能力与上限有则透传)。""" + name = item.get("name") + limits = item.get("limits") + limits = limits if isinstance(limits, dict) else {} + + def as_int(value: Any) -> int | None: + return value if isinstance(value, int) and not isinstance(value, bool) else None + + def as_bool(value: Any) -> bool | None: + return value if isinstance(value, bool) else None + + return Model( + id=model_id, + name=name if isinstance(name, str) else "", + max_input_tokens=as_int(limits.get("max_context_window_tokens")), + max_output_tokens=as_int(limits.get("max_output_tokens")), + supports_images=as_bool(item.get("supports_vision")), + supports_tool_call=as_bool(item.get("supports_tool_calls")), + ) + + +__all__ = [ + "DEFAULT_HOST", + "EP_CHAT", + "EP_ME", + "EP_MODELS", + "EP_TOKEN", + "RELOGIN_MARKERS", + "QwenClient", + "UpstreamHTTPError", + "chat_headers", + "prepare_body", +] diff --git a/src/provider/qwen_code/credential.py b/src/provider/qwen_code/credential.py new file mode 100644 index 00000000..2d9e13ed --- /dev/null +++ b/src/provider/qwen_code/credential.py @@ -0,0 +1,119 @@ +"""Qwen Code 凭证:设备码换出的 access / refresh token 对。 + +与其它 OAuth 渠道的差异: + +* **只有 token 对**:没有 cookie、没有设备指纹。`access_token` 约 1 小时, + `refresh_token` 长寿命,`expires_at` 由上游 `expires_in` 现算(不猜 TTL); +* **带 `resource_url`**:上游会下发本账号的网关地址(免费档也可能给 + `portal.qwen.ai` 这类别名),聊天请求必须打到它上面;缺失时回落默认主机; +* 刷新是标准 OAuth `grant_type=refresh_token`,`refresh_token` 一次性轮转, + 落库必须写回新值(见 `client.refresh`)。 + +`needs_refresh` 只看 `expires_at`:没有 refresh token 的老凭证判 DEAD 后只能 +重新登录。 +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from typing import Any + +from ..base import UpstreamProtocolViolation +from ..credential_fields import sanitize_header_value, text_field + +ACCESS_TOKEN_KEY = "access_token" +REFRESH_TOKEN_KEY = "refresh_token" +EXPIRES_AT_KEY = "expires_at" +RESOURCE_URL_KEY = "resource_url" +ACCOUNT_KEY = "account" + +#: 预刷新提前量:access token 约 1 小时,提前 5 分钟换 +REFRESH_SKEW_SECONDS = 300 + + +@dataclass(slots=True) +class QwenCredential: + """归一后的 Qwen Code 凭证。""" + + access_token: str + refresh_token: str = "" + expires_at: int = 0 + resource_url: str = "" + account: str = "" + + @classmethod + def from_dict(cls, raw: Any) -> QwenCredential: + """落库 JSON → 凭证;缺 access token 返回空凭证(调用方据此报错)。""" + if not isinstance(raw, dict): + return cls(access_token="") + expires = raw.get(EXPIRES_AT_KEY) + expires_at = (expires if isinstance(expires, int) and not isinstance(expires, bool) + else 0) + return cls( + access_token=text_field(raw, ACCESS_TOKEN_KEY, "token", "bearer_token"), + refresh_token=text_field(raw, REFRESH_TOKEN_KEY), + expires_at=expires_at, + resource_url=text_field(raw, RESOURCE_URL_KEY).rstrip("/"), + account=text_field(raw, ACCOUNT_KEY, "email", "username"), + ) + + @classmethod + def from_import(cls, raw: Any) -> QwenCredential: + """导入入口:形态非法(不是对象 / 没有 token)直接拒绝,不落空凭证。""" + if not isinstance(raw, dict): + raise UpstreamProtocolViolation( + "credential is not an object: paste {\"access_token\": \"…\"} " + "or finish the device-code login") + credential = cls.from_dict(raw) + if not credential.access_token: + raise UpstreamProtocolViolation( + "missing access_token: paste the Qwen Code token " + "({\"access_token\": \"…\"}) or finish the device-code login") + return credential + + def to_dict(self) -> dict[str, Any]: + """落库形态:只留非空字段(空串回写会让界面显示空行)。""" + out: dict[str, Any] = {ACCESS_TOKEN_KEY: self.access_token} + if self.refresh_token: + out[REFRESH_TOKEN_KEY] = self.refresh_token + if self.expires_at: + out[EXPIRES_AT_KEY] = self.expires_at + if self.resource_url: + out[RESOURCE_URL_KEY] = self.resource_url + if self.account: + out[ACCOUNT_KEY] = self.account + return out + + def needs_refresh(self, skew_seconds: int = REFRESH_SKEW_SECONDS, + now: int | None = None) -> bool: + """预刷新判定:有 refresh token 且 access token 到期/临近到期。""" + if not self.refresh_token or not self.expires_at: + return False + import time + + current = int(time.time()) if now is None else now + return self.expires_at - skew_seconds <= current + + def identity(self) -> str: + """稳定身份:账号(邮箱)优先,缺省用 refresh/access token 的哈希。 + + **不落 token 原文**:这个值会进运行缓存键与登录合并键。 + """ + if self.account: + return self.account + seed = self.refresh_token or self.access_token + if not seed: + return "" + digest = hashlib.sha256(seed.encode("utf-8")).hexdigest() + return f"qw-{digest[:16]}" + + def sanitized(self) -> QwenCredential: + """清掉会破坏 HTTP 头的裸控制字符。""" + return QwenCredential( + access_token=sanitize_header_value(self.access_token), + refresh_token=sanitize_header_value(self.refresh_token), + expires_at=self.expires_at, + resource_url=sanitize_header_value(self.resource_url), + account=sanitize_header_value(self.account), + ) diff --git a/src/provider/qwen_code/events.py b/src/provider/qwen_code/events.py new file mode 100644 index 00000000..49f136ce --- /dev/null +++ b/src/provider/qwen_code/events.py @@ -0,0 +1,55 @@ +"""Qwen Code 上游 SSE 帧 → 中立事件 + 状态码分类。 + +`chat.qwen.ai/api/v2/chat/completions` 是**标准 OpenAI 形状**的 SSE(`delta`、 +`usage`、`[DONE]` 收尾),故帧解析直接复用 `provider/openai_chunk.openai_events`。 +本模块只放渠道私有的部分: + +* 状态码分类:Qwen Code 的 401/403 是 token 过期或被上游收回(判 DEAD,预刷新 + 或重登可恢复);402 是额度;429 是限流;5xx 是上游故障。 +* 流内错误信封:上游会把拒绝塞进 200 帧的 `{"error": {...}}`。 +""" + +from __future__ import annotations + +from typing import Any + +from ...engine.sse import SSEFrame +from ...provider.base import ErrKind, Event, EventKind +from ...provider.openai_chunk import openai_events + +LABEL = "Qwen Code" + + +def classify_status(status: int, body: bytes = b"") -> ErrKind: + """HTTP 状态码分类。 + + * 401/403 → DEAD(token 失效 / 免费档资格被收回) + * 402 → CREDIT(额度不足) + * 400/404/422 → INVALID(模型不存在 / 请求写错,换号无意义) + * 429 → SOFT(限流,短冷却后换号重试) + * 5xx / 其余 → OTHER(累计后冷却) + """ + if status in (401, 403): + return ErrKind.DEAD + if status == 402: + return ErrKind.CREDIT + if status in (400, 404, 422): + return ErrKind.INVALID + if status == 429: + return ErrKind.SOFT + return ErrKind.OTHER + + +def error_event(error: dict[str, Any]) -> Event: + """流内 `{"error": {...}}` 信封 → 中立 ERROR 事件(不猜账号级冷却)。""" + raw_code = error.get("code") + code = (raw_code if isinstance(raw_code, int) and not isinstance(raw_code, bool) + else None) + message = error.get("message") + return Event(kind=EventKind.ERROR, error_code=code, + error_message=str(message) if message is not None else "") + + +def parse_events(frame: SSEFrame) -> list[Event]: + """一帧 → 中立事件(标准 OpenAI chunk,含 error 信封)。""" + return openai_events(frame, LABEL, error_event=error_event) diff --git a/src/provider/qwen_code/oauth.py b/src/provider/qwen_code/oauth.py new file mode 100644 index 00000000..0b518e98 --- /dev/null +++ b/src/provider/qwen_code/oauth.py @@ -0,0 +1,163 @@ +"""Qwen Code 登录轨:设备码轮询(`poll` 轨)。 + +流程(与 Qwen Code CLI 同口径): + +1. `POST {host}/api/v2/oauth/device/code` → `device_code` / `user_code` / + `verification_uri` / `interval`;`AuthSession` 只暴露本地 reservation, + `device_code` 留在服务端 pending 载荷里; +2. 前端轮询:`POST {host}/api/v2/oauth/token`(`grant_type= + urn:ietf:params:oauth:grant-type:device_code`), + `authorization_pending` / `slow_down` = **还在等**; + `expired_token` / `access_denied` = 登录结束(显式报错,不让前端一直转圈); +3. 拿到 token 对后把 `expires_in` 现算成 `expires_at` 一并落库(不猜 TTL)。 +""" + +from __future__ import annotations + +import time +from dataclasses import dataclass +from typing import Any +from urllib.parse import urlencode + +import httpx + +from ..auth_state import AuthStateStore +from ..base import AuthFlow, AuthResult, AuthSession, UpstreamProtocolViolation +from ..credential_fields import text_field +from ..proxy import build_client +from .client import DEFAULT_HOST, EP_ME, EP_TOKEN +from .credential import QwenCredential + +EP_DEVICE_CODE = "/api/v2/oauth/device/code" +#: 本地 pending 会话 TTL(上游 device_code 通常 10~15 分钟有效) +AUTH_STATE_TTL_SECONDS = 900 +#: 设备码流程的 grant_type(RFC 8628) +DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code" +#: `slow_down` 要求的最长退避(秒) +MAX_INTERVAL = 30 +#: 「还在等用户授权」的错误码(RFC 8628):不是失败,继续轮询 +PENDING_ERRORS = ("authorization_pending", "slow_down") + + +@dataclass(slots=True) +class _Pending: + """一条 pending 登录的渠道私有载荷。""" + + device_code: str + interval: int + + +class QwenCodeOAuth: + """设备码登录轨(`AuthFlow.POLL`)。""" + + def __init__(self, *, host: str = DEFAULT_HOST, + client: httpx.AsyncClient | None = None, + store: AuthStateStore | None = None, + proxy: str | None = None) -> None: + self.host = host.rstrip("/") + self.store: AuthStateStore = store if store is not None else AuthStateStore( + AUTH_STATE_TTL_SECONDS) + self._client = client + self._proxy = proxy + + @property + def _http(self) -> httpx.AsyncClient: + if self._client is None: + self._client = build_client(timeout=httpx.Timeout(30.0), proxy=self._proxy) + return self._client + + async def aclose(self) -> None: + if self._client is not None: + await self._client.aclose() + + async def start(self, username: str) -> AuthSession: + """申请设备码并登记 pending;校验通过前不让前端导航。""" + response = await self._http.post( + f"{self.host}{EP_DEVICE_CODE}", + json={"client_id": "qwen-code", "scope": "openid profile"}, + headers={"Content-Type": "application/json", "Accept": "application/json"}) + if response.status_code != 200: + raise UpstreamProtocolViolation("Qwen device code request rejected") + body = response.json() + if not isinstance(body, dict): + raise UpstreamProtocolViolation("Qwen device code response is not an object") + device_code = text_field(body, "device_code") + user_code = text_field(body, "user_code") + verification_uri = text_field(body, "verification_uri") + if not device_code or not user_code or not verification_uri: + raise UpstreamProtocolViolation("Qwen device code response incomplete") + raw_interval = body.get("interval") + interval = (raw_interval if isinstance(raw_interval, int) + and not isinstance(raw_interval, bool) and raw_interval > 0 else 5) + reservation = self.store.begin( + username, _Pending(device_code=device_code, interval=interval)) + auth_url = f"{verification_uri}?{urlencode({'user_code': user_code})}" + return AuthSession(flow=AuthFlow.POLL, state=reservation, auth_url=auth_url, + interval=interval, callback_url=None) + + async def poll(self, auth_state: str, username: str) -> AuthResult | None: + """返回 None 表示仍在等授权;成功后 state 被消费。""" + payload = self.store.payload(auth_state, username) + if payload is None: + raise UpstreamProtocolViolation("unknown or consumed auth state") + response = await self._http.post( + f"{self.host}{EP_TOKEN}", + json={"grant_type": DEVICE_GRANT, "device_code": payload.device_code, + "client_id": "qwen-code"}, + headers={"Content-Type": "application/json", "Accept": "application/json"}) + if response.status_code >= 500: + # 上游 5xx 是链路瞬态,不是登录失败:保持 pending 让前端下一轮再试 + return None + body = response.json() + if not isinstance(body, dict): + raise UpstreamProtocolViolation("Qwen token response is not an object") + error = text_field(body, "error") + if error in PENDING_ERRORS: + payload.interval = min(payload.interval + 5, MAX_INTERVAL) + return None + if error: + self.store.cancel(auth_state, username) + raise UpstreamProtocolViolation(f"Qwen device login ended: {error}") + access_token = text_field(body, "access_token") + if not access_token: + return None # 用户还没完成授权 + credential = _credential_from_token(body, access_token) + if not credential.account: + credential.account = await self._probe_account(credential) + if not self.store.consume(auth_state, username): + raise UpstreamProtocolViolation("auth state was consumed concurrently") + return AuthResult(credential_data=credential.to_dict(), + nickname=credential.account or "Qwen Code") + + async def _probe_account(self, credential: QwenCredential) -> str: + """尽力补账号标识(合并键与昵称):读不到不算登录失败。""" + try: + response = await self._http.get( + f"{credential.resource_url or self.host}{EP_ME}", + headers={"Authorization": f"Bearer {credential.access_token}", + "Accept": "application/json"}) + except httpx.TransportError: + return "" + if response.status_code != 200: + return "" + body = response.json() + return text_field(body, "email", "username", "account") if isinstance( + body, dict) else "" + + +def _credential_from_token(body: dict[str, Any], access_token: str) -> QwenCredential: + """设备码换回的 token 响应 → 凭证(`expires_in` 现算 `expires_at`)。""" + expires_in = body.get("expires_in") + expires_at = (int(time.time()) + expires_in + if isinstance(expires_in, int) and not isinstance(expires_in, bool) + and expires_in > 0 else 0) + return QwenCredential( + access_token=access_token, + refresh_token=text_field(body, "refresh_token"), + expires_at=expires_at, + resource_url=text_field(body, "resource_url").rstrip("/"), + account=text_field(body, "account", "email", "username"), + ) + + +__all__ = ["AUTH_STATE_TTL_SECONDS", "DEVICE_GRANT", "QwenCodeOAuth"] diff --git a/src/provider/tos.py b/src/provider/tos.py index 98fa0d7e..a42c4489 100644 --- a/src/provider/tos.py +++ b/src/provider/tos.py @@ -87,6 +87,16 @@ def as_dict(self) -> dict[str, str]: "标准 OpenAI 兼容端点,端点由部署者自行配置(官方 API 或自建网关)," "凭证是本部署自己持有的 API key", basis="运营判断"), + "copilot": TosRisk( + "gray", + "复用 GitHub Copilot 个人订阅:GitHub token 换短期 Copilot token 后调" + "官方补全网关,并伪装 VS Code 插件头;条款明确禁止转售与共享订阅席位", + basis="PROPOSAL §8.2 / 运营判断"), + "qwen_code": TosRisk( + "gray", + "Qwen Code 免费 OAuth 档:设备码换 token 后直调 chat.qwen.ai 私有会话" + "接口;条款禁止自动化与共享,风控按账号 + IP", + basis="PROPOSAL §8.2 / 运营判断"), "lingxi": TosRisk( "gray", "复用 WPS 灵犀桌面/网页登录态(wps_sid Cookie)调 agent-runtime 私有" diff --git a/src/runtime_settings.py b/src/runtime_settings.py index 4f15e40e..5c051545 100644 --- a/src/runtime_settings.py +++ b/src/runtime_settings.py @@ -258,6 +258,12 @@ def env_name(self) -> str: "灵犀真实账号渠道专用节流(0 关闭,默认)。上游按 run 计费," "run 缓存与单飞已避免重复计费;与其余渠道各自独立,不共享。", minimum=0.0, group="chat_throttle"), + HotSetting("copilot_chat_min_interval", float, "Copilot 聊天最小间隔(秒)", + "Copilot 真实订阅渠道专用节流(0 关闭,默认)。与其余渠道各自独立," + "不共享。", minimum=0.0, group="chat_throttle"), + HotSetting("qwen_code_chat_min_interval", float, "Qwen Code 聊天最小间隔(秒)", + "Qwen Code 免费 OAuth 档专用节流(0 关闭,默认)。风控按账号 + IP," + "与其余渠道各自独立,不共享。", minimum=0.0, group="chat_throttle"), HotSetting("raccoon_max_concurrency", int, "小浣熊每账号并发上限", "上游按请求频率限流(实测 5 并发放行、第 6 个 429 " "user_model_rate_limited)。默认 2 留余量;0 关闭上限。", @@ -1064,6 +1070,14 @@ def raccoon_chat_min_interval(self) -> float: def lingxi_chat_min_interval(self) -> float: return float(self.get("lingxi_chat_min_interval")) + @property + def copilot_chat_min_interval(self) -> float: + return float(self.get("copilot_chat_min_interval")) + + @property + def qwen_code_chat_min_interval(self) -> float: + return float(self.get("qwen_code_chat_min_interval")) + @property def raccoon_max_concurrency(self) -> int: return int(self.get("raccoon_max_concurrency")) diff --git a/tests/config/test_copilot_qwen_wiring.py b/tests/config/test_copilot_qwen_wiring.py new file mode 100644 index 00000000..1cc551be --- /dev/null +++ b/tests/config/test_copilot_qwen_wiring.py @@ -0,0 +1,153 @@ +"""Copilot / Qwen Code 接线:Settings、白名单、热更节流、注册表、ToS、登录轨。 + +两个渠道同批落地,接线点逐条对齐(漏一处就是「渠道存在但选不到」)。 +""" + +from __future__ import annotations + +import httpx + +from src.config import ( + validate_copilot_endpoint_allowed, + validate_qwen_code_endpoint_allowed, +) +from src.engine.model_resolver import KNOWN_PROVIDERS, ProviderCatalog +from src.provider.copilot import CopilotProvider +from src.provider.copilot.client import CopilotClient +from src.provider.copilot.oauth import CopilotOAuth +from src.provider.login_identity import ( + copilot_login_identities, + copilot_login_identity, + qwen_code_login_identities, + qwen_code_login_identity, +) +from src.provider.qwen_code import QwenCodeProvider +from src.provider.qwen_code.client import QwenClient +from src.provider.qwen_code.oauth import QwenCodeOAuth +from src.provider.tos import tos_for +from src.runtime_settings import HOT_BY_KEY, RuntimeSettings +from tests.helpers.auth import settings_with as _settings +from tests.helpers.stores import MemoryStore as _MemoryStore + + +def test_endpoint_defaults_and_allowed_parsing(): + settings = _settings() + assert settings.copilot_api_endpoint == "https://api.githubcopilot.com" + assert settings.copilot_github_endpoint == "https://api.github.com" + assert settings.copilot_allowed == ("https://api.githubcopilot.com", + "https://api.github.com") + assert settings.qwen_code_api_endpoint == "https://chat.qwen.ai" + assert settings.qwen_code_allowed == ("https://chat.qwen.ai",) + blank = _settings(copilot_allowed_endpoints=" https://a.example.com/ , , ", + qwen_code_allowed_endpoints=" https://b.example.com/ ") + assert blank.copilot_allowed == ("https://a.example.com",) + assert blank.qwen_code_allowed == ("https://b.example.com",) + + +def test_endpoint_whitelists_reject_foreign_hosts(): + settings = _settings() + assert validate_copilot_endpoint_allowed("https://api.github.com/", settings) + assert not validate_copilot_endpoint_allowed("https://evil.example.com", settings) + assert validate_qwen_code_endpoint_allowed("https://chat.qwen.ai", settings) + assert not validate_qwen_code_endpoint_allowed("https://evil.example.com", settings) + + +def test_chat_min_intervals_are_hot(): + for key in ("copilot_chat_min_interval", "qwen_code_chat_min_interval"): + assert key in HOT_BY_KEY + runtime = RuntimeSettings(_settings(), _MemoryStore()) + assert runtime.copilot_chat_min_interval == 0 + assert runtime.qwen_code_chat_min_interval == 0 + runtime.set("copilot_chat_min_interval", 3) + runtime.set("qwen_code_chat_min_interval", 4) + assert runtime.copilot_chat_min_interval == 3 + assert runtime.qwen_code_chat_min_interval == 4 + + +def test_registered_in_known_providers_and_tos(): + assert "copilot" in KNOWN_PROVIDERS + assert "qwen_code" in KNOWN_PROVIDERS + # 默认渠道目录里就能选中(`@copilot` 后缀可解析) + catalog = ProviderCatalog() + assert "copilot" in catalog and "qwen_code" in catalog + # ToS 灰区登记(PROPOSAL §8.2 的高/中风险) + assert tos_for("copilot").level == "gray" + assert tos_for("qwen_code").level == "gray" + assert "转售" in tos_for("copilot").reason + + +def test_login_identity_prefers_account_and_hashes_token(): + assert copilot_login_identity({"github_token": "gho", "username": "octocat"}) == ( + "octocat") + hashed = copilot_login_identity({"github_token": "gho"}) + assert hashed.startswith("gh-") and "gho" not in hashed + assert copilot_login_identities({"github_token": "gho", "username": "octocat"}) == { + "octocat", hashed} + assert copilot_login_identity({}) == "" + assert copilot_login_identities({}) == frozenset() + + assert qwen_code_login_identity({"access_token": "at", "account": "a@b.c"}) == "a@b.c" + qwen_hash = qwen_code_login_identity({"access_token": "at"}) + assert qwen_hash.startswith("qw-") and "at" not in qwen_hash + assert qwen_code_login_identities({"access_token": "at", "account": "a@b.c"}) == { + "a@b.c", qwen_hash} + assert qwen_code_login_identity({}) == "" + assert qwen_code_login_identities({}) == frozenset() + + +def test_provider_facades_are_registered_in_default_registry(): + """默认装配(生产路径)里两条渠道都能被选到,且 id 与 KNOWN_PROVIDERS 一致。""" + from src.main import _copilot_endpoints, _qwen_code_endpoint + + settings = _settings() + assert _copilot_endpoints(settings) == ("https://api.githubcopilot.com", + "https://api.github.com") + assert _qwen_code_endpoint(settings) == "https://chat.qwen.ai" + assert CopilotProvider().id == "copilot" + assert QwenCodeProvider().id == "qwen_code" + + +def test_upstream_auth_registers_poll_tracks(): + from src.main import _upstream_auth + + registry = { + "copilot": CopilotProvider(client=CopilotClient(host="https://copilot.test", + github_host="https://gh.test")), + "qwen_code": QwenCodeProvider(client=QwenClient(host="https://qwen.test")), + } + flows = _upstream_auth(registry, _settings()) + assert isinstance(flows["copilot"], CopilotOAuth) + assert isinstance(flows["qwen_code"], QwenCodeOAuth) + # Copilot 登录轨复用 provider 的客户端换短期 token(同一份连接池与代理) + assert flows["copilot"]._tokens is registry["copilot"].client + assert flows["qwen_code"].host == "https://qwen.test" + + +def test_upstream_auth_uses_configured_client_id(): + from src.main import _upstream_auth + + registry = {"copilot": CopilotProvider(client=CopilotClient())} + flows = _upstream_auth(registry, _settings(copilot_github_client_id="Iv1.custom")) + assert flows["copilot"].client_id == "Iv1.custom" + # 未配置(空串)回落官方默认值 + flows = _upstream_auth(registry, _settings(copilot_github_client_id="")) + assert flows["copilot"].client_id.startswith("Iv1.") + + +def test_registry_entry_instantiates_with_settings_endpoints(): + """装配期不得因为端点解析抛错(白名单默认值必须自洽)。""" + from src.main import _copilot_endpoints, _qwen_code_endpoint + + settings = _settings() + host, github = _copilot_endpoints(settings) + client = CopilotClient(host=host, github_host=github) + assert client.host == host and client.github_host == github + assert QwenClient(host=_qwen_code_endpoint(settings)).host == "https://chat.qwen.ai" + + +async def test_copilot_oauth_closure_releases_pools(): + """登录轨的 aclose 同时释放自己的连接池与被复用的 token 客户端。""" + oauth = CopilotOAuth(client=httpx.AsyncClient( + transport=httpx.MockTransport(lambda request: httpx.Response(200)), timeout=None)) + await oauth.aclose() + assert oauth._client.is_closed diff --git a/tests/provider/copilot/__init__.py b/tests/provider/copilot/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/provider/copilot/_support.py b/tests/provider/copilot/_support.py new file mode 100644 index 00000000..b1f9fce0 --- /dev/null +++ b/tests/provider/copilot/_support.py @@ -0,0 +1,21 @@ +"""Copilot 测试共享装配助手。""" + +from __future__ import annotations + +import httpx + +from src.provider.copilot.client import CopilotClient + +__all__ = ["client"] + + +def client(handler, **kw) -> CopilotClient: + """用 `handler` 造 CopilotClient(默认测试主机,便于按端点常量断言)。""" + kw.setdefault("host", "https://copilot.test") + kw.setdefault("github_host", "https://github.test") + transport = httpx.MockTransport(handler) + return CopilotClient( + stream_client=httpx.AsyncClient(transport=transport, timeout=None), + short_client=httpx.AsyncClient(transport=transport, timeout=None), + **kw, + ) diff --git a/tests/provider/copilot/test_client.py b/tests/provider/copilot/test_client.py new file mode 100644 index 00000000..62e39921 --- /dev/null +++ b/tests/provider/copilot/test_client.py @@ -0,0 +1,323 @@ +"""Copilot 客户端:短期 token 预刷新、聊天流、模型表、额度与分类。""" + +from __future__ import annotations + +import json + +import httpx + +from src.provider.base import ErrKind, EventKind +from src.provider.copilot import events as copilot_events +from src.provider.copilot.client import ( + EP_CHAT, + EP_MODELS, + EP_TOKEN, + EP_USER, + CopilotClient, + UpstreamHTTPError, + _model_from_item, + _num, + _premium_snapshot, + chat_headers, + github_headers, + prepare_body, +) +from src.provider.copilot.credential import CopilotCredential +from tests.helpers.http import chunk_payload as chunk +from tests.helpers.http import sse_text_done as _sse +from tests.provider.copilot._support import client as _client + + +def test_prepare_body_forces_stream_and_deepcopies_messages(): + messages = [{"role": "developer", "content": "hi"}] + body = prepare_body({"messages": messages, "stream": False, "temperature": 0.5}, + "gpt-4o") + assert body["stream"] is True + assert body["model"] == "gpt-4o" + assert body["temperature"] == 0.5 + # developer → system 归一(上游只认 system) + assert body["messages"][0]["role"] == "system" + body["messages"][0]["content"] = "changed" + assert messages[0]["content"] == "hi" + + +def test_headers_carry_token_and_plugin_disguise(): + chat = chat_headers("cp") + assert chat["Authorization"] == "Bearer cp" + assert chat["Copilot-Integration-Id"] + assert chat["Editor-Version"] + gh = github_headers("gho") + assert gh["Authorization"] == "Bearer gho" + assert gh["Accept"] == "application/json" + + +async def test_exchange_returns_credential_with_expiry(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_TOKEN + assert request.headers["authorization"] == "Bearer gho" + return httpx.Response(200, json={"token": "cp1", "expires_at": 1_700_000_000}) + + credential = await _client(handler).exchange("gho", username="octocat") + assert credential.copilot_token == "cp1" + assert credential.expires_at == 1_700_000_000 + assert credential.username == "octocat" + + +async def test_exchange_rejects_malformed_responses(): + for payload, message in ( + (["not", "an", "object"], "not an object"), + ({"expires_at": 1}, "missing token"), + ): + def handler(request: httpx.Request, payload=payload) -> httpx.Response: + return httpx.Response(200, json=payload) + + try: + await _client(handler).exchange("gho") + except Exception as error: # noqa: BLE001 - 断言类型与文案 + assert "UpstreamProtocolViolation" in type(error).__name__ + assert message in str(error) + else: # pragma: no cover - 失败即说明没抛 + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_exchange_propagates_http_error_with_classification(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(401, json={"message": "bad credentials"}) + + try: + await _client(handler).exchange("gho") + except UpstreamHTTPError as error: + assert error.status == 401 + assert error.kind() is ErrKind.DEAD + else: # pragma: no cover + raise AssertionError("expected UpstreamHTTPError") + + +async def test_ensure_token_reuses_valid_and_refreshes_expired(): + calls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.path) + return httpx.Response(200, json={"token": "fresh", "expires_at": 9_999_999_999}) + + client = _client(handler) + valid = CopilotCredential(github_token="gho", copilot_token="cp", + expires_at=9_999_999_999) + assert await client.ensure_token(valid) is valid + assert calls == [] + + expired = CopilotCredential(github_token="gho", copilot_token="cp", expires_at=1) + refreshed = await client.ensure_token(expired) + assert refreshed.copilot_token == "fresh" + assert calls == [EP_TOKEN] + + # 没有 GitHub token:换不出来,原样返回(上游 401 → DEAD) + manual = CopilotCredential(copilot_token="cp", expires_at=1) + assert await client.ensure_token(manual) is manual + + +async def test_stream_chat_yields_events_and_sends_headers(): + seen: dict[str, str] = {} + + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_CHAT + seen["auth"] = request.headers["authorization"] + body = json.loads(request.content) + assert body["stream"] is True + return httpx.Response(200, text=_sse( + chunk({"content": "hi"}), + chunk({}, finish="stop", usage={"prompt_tokens": 3, "completion_tokens": 1}))) + + credential = CopilotCredential(github_token="gho", copilot_token="cp", + expires_at=9_999_999_999) + events = [event async for event in _client(handler).stream_chat( + credential, {"messages": [{"role": "user", "content": "hi"}]}, "gpt-4o")] + assert seen["auth"] == "Bearer cp" + assert [e.kind for e in events] == [EventKind.CONTENT, EventKind.USAGE, + EventKind.FINISH] + assert events[0].content == "hi" + + +async def test_stream_chat_retries_once_after_401_with_new_token(): + tokens: list[str] = [] + refreshed: list[bool] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_TOKEN: + refreshed.append(True) + return httpx.Response(200, json={"token": "cp2", "expires_at": 9_999_999_999}) + tokens.append(request.headers["authorization"]) + if len(tokens) == 1: + return httpx.Response(401, json={"error": "expired"}) + return httpx.Response(200, text=_sse(chunk({"content": "ok"}))) + + credential = CopilotCredential(github_token="gho", copilot_token="cp1", + expires_at=9_999_999_999) + events = [event async for event in _client(handler).stream_chat( + credential, {"messages": []}, "gpt-4o")] + assert refreshed == [True] + assert tokens == ["Bearer cp1", "Bearer cp2"] + assert events[0].content == "ok" + + +async def test_stream_chat_does_not_retry_without_github_token(): + calls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.path) + return httpx.Response(401, json={"error": "expired"}) + + credential = CopilotCredential(copilot_token="cp", expires_at=9_999_999_999) + try: + [event async for event in _client(handler).stream_chat( + credential, {"messages": []}, "gpt-4o")] + except UpstreamHTTPError as error: + assert error.status == 401 + else: # pragma: no cover + raise AssertionError("expected UpstreamHTTPError") + assert calls == [EP_CHAT] + + +async def test_stream_chat_gives_up_after_second_401(): + calls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.path) + if request.url.path == EP_TOKEN: + return httpx.Response(200, json={"token": "cp2", "expires_at": 9_999_999_999}) + return httpx.Response(401, json={"error": "expired"}) + + credential = CopilotCredential(github_token="gho", copilot_token="cp1", + expires_at=9_999_999_999) + try: + [event async for event in _client(handler).stream_chat( + credential, {"messages": []}, "gpt-4o")] + except UpstreamHTTPError as error: + assert error.status == 401 + else: # pragma: no cover + raise AssertionError("expected UpstreamHTTPError") + assert calls == [EP_CHAT, EP_TOKEN, EP_CHAT] + + +async def test_fetch_models_maps_capabilities(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_MODELS + return httpx.Response(200, json={"data": [ + {"id": "gpt-4o", "name": "GPT-4o", + "capabilities": {"supports_vision": True, "supports_tool_calls": True}, + "limits": {"max_context_window_tokens": 128000, + "max_output_tokens": 4096}}, + {"id": "", "name": "skip"}, + "junk", + {"id": "claude"}, + ]}) + + models = await _client(handler).fetch_models("cp") + assert [m.id for m in models] == ["gpt-4o", "claude"] + assert models[0].max_input_tokens == 128000 + assert models[0].supports_images is True + assert models[1].supports_images is None + + +async def test_fetch_models_rejects_missing_data_list(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"nope": 1}) + + try: + await _client(handler).fetch_models("cp") + except Exception as error: # noqa: BLE001 + assert "missing data list" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_probe_quota_reads_premium_snapshot(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_USER + return httpx.Response(200, json={"quota_snapshots": { + "premium_interactions": {"remaining": 12, "entitlement": 300}}}) + + quota = await _client(handler).probe_quota(CopilotCredential(github_token="gho")) + assert quota.remaining == 12.0 + assert quota.total == 300.0 + assert quota.probe_failed is False + + +async def test_probe_quota_is_unknown_when_snapshot_missing_or_broken(): + for payload in ({"quota_snapshots": {"chat": {"remaining": 1}}}, + {"quota_snapshots": "junk"}, []): + def handler(request: httpx.Request, payload=payload) -> httpx.Response: + return httpx.Response(200, json=payload) + + quota = await _client(handler).probe_quota( + CopilotCredential(github_token="gho")) + assert quota.probe_failed is True + assert quota.remaining is None + + +async def test_probe_quota_degrades_on_http_error_and_missing_token(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(500, text="boom") + + quota = await _client(handler).probe_quota(CopilotCredential(github_token="gho")) + assert quota.probe_failed is True + # 手工只贴了短期票:读不到额度面(判未知而非耗尽) + quota = await _client(handler).probe_quota(CopilotCredential(copilot_token="cp")) + assert quota.probe_failed is True + + +async def test_probe_quota_degrades_on_protocol_violation(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, text="not json") + + quota = await _client(handler).probe_quota(CopilotCredential(github_token="gho")) + assert quota.probe_failed is True + + +def test_classify_status_table(): + assert copilot_events.classify_status(401) is ErrKind.DEAD + assert copilot_events.classify_status(403) is ErrKind.DEAD + assert copilot_events.classify_status(402) is ErrKind.CREDIT + assert copilot_events.classify_status(400) is ErrKind.INVALID + assert copilot_events.classify_status(404) is ErrKind.INVALID + assert copilot_events.classify_status(422) is ErrKind.INVALID + assert copilot_events.classify_status(429) is ErrKind.SOFT + assert copilot_events.classify_status(500) is ErrKind.OTHER + assert copilot_events.classify_status(418) is ErrKind.OTHER + + +def test_error_event_keeps_code_and_message(): + event = copilot_events.error_event({"code": 7, "message": "denied"}) + assert event.kind is EventKind.ERROR + assert event.error_code == 7 + assert event.error_message == "denied" + # 非整数码(含 bool)留空;缺 message 也留空串 + assert copilot_events.error_event({"code": True}).error_code is None + assert copilot_events.error_event({}).error_message == "" + + +def test_parse_events_flags_error_envelope(): + from tests.helpers.http import sse_frame + + events = copilot_events.parse_events( + sse_frame({"error": {"code": 1, "message": "nope"}})) + assert events[0].kind is EventKind.ERROR + assert events[0].error_message == "nope" + + +def test_model_and_number_helpers(): + model = _model_from_item({"id": "x", "name": "X", "limits": "junk", + "capabilities": {"supports_vision": "yes"}}, "x") + assert model.name == "X" + assert model.max_input_tokens is None + assert model.supports_images is None + assert _num(True) is None + assert _num("3") is None + assert _num(3) == 3.0 + assert _premium_snapshot(None) == {} + + +def test_default_client_hosts(): + client = CopilotClient() + assert client.host == "https://api.githubcopilot.com" + assert client.github_host == "https://api.github.com" diff --git a/tests/provider/copilot/test_credential.py b/tests/provider/copilot/test_credential.py new file mode 100644 index 00000000..776e5b46 --- /dev/null +++ b/tests/provider/copilot/test_credential.py @@ -0,0 +1,67 @@ +"""Copilot 凭证归一:导入、落库形状、到期判定与稳定身份。""" + +from __future__ import annotations + +import pytest + +from src.provider.base import UpstreamProtocolViolation +from src.provider.copilot.credential import CopilotCredential + + +def test_from_dict_reads_aliases_and_defaults(): + credential = CopilotCredential.from_dict( + {"token": "gho_a", "bearer_token": "cp_b", "expires_at": 100, "login": "octocat"}) + assert credential.github_token == "gho_a" + assert credential.copilot_token == "cp_b" + assert credential.expires_at == 100 + assert credential.username == "octocat" + # 非对象 / 缺失一律空凭证,不抛 + assert CopilotCredential.from_dict(None).github_token == "" + # 布尔是 int 的子类:`true` 不能被当成 epoch 1 + assert CopilotCredential.from_dict({"expires_at": True}).expires_at == 0 + + +def test_from_import_rejects_missing_or_bad_shape(): + with pytest.raises(UpstreamProtocolViolation, match="not an object"): + CopilotCredential.from_import("gho_x") + with pytest.raises(UpstreamProtocolViolation, match="missing github_token"): + CopilotCredential.from_import({"copilot_token": "x"}) + + +def test_to_dict_keeps_only_non_empty_fields(): + full = CopilotCredential(github_token="gho", copilot_token="cp", expires_at=5, + username="octocat") + assert full.to_dict() == {"github_token": "gho", "copilot_token": "cp", + "expires_at": 5, "username": "octocat"} + # 空串不回写(界面会显示空 token 行) + assert CopilotCredential(github_token="gho").to_dict() == {"github_token": "gho"} + + +def test_expired_and_needs_refresh(): + credential = CopilotCredential(github_token="gho", copilot_token="cp", + expires_at=1_000) + assert credential.expired(now=100) is False + # 提前量内视为过期(提前 300s 换) + assert credential.expired(now=800) is True + assert credential.needs_refresh(now=800) is True + # 没有短期票 = 该换 + assert CopilotCredential(github_token="gho").expired(now=0) is True + # 没有 GitHub token 就无法自愈:不报「该刷新」,让上游 401 判 DEAD + assert CopilotCredential(copilot_token="cp", expires_at=10).needs_refresh( + now=10) is False + + +def test_identity_prefers_username_and_never_leaks_token(): + assert CopilotCredential(github_token="gho", username="octocat").identity() == "octocat" + hashed = CopilotCredential(github_token="gho").identity() + assert hashed.startswith("gh-") + assert "gho" not in hashed + assert CopilotCredential(github_token="").identity() == "" + + +def test_sanitized_strips_header_breaking_bytes(): + credential = CopilotCredential(github_token="gho\n_x", copilot_token="cp\r", + username="octo\x00cat").sanitized() + assert credential.github_token == "gho_x" + assert credential.copilot_token == "cp" + assert credential.username == "octocat" diff --git a/tests/provider/copilot/test_oauth.py b/tests/provider/copilot/test_oauth.py new file mode 100644 index 00000000..0323292c --- /dev/null +++ b/tests/provider/copilot/test_oauth.py @@ -0,0 +1,282 @@ +"""Copilot 设备码登录轨:待授权 / 降频 / 结束 / 成功 与身份补全。""" + +from __future__ import annotations + +import httpx + +from src.provider.base import AuthFlow, UpstreamProtocolViolation +from src.provider.copilot.oauth import ( + DEFAULT_CLIENT_ID, + EP_ACCESS_TOKEN, + EP_DEVICE_CODE, + CopilotOAuth, +) +from tests.provider.copilot._support import client as _token_client + + +def _oauth(handler, **kw) -> CopilotOAuth: + transport = httpx.MockTransport(handler) + return CopilotOAuth( + client=httpx.AsyncClient(transport=transport, timeout=None), + token_client=_token_client(handler), **kw) + + +def _device_code_response(**overrides) -> httpx.Response: + payload = {"device_code": "dc", "user_code": "ABCD-1234", + "verification_uri": "https://github.com/login/device", "interval": 5} + payload.update(overrides) + return httpx.Response(200, json=payload) + + +async def test_start_registers_pending_and_hides_device_code(): + seen: dict[str, str] = {} + + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_DEVICE_CODE + seen.update(dict(request.headers)) + body = request.content.decode() + assert "client_id=" in body and "scope=" in body + return _device_code_response() + + session = await _oauth(handler).start("admin") + assert session.flow is AuthFlow.POLL + assert session.auth_url == "https://github.com/login/device?user_code=ABCD-1234" + assert session.interval == 5 + assert session.callback_url is None + # 本地 reservation 不是上游 device_code + assert session.state != "dc" + assert seen["accept"] == "application/json" + + +async def test_start_rejects_incomplete_or_failed_responses(): + for response, message in ( + (httpx.Response(500, json={}), "rejected"), + (httpx.Response(200, text="not json"), "not JSON"), + (httpx.Response(200, json={"device_code": "dc"}), "incomplete"), + ): + def handler(request: httpx.Request, response=response) -> httpx.Response: + return response + + try: + await _oauth(handler).start("admin") + except UpstreamProtocolViolation as error: + assert message in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_start_defaults_interval_when_absent_or_invalid(): + for interval in (None, "5", True, 0): + def handler(request: httpx.Request, interval=interval) -> httpx.Response: + body = {"device_code": "dc", "user_code": "U", + "verification_uri": "https://github.com/login/device"} + if interval is not None: + body["interval"] = interval + return httpx.Response(200, json=body) + + session = await _oauth(handler).start("admin") + assert session.interval == 5 + + +async def test_poll_pending_then_success_builds_credential(): + token_calls: list[int] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + if request.url.path == EP_ACCESS_TOKEN: + token_calls.append(1) + if len(token_calls) == 1: + return httpx.Response(200, json={"error": "authorization_pending"}) + return httpx.Response(200, json={"access_token": "gho_1"}) + if request.url.path == "/copilot_internal/v2/token": + return httpx.Response(200, json={"token": "cp1", "expires_at": 1_800_000_000}) + if request.url.path == "/user": + return httpx.Response(200, json={"login": "octocat"}) + raise AssertionError(f"unexpected path {request.url.path}") + + oauth = _oauth(handler) + session = await oauth.start("admin") + assert await oauth.poll(session.state, "admin") is None # 还在等 + result = await oauth.poll(session.state, "admin") + assert result is not None + assert result.credential_data["github_token"] == "gho_1" + assert result.credential_data["copilot_token"] == "cp1" + assert result.credential_data["username"] == "octocat" + assert result.nickname == "octocat" + # state 已消费,不能重放 + try: + await oauth.poll(session.state, "admin") + except UpstreamProtocolViolation as error: + assert "unknown or consumed" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_poll_unknown_state_is_rejected(): + oauth = _oauth(lambda request: httpx.Response(200, json={})) + try: + await oauth.poll("nope", "admin") + except UpstreamProtocolViolation as error: + assert "unknown or consumed" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_poll_slow_down_extends_interval_and_stays_pending(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_ACCESS_TOKEN: + return httpx.Response(200, json={"error": "slow_down"}) + return _device_code_response() + + oauth = _oauth(handler) + session = await oauth.start("admin") + pending = oauth.store.payload(session.state, "admin") + assert pending.interval == 5 + assert await oauth.poll(session.state, "admin") is None + assert pending.interval == 10 + # 反复降频封顶 MAX_INTERVAL + for _ in range(10): + await oauth.poll(session.state, "admin") + assert pending.interval == 30 + + +async def test_poll_terminal_error_ends_login(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_ACCESS_TOKEN: + return httpx.Response(200, json={"error": "access_denied"}) + return _device_code_response() + + oauth = _oauth(handler) + session = await oauth.start("admin") + try: + await oauth.poll(session.state, "admin") + except UpstreamProtocolViolation as error: + assert "access_denied" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + # 已消费:不再无限转圈 + assert oauth.store.payload(session.state, "admin") is None + + +async def test_poll_rejects_non_object_token_response(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_ACCESS_TOKEN: + return httpx.Response(200, json=["nope"]) + return _device_code_response() + + oauth = _oauth(handler) + session = await oauth.start("admin") + try: + await oauth.poll(session.state, "admin") + except UpstreamProtocolViolation as error: + assert "not an object" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_poll_returns_pending_on_empty_or_form_encoded_body(): + """GitHub 默认回表单编码:不是 JSON 时按「还没授权」处理,不能报协议损坏。""" + bodies = (httpx.Response(200, text=""), + httpx.Response(200, text="access_token=&token_type=bearer", + headers={"content-type": "application/x-www-form-urlencoded"})) + for response in bodies: + def handler(request: httpx.Request, response=response) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + return response + + oauth = _oauth(handler) + session = await oauth.start("admin") + assert await oauth.poll(session.state, "admin") is None + + +async def test_poll_survives_identity_lookup_failures(): + """补用户名失败(网络 / 非 200 / 非 JSON)不算登录失败,昵称回落。""" + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + if request.url.path == EP_ACCESS_TOKEN: + return httpx.Response(200, json={"access_token": "gho_1"}) + if request.url.path == "/copilot_internal/v2/token": + return httpx.Response(200, json={"token": "cp1", "expires_at": 9_999_999_999}) + return httpx.Response(403, text="nope") + + oauth = _oauth(handler) + session = await oauth.start("admin") + result = await oauth.poll(session.state, "admin") + assert result is not None + assert result.nickname == "GitHub Copilot" + assert "username" not in result.credential_data + + +async def test_identity_lookup_handles_transport_error_and_non_object(): + oauth = _oauth(lambda request: httpx.Response(200, json={})) + + def boom(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("boom", request=request) + + transport = httpx.MockTransport(boom) + oauth._client = httpx.AsyncClient(transport=transport, timeout=None) + assert await oauth._fetch_login("gho") == "" + + oauth._client = httpx.AsyncClient( + transport=httpx.MockTransport(lambda request: httpx.Response(200, json=["x"])), + timeout=None) + assert await oauth._fetch_login("gho") == "" + + +async def test_identity_lookup_rejects_non_json_body(): + oauth = _oauth(lambda request: httpx.Response(200, text="not json")) + assert await oauth._fetch_login("gho") == "" + + +async def test_default_client_id_and_aclose(): + oauth = CopilotOAuth() + assert oauth.client_id == DEFAULT_CLIENT_ID + # 未建过连接池时 aclose 不抛 + await oauth.aclose() + + +async def test_lazy_pool_is_built_and_closed(): + """未注入 client 时按需建池,aclose 后释放(lifespan 关闭阶段会调)。""" + oauth = CopilotOAuth() + pool = oauth._http + assert pool is oauth._http # 复用同一份池 + await oauth.aclose() + assert pool.is_closed + + +async def test_poll_missing_access_token_stays_pending(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + return httpx.Response(200, json={"token_type": "bearer"}) + + oauth = _oauth(handler) + session = await oauth.start("admin") + assert await oauth.poll(session.state, "admin") is None + + +async def test_poll_concurrent_consume_is_rejected(): + """两次轮询并发拿到同一 state:后完成的那次必须失败(不能双落库)。""" + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + if request.url.path == EP_ACCESS_TOKEN: + return httpx.Response(200, json={"access_token": "gho_1"}) + if request.url.path == "/copilot_internal/v2/token": + return httpx.Response(200, json={"token": "cp1", "expires_at": 9_999_999_999}) + return httpx.Response(200, json={"login": "octocat"}) + + oauth = _oauth(handler) + session = await oauth.start("admin") + original = oauth.store.consume + oauth.store.consume = lambda *args, **kwargs: False # 模拟已被别的轮询消费 + try: + await oauth.poll(session.state, "admin") + except UpstreamProtocolViolation as error: + assert "consumed concurrently" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + oauth.store.consume = original diff --git a/tests/provider/copilot/test_provider.py b/tests/provider/copilot/test_provider.py new file mode 100644 index 00000000..b3ba52dc --- /dev/null +++ b/tests/provider/copilot/test_provider.py @@ -0,0 +1,117 @@ +"""CopilotProvider 委托、预刷新、身份与装配默认值。""" + +from __future__ import annotations + +import httpx + +from src.provider.base import ErrKind, EventKind, Quota +from src.provider.copilot import CopilotProvider +from src.provider.copilot.client import COPILOT_HOST, EP_CHAT, EP_MODELS, EP_TOKEN +from src.provider.copilot.credential import CopilotCredential +from tests.helpers.http import chunk_payload as chunk +from tests.helpers.http import sse_text_done as _sse +from tests.provider.copilot._support import client as _client + + +def test_default_id_and_client_hosts(): + provider = CopilotProvider() + assert provider.id == "copilot" + assert provider.client.host == COPILOT_HOST + + +def test_import_credential_normalizes_shape(): + provider = CopilotProvider() + assert provider.import_credential({"github_token": "gho_x"}) == {"github_token": "gho_x"} + + +def test_credential_from_and_login_identity(): + provider = CopilotProvider() + credential = provider.credential_from({"github_token": "gho", "username": "octocat"}) + assert isinstance(credential, CopilotCredential) + assert provider.login_identity({"github_token": "gho", "username": "octocat"}) == ( + "octocat") + hashed = provider.login_identity({"github_token": "gho"}) + assert hashed.startswith("gh-") and "gho" not in hashed + + +def test_classify_delegates(): + provider = CopilotProvider() + assert provider.classify(429, b"") is ErrKind.SOFT + assert provider.classify(401, b"") is ErrKind.DEAD + + +async def test_refresh_exchanges_and_keeps_extra_fields(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_TOKEN + return httpx.Response(200, json={"token": "cp2", "expires_at": 1_800_000_000}) + + provider = CopilotProvider(client=_client(handler)) + data = {"github_token": "gho", "username": "octocat", "custom": "keep"} + refreshed = await provider.refresh(data) + assert refreshed["copilot_token"] == "cp2" + assert refreshed["expires_at"] == 1_800_000_000 + assert refreshed["custom"] == "keep" + + +async def test_refresh_without_github_token_is_noop(): + provider = CopilotProvider() + data = {"copilot_token": "cp"} + assert await provider.refresh(data) is data + + +async def test_probe_quota_delegates_and_guards_missing_token(): + provider = CopilotProvider() + quota = await provider.probe_quota({}) + assert isinstance(quota, Quota) + assert quota.probe_failed is True + + +async def test_list_models_requires_token(): + provider = CopilotProvider() + try: + await provider.list_models({}) + except Exception as error: # noqa: BLE001 + assert "missing token" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_list_models_refreshes_expired_token(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_TOKEN: + return httpx.Response(200, json={"token": "cp2", "expires_at": 9_999_999_999}) + assert request.url.path == EP_MODELS + assert request.headers["authorization"] == "Bearer cp2" + return httpx.Response(200, json={"data": [{"id": "gpt-4o"}]}) + + provider = CopilotProvider(client=_client(handler)) + models = await provider.list_models({"github_token": "gho", "copilot_token": "cp1", + "expires_at": 1}) + assert [m.id for m in models] == ["gpt-4o"] + + +async def test_stream_chat_requires_token(): + provider = CopilotProvider() + try: + [event async for event in provider.stream_chat({}, {"messages": []}, "gpt-4o")] + except Exception as error: # noqa: BLE001 + assert "missing token" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_stream_chat_delegates_with_pacer_bucket(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_CHAT + return httpx.Response(200, text=_sse(chunk({"content": "hi"}))) + + provider = CopilotProvider(client=_client(handler)) + events = [event async for event in provider.stream_chat( + {"github_token": "gho", "copilot_token": "cp", "expires_at": 9_999_999_999}, + {"messages": []}, "gpt-4o")] + assert events[0].kind is EventKind.CONTENT + + +async def test_aclose_releases_pool(): + provider = CopilotProvider(client=_client(lambda request: httpx.Response(200))) + await provider.aclose() diff --git a/tests/provider/qwen_code/__init__.py b/tests/provider/qwen_code/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/provider/qwen_code/_support.py b/tests/provider/qwen_code/_support.py new file mode 100644 index 00000000..f9f94858 --- /dev/null +++ b/tests/provider/qwen_code/_support.py @@ -0,0 +1,20 @@ +"""Qwen Code 测试共享装配助手。""" + +from __future__ import annotations + +import httpx + +from src.provider.qwen_code.client import QwenClient + +__all__ = ["client"] + + +def client(handler, **kw) -> QwenClient: + """用 `handler` 造 QwenClient(默认测试主机,便于按端点常量断言)。""" + kw.setdefault("host", "https://qwen.test") + transport = httpx.MockTransport(handler) + return QwenClient( + stream_client=httpx.AsyncClient(transport=transport, timeout=None), + short_client=httpx.AsyncClient(transport=transport, timeout=None), + **kw, + ) diff --git a/tests/provider/qwen_code/test_client.py b/tests/provider/qwen_code/test_client.py new file mode 100644 index 00000000..9acd528a --- /dev/null +++ b/tests/provider/qwen_code/test_client.py @@ -0,0 +1,281 @@ +"""Qwen Code 客户端:聊天流、OAuth 刷新(含废票)、模型表、额度与分类。""" + +from __future__ import annotations + +import json + +import httpx + +from src.provider.base import ErrKind, EventKind, UpstreamReloginRequired +from src.provider.qwen_code import events as qwen_events +from src.provider.qwen_code.client import ( + EP_CHAT, + EP_ME, + EP_MODELS, + EP_TOKEN, + QwenClient, + UpstreamHTTPError, + _credential_from_token, + _json_object, + _model_from_item, + _num, + chat_headers, + prepare_body, +) +from src.provider.qwen_code.credential import QwenCredential +from tests.helpers.http import chunk_payload as chunk +from tests.helpers.http import sse_text_done as _sse +from tests.provider.qwen_code._support import client as _client + + +def test_prepare_body_forces_stream_and_deepcopies_messages(): + messages = [{"role": "user", "content": "hi"}] + body = prepare_body({"messages": messages, "stream": False, "top_p": 0.9}, "qwen3") + assert body["stream"] is True + assert body["model"] == "qwen3" + assert body["top_p"] == 0.9 + body["messages"][0]["content"] = "changed" + assert messages[0]["content"] == "hi" + + +def test_chat_headers_are_bearer(): + headers = chat_headers("at") + assert headers["Authorization"] == "Bearer at" + assert headers["Accept"] == "text/event-stream" + + +def test_base_of_prefers_resource_url(): + client = QwenClient(host="https://qwen.test") + assert client.base_of(QwenCredential(access_token="at")) == "https://qwen.test" + assert client.base_of( + QwenCredential(access_token="at", resource_url="https://portal.qwen.ai")) == ( + "https://portal.qwen.ai") + + +async def test_stream_chat_yields_events(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_CHAT + assert request.headers["authorization"] == "Bearer at" + assert json.loads(request.content)["stream"] is True + return httpx.Response(200, text=_sse( + chunk({"content": "hi"}), + chunk({}, finish="stop", usage={"prompt_tokens": 2, "completion_tokens": 1}))) + + events = [event async for event in _client(handler).stream_chat( + QwenCredential(access_token="at"), {"messages": []}, "qwen3")] + assert [e.kind for e in events] == [EventKind.CONTENT, EventKind.USAGE, + EventKind.FINISH] + + +async def test_stream_chat_uses_resource_url_and_raises_on_http_error(): + seen: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(str(request.url)) + return httpx.Response(429, text="rate limited") + + try: + [event async for event in _client(handler).stream_chat( + QwenCredential(access_token="at", resource_url="https://portal.qwen.ai"), + {"messages": []}, "qwen3")] + except UpstreamHTTPError as error: + assert error.status == 429 + assert error.kind() is ErrKind.SOFT + else: # pragma: no cover + raise AssertionError("expected UpstreamHTTPError") + assert seen == ["https://portal.qwen.ai/api/v2/chat/completions"] + + +async def test_refresh_rotates_tokens_and_recomputes_expiry(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_TOKEN + body = json.loads(request.content) + assert body["grant_type"] == "refresh_token" + assert body["refresh_token"] == "rt1" + return httpx.Response(200, json={"access_token": "at2", "refresh_token": "rt2", + "expires_in": 3600}) + + refreshed = await _client(handler).refresh( + QwenCredential(access_token="at1", refresh_token="rt1", account="a@b.c")) + assert refreshed.access_token == "at2" + assert refreshed.refresh_token == "rt2" + assert refreshed.expires_at > 0 + # 账号身份不在刷新响应里,必须保留(否则合并键丢失) + assert refreshed.account == "a@b.c" + + +async def test_refresh_keeps_old_refresh_token_and_resource_url_when_absent(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"access_token": "at2"}) + + refreshed = await _client(handler).refresh(QwenCredential( + access_token="at1", refresh_token="rt1", resource_url="https://portal.qwen.ai")) + assert refreshed.refresh_token == "rt1" + assert refreshed.resource_url == "https://portal.qwen.ai" + # 上游没给 expires_in:不猜 TTL,留 0(未知) + assert refreshed.expires_at == 0 + + +async def test_refresh_flags_dead_refresh_token(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(400, json={"error": "invalid_grant"}) + + try: + await _client(handler).refresh(QwenCredential(access_token="at", + refresh_token="rt")) + except UpstreamReloginRequired: + pass + else: # pragma: no cover + raise AssertionError("expected UpstreamReloginRequired") + + +async def test_refresh_propagates_retryable_errors(): + for response in (httpx.Response(400, json={"error": "temporarily_unavailable"}), + httpx.Response(429, text="slow down")): + def handler(request: httpx.Request, response=response) -> httpx.Response: + return response + + try: + await _client(handler).refresh(QwenCredential(access_token="at", + refresh_token="rt")) + except UpstreamHTTPError as error: + assert error.status == response.status_code + else: # pragma: no cover + raise AssertionError("expected UpstreamHTTPError") + + +async def test_refresh_rejects_response_without_access_token(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"refresh_token": "rt2"}) + + try: + await _client(handler).refresh(QwenCredential(access_token="at", + refresh_token="rt")) + except Exception as error: # noqa: BLE001 + assert "missing access_token" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_fetch_models_maps_capabilities(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_MODELS + return httpx.Response(200, json={"data": [ + {"id": "qwen3-coder-plus", "name": "Qwen3 Coder Plus", + "supports_vision": True, "supports_tool_calls": True, + "limits": {"max_context_window_tokens": 1000000, + "max_output_tokens": 65536}}, + {"id": "", "name": "skip"}, + {"id": "qwen3-max"}, + ]}) + + models = await _client(handler).fetch_models("at", "https://portal.qwen.ai") + assert [m.id for m in models] == ["qwen3-coder-plus", "qwen3-max"] + assert models[0].max_input_tokens == 1000000 + assert models[0].supports_tool_call is True + assert models[1].supports_images is None + + +async def test_fetch_models_rejects_missing_data_list(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"nope": 1}) + + try: + await _client(handler).fetch_models("at") + except Exception as error: # noqa: BLE001 + assert "missing data list" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_probe_quota_reads_quota_block(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_ME + return httpx.Response(200, json={"quota": {"remaining": 8, "total": 100}}) + + quota = await _client(handler).probe_quota(QwenCredential(access_token="at")) + assert quota.remaining == 8.0 + assert quota.total == 100.0 + assert quota.probe_failed is False + + +async def test_probe_quota_is_unknown_without_quota_block(): + for payload in ({"quota": {"used": 1}}, {"quota": "junk"}, ["x"]): + def handler(request: httpx.Request, payload=payload) -> httpx.Response: + return httpx.Response(200, json=payload) + + quota = await _client(handler).probe_quota(QwenCredential(access_token="at")) + assert quota.probe_failed is True + + +async def test_probe_quota_degrades_on_http_error_and_bad_body(): + for response in (httpx.Response(500, text="boom"), httpx.Response(200, text="nope")): + def handler(request: httpx.Request, response=response) -> httpx.Response: + return response + + quota = await _client(handler).probe_quota(QwenCredential(access_token="at")) + assert quota.probe_failed is True + + +def test_classify_status_table(): + assert qwen_events.classify_status(401) is ErrKind.DEAD + assert qwen_events.classify_status(403) is ErrKind.DEAD + assert qwen_events.classify_status(402) is ErrKind.CREDIT + assert qwen_events.classify_status(400) is ErrKind.INVALID + assert qwen_events.classify_status(404) is ErrKind.INVALID + assert qwen_events.classify_status(422) is ErrKind.INVALID + assert qwen_events.classify_status(429) is ErrKind.SOFT + assert qwen_events.classify_status(503) is ErrKind.OTHER + + +def test_error_event_and_parse_events(): + from tests.helpers.http import sse_frame + + event = qwen_events.error_event({"code": 3, "message": "denied"}) + assert event.kind is EventKind.ERROR + assert event.error_code == 3 + assert qwen_events.error_event({"code": False}).error_code is None + assert qwen_events.error_event({}).error_message == "" + events = qwen_events.parse_events(sse_frame({"error": {"message": "nope"}})) + assert events[0].kind is EventKind.ERROR + + +def test_helpers_edge_cases(): + model = _model_from_item({"id": "x", "limits": "junk", "supports_vision": "yes"}, "x") + assert model.name == "" + assert model.max_input_tokens is None + assert model.supports_images is None + assert _num(True) is None + assert _num("3") is None + assert _num(3) == 3.0 + old = QwenCredential(access_token="at0", refresh_token="rt0", account="a@b.c") + # 非整数 expires_in 不猜 TTL + assert _credential_from_token({"expires_in": "3600"}, old, "at").expires_at == 0 + assert _credential_from_token({"expires_in": True}, old, "at").expires_at == 0 + rotated = _credential_from_token({"expires_in": 60, "refresh_token": "rt1"}, old, "at") + assert rotated.refresh_token == "rt1" and rotated.account == "a@b.c" + try: + _json_object(b"not json", "x") + except Exception as error: # noqa: BLE001 + assert "non-JSON" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + try: + _json_object(b"[1]", "x") + except Exception as error: # noqa: BLE001 + assert "not an object" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +def test_default_client_host(): + assert QwenClient().host == "https://chat.qwen.ai" + + +async def test_fetch_models_skips_non_string_ids(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"data": ["junk", {"id": 42}, + {"id": "qwen3-max"}]}) + + models = await _client(handler).fetch_models("at") + assert [m.id for m in models] == ["qwen3-max"] diff --git a/tests/provider/qwen_code/test_credential.py b/tests/provider/qwen_code/test_credential.py new file mode 100644 index 00000000..15ab9718 --- /dev/null +++ b/tests/provider/qwen_code/test_credential.py @@ -0,0 +1,68 @@ +"""Qwen Code 凭证归一:导入、落库形状、预刷新判定与稳定身份。""" + +from __future__ import annotations + +import pytest + +from src.provider.base import UpstreamProtocolViolation +from src.provider.qwen_code.credential import QwenCredential + + +def test_from_dict_reads_aliases_and_defaults(): + credential = QwenCredential.from_dict({ + "token": "at", "refresh_token": "rt", "expires_at": 100, + "resource_url": "https://portal.qwen.ai/", "email": "a@b.c"}) + assert credential.access_token == "at" + assert credential.refresh_token == "rt" + assert credential.expires_at == 100 + # resource_url 归一去掉尾斜杠(拼端点时不出现 `//api`) + assert credential.resource_url == "https://portal.qwen.ai" + assert credential.account == "a@b.c" + assert QwenCredential.from_dict(None).access_token == "" + assert QwenCredential.from_dict({"expires_at": False}).expires_at == 0 + + +def test_from_import_rejects_missing_or_bad_shape(): + with pytest.raises(UpstreamProtocolViolation, match="not an object"): + QwenCredential.from_import(["at"]) + with pytest.raises(UpstreamProtocolViolation, match="missing access_token"): + QwenCredential.from_import({"refresh_token": "rt"}) + + +def test_to_dict_keeps_only_non_empty_fields(): + full = QwenCredential(access_token="at", refresh_token="rt", expires_at=5, + resource_url="https://x", account="a@b.c") + assert full.to_dict() == {"access_token": "at", "refresh_token": "rt", + "expires_at": 5, "resource_url": "https://x", + "account": "a@b.c"} + assert QwenCredential(access_token="at").to_dict() == {"access_token": "at"} + + +def test_needs_refresh_requires_refresh_token_and_expiry(): + credential = QwenCredential(access_token="at", refresh_token="rt", expires_at=1_000) + assert credential.needs_refresh(now=100) is False + assert credential.needs_refresh(now=800) is True + # 没有 refresh token 或到期时间:判不了,不能每小时白跑一次刷新 + assert QwenCredential(access_token="at", expires_at=1).needs_refresh(now=10) is False + assert QwenCredential(access_token="at", refresh_token="rt").needs_refresh( + now=10) is False + + +def test_identity_prefers_account_and_hashes_tokens(): + assert QwenCredential(access_token="at", account="a@b.c").identity() == "a@b.c" + hashed = QwenCredential(access_token="at", refresh_token="rt").identity() + assert hashed.startswith("qw-") + assert hashed != "at" and "rt" not in hashed + # 只有 refresh token 时也用它(重新登录后 access token 会变) + assert QwenCredential(access_token="", refresh_token="rt").identity().startswith("qw-") + assert QwenCredential(access_token="").identity() == "" + + +def test_sanitized_strips_header_breaking_bytes(): + credential = QwenCredential(access_token="at\n_x", refresh_token="rt\r", + resource_url="https://x\x00", account="a@b.c\x01" + ).sanitized() + assert credential.access_token == "at_x" + assert credential.refresh_token == "rt" + assert credential.resource_url == "https://x" + assert credential.account == "a@b.c" diff --git a/tests/provider/qwen_code/test_oauth.py b/tests/provider/qwen_code/test_oauth.py new file mode 100644 index 00000000..dc78ba38 --- /dev/null +++ b/tests/provider/qwen_code/test_oauth.py @@ -0,0 +1,267 @@ +"""Qwen Code 设备码登录轨:待授权 / 降频 / 结束 / 成功 与账号补全。""" + +from __future__ import annotations + +import httpx + +from src.provider.base import AuthFlow, UpstreamProtocolViolation +from src.provider.qwen_code.client import EP_ME, EP_TOKEN +from src.provider.qwen_code.oauth import ( + EP_DEVICE_CODE, + MAX_INTERVAL, + QwenCodeOAuth, + _credential_from_token, +) + + +def _oauth(handler) -> QwenCodeOAuth: + return QwenCodeOAuth(host="https://qwen.test", + client=httpx.AsyncClient( + transport=httpx.MockTransport(handler), timeout=None)) + + +def _device_code_response(**overrides) -> httpx.Response: + payload = {"device_code": "dc", "user_code": "WXYZ-9876", + "verification_uri": "https://chat.qwen.ai/device", "interval": 5} + payload.update(overrides) + return httpx.Response(200, json=payload) + + +async def test_start_registers_pending_and_hides_device_code(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_DEVICE_CODE + return _device_code_response() + + session = await _oauth(handler).start("admin") + assert session.flow is AuthFlow.POLL + assert session.auth_url == "https://chat.qwen.ai/device?user_code=WXYZ-9876" + assert session.interval == 5 + assert session.state != "dc" + + +async def test_start_rejects_failed_or_incomplete_responses(): + for response, message in ( + (httpx.Response(500, json={}), "rejected"), + (httpx.Response(200, json=["x"]), "not an object"), + (httpx.Response(200, json={"device_code": "dc"}), "incomplete"), + ): + def handler(request: httpx.Request, response=response) -> httpx.Response: + return response + + try: + await _oauth(handler).start("admin") + except UpstreamProtocolViolation as error: + assert message in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_start_defaults_interval_when_absent_or_invalid(): + for interval in (None, "5", True, -1): + def handler(request: httpx.Request, interval=interval) -> httpx.Response: + body = {"device_code": "dc", "user_code": "U", + "verification_uri": "https://chat.qwen.ai/device"} + if interval is not None: + body["interval"] = interval + return httpx.Response(200, json=body) + + session = await _oauth(handler).start("admin") + assert session.interval == 5 + + +async def test_poll_pending_then_success_builds_credential(): + token_calls: list[int] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + if request.url.path == EP_TOKEN: + token_calls.append(1) + if len(token_calls) == 1: + return httpx.Response(200, json={"error": "authorization_pending"}) + return httpx.Response(200, json={"access_token": "at1", "refresh_token": "rt1", + "expires_in": 3600, + "resource_url": "https://portal.qwen.ai/", + "email": "a@b.c"}) + raise AssertionError(f"unexpected path {request.url.path}") + + oauth = _oauth(handler) + session = await oauth.start("admin") + assert await oauth.poll(session.state, "admin") is None + result = await oauth.poll(session.state, "admin") + assert result is not None + assert result.credential_data["access_token"] == "at1" + assert result.credential_data["refresh_token"] == "rt1" + assert result.credential_data["resource_url"] == "https://portal.qwen.ai" + assert result.credential_data["expires_at"] > 0 + assert result.nickname == "a@b.c" + try: + await oauth.poll(session.state, "admin") + except UpstreamProtocolViolation as error: + assert "unknown or consumed" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_poll_unknown_state_is_rejected(): + oauth = _oauth(lambda request: httpx.Response(200, json={})) + try: + await oauth.poll("nope", "admin") + except UpstreamProtocolViolation as error: + assert "unknown or consumed" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_poll_slow_down_extends_interval_and_stays_pending(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_TOKEN: + return httpx.Response(200, json={"error": "slow_down"}) + return _device_code_response() + + oauth = _oauth(handler) + session = await oauth.start("admin") + pending = oauth.store.payload(session.state, "admin") + assert await oauth.poll(session.state, "admin") is None + assert pending.interval == 10 + for _ in range(10): + await oauth.poll(session.state, "admin") + assert pending.interval == MAX_INTERVAL + + +async def test_poll_5xx_keeps_pending(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_TOKEN: + return httpx.Response(503, text="upstream down") + return _device_code_response() + + oauth = _oauth(handler) + session = await oauth.start("admin") + # 链路瞬态不是登录失败:保持 pending 让前端下一轮再试 + assert await oauth.poll(session.state, "admin") is None + assert oauth.store.payload(session.state, "admin") is not None + + +async def test_poll_terminal_error_ends_login(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_TOKEN: + return httpx.Response(200, json={"error": "expired_token"}) + return _device_code_response() + + oauth = _oauth(handler) + session = await oauth.start("admin") + try: + await oauth.poll(session.state, "admin") + except UpstreamProtocolViolation as error: + assert "expired_token" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + assert oauth.store.payload(session.state, "admin") is None + + +async def test_poll_rejects_non_object_token_response(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_TOKEN: + return httpx.Response(200, json=["nope"]) + return _device_code_response() + + oauth = _oauth(handler) + session = await oauth.start("admin") + try: + await oauth.poll(session.state, "admin") + except UpstreamProtocolViolation as error: + assert "not an object" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + +async def test_poll_probes_account_when_token_response_has_no_identity(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + if request.url.path == EP_TOKEN: + return httpx.Response(200, json={"access_token": "at1"}) + if request.url.path == EP_ME: + return httpx.Response(200, json={"email": "probe@b.c"}) + raise AssertionError(f"unexpected path {request.url.path}") + + oauth = _oauth(handler) + session = await oauth.start("admin") + result = await oauth.poll(session.state, "admin") + assert result is not None + assert result.credential_data["account"] == "probe@b.c" + assert result.nickname == "probe@b.c" + + +async def test_poll_survives_account_probe_failures(): + """补账号失败(非 200 / 非对象 / 传输错误)不算登录失败,昵称回落。""" + for response in (httpx.Response(404, text="nope"), httpx.Response(200, json=["x"])): + def handler(request: httpx.Request, response=response) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + if request.url.path == EP_TOKEN: + return httpx.Response(200, json={"access_token": "at1"}) + return response + + oauth = _oauth(handler) + session = await oauth.start("admin") + result = await oauth.poll(session.state, "admin") + assert result is not None + assert result.nickname == "Qwen Code" + assert "account" not in result.credential_data + + +async def test_account_probe_handles_transport_error(): + oauth = _oauth(lambda request: httpx.Response(200, json={})) + + def boom(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("boom", request=request) + + oauth._client = httpx.AsyncClient(transport=httpx.MockTransport(boom), timeout=None) + assert await oauth._probe_account(_credential_from_token({}, "at")) == "" + + +async def test_aclose_is_safe_without_pool(): + oauth = QwenCodeOAuth() + assert oauth.host == "https://chat.qwen.ai" + await oauth.aclose() + + +async def test_lazy_pool_is_built_and_closed(): + """未注入 client 时按需建池,aclose 后释放(lifespan 关闭阶段会调)。""" + oauth = QwenCodeOAuth() + pool = oauth._http + assert pool is oauth._http + await oauth.aclose() + assert pool.is_closed + + +async def test_poll_missing_access_token_stays_pending(): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + return httpx.Response(200, json={"token_type": "bearer"}) + + oauth = _oauth(handler) + session = await oauth.start("admin") + assert await oauth.poll(session.state, "admin") is None + + +async def test_poll_concurrent_consume_is_rejected(): + """两次轮询并发拿到同一 state:后完成的那次必须失败(不能双落库)。""" + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == EP_DEVICE_CODE: + return _device_code_response() + if request.url.path == EP_TOKEN: + return httpx.Response(200, json={"access_token": "at1", "email": "a@b.c"}) + raise AssertionError(f"unexpected path {request.url.path}") + + oauth = _oauth(handler) + session = await oauth.start("admin") + oauth.store.consume = lambda *args, **kwargs: False # 模拟已被别的轮询消费 + try: + await oauth.poll(session.state, "admin") + except UpstreamProtocolViolation as error: + assert "consumed concurrently" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") diff --git a/tests/provider/qwen_code/test_provider.py b/tests/provider/qwen_code/test_provider.py new file mode 100644 index 00000000..ff6fa0cd --- /dev/null +++ b/tests/provider/qwen_code/test_provider.py @@ -0,0 +1,128 @@ +"""QwenCodeProvider 委托、预刷新、身份与装配默认值。""" + +from __future__ import annotations + +import httpx + +from src.provider.base import ErrKind, EventKind, Quota, UpstreamReloginRequired +from src.provider.qwen_code import QwenCodeProvider +from src.provider.qwen_code.client import DEFAULT_HOST, EP_CHAT, EP_MODELS, EP_TOKEN +from src.provider.qwen_code.credential import QwenCredential +from tests.helpers.http import chunk_payload as chunk +from tests.helpers.http import sse_text_done as _sse +from tests.provider.qwen_code._support import client as _client + + +def test_default_id_and_client_host(): + provider = QwenCodeProvider() + assert provider.id == "qwen_code" + assert provider.client.host == DEFAULT_HOST + + +def test_import_credential_and_identity(): + provider = QwenCodeProvider() + assert provider.import_credential({"access_token": "at"}) == {"access_token": "at"} + assert isinstance(provider.credential_from({"access_token": "at"}), QwenCredential) + assert provider.login_identity({"access_token": "at", "account": "a@b.c"}) == "a@b.c" + hashed = provider.login_identity({"access_token": "at"}) + assert hashed.startswith("qw-") and "at" not in hashed + + +def test_classify_delegates(): + provider = QwenCodeProvider() + assert provider.classify(429, b"") is ErrKind.SOFT + assert provider.classify(401, b"") is ErrKind.DEAD + + +async def test_refresh_rotates_and_keeps_extra_fields(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_TOKEN + return httpx.Response(200, json={"access_token": "at2", "refresh_token": "rt2", + "expires_in": 60}) + + provider = QwenCodeProvider(client=_client(handler)) + data = {"access_token": "at1", "refresh_token": "rt1", "custom": "keep"} + refreshed = await provider.refresh(data) + assert refreshed["access_token"] == "at2" + assert refreshed["refresh_token"] == "rt2" + assert refreshed["custom"] == "keep" + + +async def test_refresh_without_refresh_token_is_noop(): + provider = QwenCodeProvider() + data = {"access_token": "at"} + assert await provider.refresh(data) is data + + +async def test_refresh_propagates_relogin_required(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(400, json={"error": "invalid_grant"}) + + provider = QwenCodeProvider(client=_client(handler)) + try: + await provider.refresh({"access_token": "at", "refresh_token": "rt"}) + except UpstreamReloginRequired: + pass + else: # pragma: no cover + raise AssertionError("expected UpstreamReloginRequired") + + +async def test_probe_quota_guards_missing_token_and_delegates(): + provider = QwenCodeProvider() + quota = await provider.probe_quota({}) + assert isinstance(quota, Quota) + assert quota.probe_failed is True + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"quota": {"remaining": 5, "total": 10}}) + + provider = QwenCodeProvider(client=_client(handler)) + quota = await provider.probe_quota({"access_token": "at"}) + assert quota.remaining == 5.0 + + +async def test_list_models_requires_token_and_uses_resource_url(): + provider = QwenCodeProvider() + try: + await provider.list_models({}) + except Exception as error: # noqa: BLE001 + assert "missing access_token" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + seen: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(str(request.url)) + assert request.url.path == EP_MODELS + return httpx.Response(200, json={"data": [{"id": "qwen3-max"}]}) + + provider = QwenCodeProvider(client=_client(handler)) + models = await provider.list_models({"access_token": "at", + "resource_url": "https://portal.qwen.ai"}) + assert [m.id for m in models] == ["qwen3-max"] + assert seen == ["https://portal.qwen.ai/api/v2/models"] + + +async def test_stream_chat_requires_token_and_delegates(): + provider = QwenCodeProvider() + try: + [event async for event in provider.stream_chat({}, {"messages": []}, "qwen3")] + except Exception as error: # noqa: BLE001 + assert "missing access_token" in str(error) + else: # pragma: no cover + raise AssertionError("expected UpstreamProtocolViolation") + + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == EP_CHAT + return httpx.Response(200, text=_sse(chunk({"content": "hi"}))) + + provider = QwenCodeProvider(client=_client(handler)) + events = [event async for event in provider.stream_chat( + {"access_token": "at"}, {"messages": []}, "qwen3")] + assert events[0].kind is EventKind.CONTENT + + +async def test_aclose_releases_pool(): + provider = QwenCodeProvider(client=_client(lambda request: httpx.Response(200))) + await provider.aclose() diff --git a/tests/provider/test_login_identity.py b/tests/provider/test_login_identity.py index 27d15041..b95daf05 100644 --- a/tests/provider/test_login_identity.py +++ b/tests/provider/test_login_identity.py @@ -20,7 +20,8 @@ def test_registry_declares_only_mergeable_channels(): - assert set(LOGIN_IDENTITIES) == {"codearts", "officeace", "lingxi", "raccoon"} + assert set(LOGIN_IDENTITIES) == {"codearts", "officeace", "lingxi", "raccoon", + "copilot", "qwen_code"} # 首选身份与别名集合必须覆盖同一批渠道,否则「能合并」与「找得到」会错开 assert set(LOGIN_IDENTITY_SETS) == set(LOGIN_IDENTITIES) # 手工导入即重登的渠道只能是「没有 OAuth 轨道」的两家:CodeArts / diff --git a/tests/provider/trae/test_client.py b/tests/provider/trae/test_client.py index ca8fdc23..4200cccd 100644 --- a/tests/provider/trae/test_client.py +++ b/tests/provider/trae/test_client.py @@ -35,7 +35,8 @@ def _client(handler, **kw) -> TraeClient: def test_resolve_flat_auto_and_forced(): assert resolve("glm-5.2", "d").providers == ( "codebuddy", "codebuddy_intl", "trae", "zen", "kilo", "qoder", - "codearts", "officeace", "raccoon", "lingxi", "generic") + "codearts", "officeace", "raccoon", "lingxi", "copilot", "qwen_code", + "generic") assert resolve("", "glm-5.2").model == "glm-5.2" assert resolve("auto", "glm-5.2").model == "glm-5.2" assert resolve(None, "glm-5.2").model == "glm-5.2" diff --git a/web/src/api/__tests__/providers.test.ts b/web/src/api/__tests__/providers.test.ts index fbe48b93..ed247fa8 100644 --- a/web/src/api/__tests__/providers.test.ts +++ b/web/src/api/__tests__/providers.test.ts @@ -44,8 +44,8 @@ describe("渠道展示元数据", () => { it("每个已知渠道都有标签、缩写与专属配色(三者对齐)", () => { const providers = Object.keys(PROVIDER_LABEL); expect(providers.sort()).toEqual([ - "codearts", "codebuddy", "codebuddy_intl", "kilo", "lingxi", "officeace", - "qoder", "raccoon", "trae", "zen", + "codearts", "codebuddy", "codebuddy_intl", "copilot", "kilo", "lingxi", + "officeace", "qoder", "qwen_code", "raccoon", "trae", "zen", ]); for (const provider of providers) { expect(PROVIDER_ABBR[provider as keyof typeof PROVIDER_ABBR]).toBeTruthy(); diff --git a/web/src/api/providers.ts b/web/src/api/providers.ts index e9ff9e80..debb181a 100644 --- a/web/src/api/providers.ts +++ b/web/src/api/providers.ts @@ -23,6 +23,8 @@ export const PROVIDER_LABEL: Record = { officeace: "OfficeAce", raccoon: "小浣熊", lingxi: "灵犀", + copilot: "GitHub Copilot", + qwen_code: "Qwen Code", }; /** 模型下拉里的渠道缩写(如 `CB x0.29`)。 */ @@ -37,6 +39,8 @@ export const PROVIDER_ABBR: Record = { officeace: "OA", raccoon: "RC", lingxi: "LX", + copilot: "GH", + qwen_code: "QW", }; /** @@ -56,6 +60,8 @@ export const PROVIDER_CHART_COLOR: Record = { officeace: "var(--chart-8)", raccoon: "var(--chart-9)", lingxi: "var(--chart-10)", + copilot: "var(--chart-11)", + qwen_code: "var(--chart-12)", }; /** 未知渠道(老数据/未来渠道)的兜底色。 */ @@ -80,6 +86,8 @@ export const PROVIDER_ORDER: BuiltinProvider[] = [ "officeace", "raccoon", "lingxi", + "copilot", + "qwen_code", ]; /** diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 3178c4e9..4ce64482 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -24,7 +24,9 @@ export type BuiltinProvider = | "codearts" | "officeace" | "raccoon" - | "lingxi"; + | "lingxi" + | "copilot" + | "qwen_code"; export type Provider = BuiltinProvider | (string & {}); diff --git a/web/src/components/AddCredentialDialog.tsx b/web/src/components/AddCredentialDialog.tsx index 67630039..5c6d1d10 100644 --- a/web/src/components/AddCredentialDialog.tsx +++ b/web/src/components/AddCredentialDialog.tsx @@ -30,6 +30,8 @@ const LOGIN_PROVIDERS: BuiltinProvider[] = [ "qoder", "codearts", "officeace", + "copilot", + "qwen_code", ]; /** 上次成功导入的渠道:重复加号时不用每次重新选。 */ @@ -65,6 +67,8 @@ const IMPORT_TEMPLATES: Partial> = { '{\n "model_app_key": "",\n "model_app_secret": "",\n "model_base_url": "https://modelgw-xxxx.officeace.cn-southwest-2.huaweicloud-agentarts.com"\n}', raccoon: '{\n "access_token": ""\n}', lingxi: '{\n "cookie": "wps_sid=…; uid=…"\n}', + copilot: '{\n "github_token": "gho_…"\n}', + qwen_code: '{\n "access_token": ""\n}', }; type TabValue = "login" | "import"; diff --git a/web/src/lib/credentialImport.ts b/web/src/lib/credentialImport.ts index abd39f85..1fe8ae5c 100644 --- a/web/src/lib/credentialImport.ts +++ b/web/src/lib/credentialImport.ts @@ -35,6 +35,8 @@ export const IMPORT_PROVIDERS: BuiltinProvider[] = [ "officeace", "raccoon", "lingxi", + "copilot", + "qwen_code", ]; /** 通用上游的凭证形状与内置渠道不同(只有 Bearer key),模板固定一份。 */ diff --git a/web/src/styles.css b/web/src/styles.css index deaa42b7..2420acef 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -70,6 +70,8 @@ --chart-8: oklch(0.56 0.15 25); --chart-9: oklch(0.60 0.13 130); --chart-10: oklch(0.60 0.15 95); + --chart-11: oklch(0.58 0.16 120); + --chart-12: oklch(0.62 0.14 340); /* 模型线专用色(按模型趋势图)。与 --chart-N 的渠道色分开:那张图上 渠道色代表渠道,模型图上代表模型,混用会让同一页两种图的颜色语义 对不上(MASTER §2.4「chart-N 为渠道色」)。 */ @@ -117,6 +119,8 @@ --chart-8: oklch(0.72 0.15 25); --chart-9: oklch(0.74 0.12 130); --chart-10: oklch(0.74 0.13 95); + --chart-11: oklch(0.72 0.15 120); + --chart-12: oklch(0.76 0.14 340); --model-1: oklch(0.75 0.14 40); --model-2: oklch(0.70 0.13 285); --model-3: oklch(0.73 0.12 200); @@ -176,6 +180,8 @@ --color-chart-8: var(--chart-8); --color-chart-9: var(--chart-9); --color-chart-10: var(--chart-10); + --color-chart-11: var(--chart-11); + --color-chart-12: var(--chart-12); /* 阴影 token(覆盖 Tailwind 默认 shadow-*) */ --shadow-sm: var(--elevation-sm); From b7c251f7d14e4da6b4cd053da3a2a8a640ceeff6 Mon Sep 17 00:00:00 2001 From: Robbs Luo Date: Thu, 3 Dec 2026 11:33:56 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix=20COD-53=EF=BC=9A=E5=90=88=E5=B9=B6=20m?= =?UTF-8?q?ain=20=E5=90=8E=E4=BF=AE=E5=89=8D=E7=AB=AF=20i18n=20=E8=AF=8D?= =?UTF-8?q?=E8=A1=A8=E4=B8=8E=E5=8E=BB=E9=87=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/src/api/providers.ts | 4 ++-- web/src/api/statsErrors.ts | 2 +- web/src/i18n/text.ts | 7 +++---- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/web/src/api/providers.ts b/web/src/api/providers.ts index c138328b..918771b0 100644 --- a/web/src/api/providers.ts +++ b/web/src/api/providers.ts @@ -24,8 +24,8 @@ export const PROVIDER_LABEL: Record = { officeace: "OfficeAce", raccoon: tr("小浣熊"), lingxi: tr("灵犀"), - copilot: tr("GitHub Copilot"), - qwen_code: tr("Qwen Code"), + copilot: "GitHub Copilot", + qwen_code: "Qwen Code", }; /** 模型下拉里的渠道缩写(如 `CB x0.29`)。 */ diff --git a/web/src/api/statsErrors.ts b/web/src/api/statsErrors.ts index a9fbca20..03475318 100644 --- a/web/src/api/statsErrors.ts +++ b/web/src/api/statsErrors.ts @@ -127,7 +127,7 @@ async function fetchStatsErrorTrend( }, ); if (!response.ok) { - throw new Error(`失败趋势加载失败(HTTP ${response.status})`); + throw new Error(tr("失败趋势加载失败(HTTP {0})", [response.status])); } return (await response.json()) as StatsErrorTrendResponse; } diff --git a/web/src/i18n/text.ts b/web/src/i18n/text.ts index 4de1f6dd..eeff6fc1 100644 --- a/web/src/i18n/text.ts +++ b/web/src/i18n/text.ts @@ -1024,6 +1024,7 @@ export const TEXT_EN: Record = { "天失败": "days failed", "天)·": "days) ·", "失败归因加载失败(HTTP {0})": "Failed to load failure attribution (HTTP {0})", + "失败趋势加载失败(HTTP {0})": "Failed to load the failure trend (HTTP {0})", "完成": "Done", "官方状态页": "Official status pages", "官方状态页粒度比本服务的模型级冷却粗、更新也滞后,这里只做解释,不参与选号 / 熔断;本服务实时冷却见「凭证管理」页。数据仅存内存,服务重启后归零。": "Official status pages are coarser than this service's per-model cooldown and lag behind, so they only explain, they never pick credentials or trip the breaker; see the credentials page for live cooldowns. The data lives in memory only and resets when the service restarts.", @@ -1278,16 +1279,14 @@ export const TEXT_EN: Record = { "运行中…": "Running…", "运行时配置加载失败": "Failed to load runtime settings", "近": "Last ", - "近 30 天": "Last 30 days", - "近 7 天": "Last 7 days", - "近期事故": "Recent incidents", - "返回": "Back", "还没有备份": "No backups yet", "还没有记录。冷却、恢复或启停发生后,这里会留下时间与原因。": "No records yet. Cooldowns, restores and enable/disable events leave their time and reason here.", "这条 cURL 里没有 Cookie 或 Authorization 头,换一条带登录态的请求再复制": "This cURL has no Cookie or Authorization header; copy one from a request that carries the session", "这里没有配置项。": "There are no settings here.", "进行中": "Ongoing", "连续失败": "Consecutive failures", + "近期事故": "Recent incidents", + "返回": "Back", "选择文件": "Choose file", "逗号分隔的模型名或 glob(如 glm-*、kimi-k3),留空 = 该号参与所有模型。不命中的请求只是这次不选它——不会停用、不会进冷却,换别的模型照常可用。": "Comma-separated model names or globs (e.g. glm-*, kimi-k3); blank = this credential serves every model. A non-matching request only skips it this time — nothing is disabled, nothing cools down, and other models keep working.", "逗号分隔的模型名或 glob(如 glm-*)。命中即不参与该模型选号——被某模型封号时只摘掉那一个,其余模型照常可用;与白名单取交集、黑名单优先。留空 = 不限制。": "Comma-separated model names or globs (e.g. glm-*). A match excludes the credential from that model only — being banned by one model drops just that one and the rest keep working; intersected with the allowlist, the blocklist wins. Blank = unlimited.", From 926aa090142936945beb387fafff2a332c7135f2 Mon Sep 17 00:00:00 2001 From: Robbs Luo Date: Thu, 3 Dec 2026 13:07:10 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix=20COD-53=EF=BC=9A=E6=81=A2=E5=A4=8D=20C?= =?UTF-8?q?OD-56=20=E5=87=AD=E8=AF=81=E5=88=86=E7=BB=84=E6=96=87=E6=A1=88?= =?UTF-8?q?=E4=B8=8E=E5=9B=9E=E5=BD=92=E6=B5=8B=E8=AF=95=E5=B9=B6=E5=8E=BB?= =?UTF-8?q?=E9=87=8D=20i18n=20=E8=AF=8D=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/src/i18n/text.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/web/src/i18n/text.ts b/web/src/i18n/text.ts index 681b72ba..da95c13f 100644 --- a/web/src/i18n/text.ts +++ b/web/src/i18n/text.ts @@ -1055,7 +1055,6 @@ export const TEXT_EN: Record = { "天失败": "days failed", "天)·": "days) ·", "失败归因加载失败(HTTP {0})": "Failed to load failure attribution (HTTP {0})", - "失败趋势加载失败(HTTP {0})": "Failed to load failure trend (HTTP {0})", "完成": "Done", "官方状态页": "Official status pages", "官方状态页粒度比本服务的模型级冷却粗、更新也滞后,这里只做解释,不参与选号 / 熔断;本服务实时冷却见「凭证管理」页。数据仅存内存,服务重启后归零。": "Official status pages are coarser than this service's per-model cooldown and lag behind, so they only explain, they never pick credentials or trip the breaker; see the credentials page for live cooldowns. The data lives in memory only and resets when the service restarts.",