Skip to content

Commit f876679

Browse files
committed
fix(copilot): 额度按套餐选快照,免费档不再一登录就判耗尽
免费档(free_limited_copilot)的 premium_interactions 恒为 0/0 且 has_quota=false,表示「没有这项权益」;原实现只读该快照,0/0 被 health_score 判成「已耗尽」,新登录的账号立刻显示耗尽。 改为按优先级取真正约束聊天的快照:premium_interactions → chat → completions,跳过 entitlement<=0 的占位;unlimited 判未知;都无效 才判探测失败。实测免费档读出 chat 200/200、健康度 100。
1 parent 7ff6815 commit f876679

3 files changed

Lines changed: 85 additions & 11 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,8 +276,11 @@ token(`gho_…`),上游只认约 30 分钟的**短期 Copilot token**—
276276
- **端点**:聊天 `api.githubcopilot.com`(带 `Copilot-Integration-Id` +
277277
`Editor-Version` 伪装),换票 / 额度 `api.github.com`;两者都在
278278
`COPILOT_ALLOWED_ENDPOINTS` 白名单里。
279-
- **额度**:`copilot_internal/user` 的 `quota_snapshots.premium_interactions`
280-
(剩余 / 权益条数),无该快照判「未知」而非「耗尽」。
279+
- **额度**:`copilot_internal/user` 的 `quota_snapshots`,按套餐取真正约束聊天的
280+
快照:付费档 `premium_interactions`,免费档(`free_limited_copilot`)该快照恒为
281+
`0/0` 表示「无此权益」而非耗尽,落到 `chat`(再兜底 `completions`);都没有判
282+
「未知」而非「耗尽」。换票端点 403(GitHub 防爬)时回退用 GitHub token 本身当
283+
Bearer,有效期 30 分钟后由预刷新重试换票。
281284
- **错误分类**:401/403 → `DEAD`(换票即恢复);402 → `CREDIT`;400/404/422 →
282285
`INVALID`;429 → `SOFT`;5xx → `OTHER`。不新增冷却逻辑。
283286
- **ToS 灰区**:个人订阅条款禁止转售 / 共享席位,见 `provider/tos.py`。

‎src/provider/copilot/client.py‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,9 @@ async def fetch_models(self, copilot_token: str) -> list[Model]:
212212
async def probe_quota(self, credential: CopilotCredential) -> Quota:
213213
"""`copilot_internal/user` 的 `quota_snapshots` → 中立额度。
214214
215-
只取 `premium_interactions`(免费档可能没有该快照 → 未知而不是「耗尽」)。
216-
上游给的是「剩余条数 / 权益条数」,不做积分换算。
215+
按套餐取真正约束聊天的快照(见 `_quota_snapshot`):付费档读
216+
`premium_interactions`,免费档读 `chat`。上游给的是「剩余条数 /
217+
权益条数」,不做积分换算。
217218
"""
218219
now = int(time.time())
219220
if not credential.github_token:
@@ -225,23 +226,45 @@ async def probe_quota(self, credential: CopilotCredential) -> Quota:
225226
message="non-JSON copilot user response")
226227
except (UpstreamHTTPError, UpstreamProtocolViolation):
227228
return Quota(probe_failed=True, probed_at=now)
228-
snapshot = _premium_snapshot(data)
229+
snapshot = _quota_snapshot(data)
230+
if snapshot.get("unlimited") is True:
231+
# 无限额度不是「0/0 耗尽」,也不是探测失败:返回未知量纲
232+
return Quota(probed_at=now)
229233
remaining = _num(snapshot.get("remaining"))
230234
total = _num(snapshot.get("entitlement"))
231235
if remaining is None and total is None:
232236
return Quota(probe_failed=True, probed_at=now)
233237
return Quota(remaining=remaining, total=total, probed_at=now)
234238

235239

236-
def _premium_snapshot(data: Any) -> dict[str, Any]:
237-
"""取 `quota_snapshots.premium_interactions`(缺失/畸形返回空 dict)。"""
240+
#: 快照优先级:付费档看 premium_interactions,免费档看 chat。
241+
#: completions 只兜底(补齐式自动补全),不是聊天额度。
242+
_QUOTA_SNAPSHOT_ORDER = ("premium_interactions", "chat", "completions")
243+
244+
245+
def _quota_snapshot(data: Any) -> dict[str, Any]:
246+
"""取真正约束聊天的额度快照(缺失/畸形返回空 dict)。
247+
248+
免费档(`free_limited_copilot`)的 `premium_interactions` 恒为
249+
`remaining=0 / entitlement=0 / has_quota=false`,它表示「没有这项权益」,
250+
不是「额度用光」。只读它会立刻把新登录的免费账号判成耗尽;因此按顺序
251+
跳过 entitlement 为 0 的占位快照,落到实际计量的 `chat`。
252+
"""
238253
if not isinstance(data, dict):
239254
return {}
240255
snapshots = data.get("quota_snapshots")
241256
if not isinstance(snapshots, dict):
242257
return {}
243-
premium = snapshots.get("premium_interactions")
244-
return premium if isinstance(premium, dict) else {}
258+
for name in _QUOTA_SNAPSHOT_ORDER:
259+
snapshot = snapshots.get(name)
260+
if not isinstance(snapshot, dict):
261+
continue
262+
if snapshot.get("unlimited") is True:
263+
return snapshot
264+
total = _num(snapshot.get("entitlement"))
265+
if total is not None and total > 0:
266+
return snapshot
267+
return {}
245268

246269

247270
def _num(value: Any) -> float | None:

‎tests/provider/copilot/test_client.py‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
UpstreamHTTPError,
1818
_model_from_item,
1919
_num,
20-
_premium_snapshot,
20+
_quota_snapshot,
2121
chat_headers,
2222
github_headers,
2323
prepare_body,
@@ -243,6 +243,50 @@ def handler(request: httpx.Request) -> httpx.Response:
243243
assert quota.probe_failed is False
244244

245245

246+
async def test_probe_quota_falls_back_to_chat_snapshot_on_free_plan():
247+
"""免费档 premium_interactions 恒为 0/0(没有该权益),不能判成耗尽。
248+
249+
实测 `free_limited_copilot` 的账号面:premium 0/0 且
250+
`has_quota=false`,真正约束聊天的是 `chat`(200 条)。
251+
"""
252+
def handler(request: httpx.Request) -> httpx.Response:
253+
return httpx.Response(200, json={"quota_snapshots": {
254+
"premium_interactions": {
255+
"remaining": 0, "entitlement": 0, "has_quota": False},
256+
"chat": {"remaining": 200, "entitlement": 200},
257+
}})
258+
259+
quota = await _client(handler).probe_quota(CopilotCredential(github_token="gho"))
260+
assert quota.remaining == 200.0
261+
assert quota.total == 200.0
262+
assert quota.probe_failed is False
263+
264+
265+
async def test_probe_quota_falls_back_to_completions_when_chat_missing():
266+
def handler(request: httpx.Request) -> httpx.Response:
267+
return httpx.Response(200, json={"quota_snapshots": {
268+
"premium_interactions": {"remaining": 0, "entitlement": 0},
269+
"completions": {"remaining": 1999, "entitlement": 2000},
270+
}})
271+
272+
quota = await _client(handler).probe_quota(CopilotCredential(github_token="gho"))
273+
assert quota.remaining == 1999.0
274+
assert quota.total == 2000.0
275+
276+
277+
async def test_probe_quota_unlimited_snapshot_is_unknown_not_exhausted():
278+
def handler(request: httpx.Request) -> httpx.Response:
279+
return httpx.Response(200, json={"quota_snapshots": {
280+
"premium_interactions": {"unlimited": True, "remaining": 0,
281+
"entitlement": 0},
282+
}})
283+
284+
quota = await _client(handler).probe_quota(CopilotCredential(github_token="gho"))
285+
assert quota.probe_failed is False
286+
assert quota.remaining is None
287+
assert quota.total is None
288+
289+
246290
async def test_probe_quota_is_unknown_when_snapshot_missing_or_broken():
247291
for payload in ({"quota_snapshots": {"chat": {"remaining": 1}}},
248292
{"quota_snapshots": "junk"}, []):
@@ -314,7 +358,11 @@ def test_model_and_number_helpers():
314358
assert _num(True) is None
315359
assert _num("3") is None
316360
assert _num(3) == 3.0
317-
assert _premium_snapshot(None) == {}
361+
assert _quota_snapshot(None) == {}
362+
# 没有任何「有权益」的快照 → 空 dict(调用方据此判未知)
363+
assert _quota_snapshot({"quota_snapshots": {
364+
"premium_interactions": {"remaining": 0, "entitlement": 0}}}) == {}
365+
assert _quota_snapshot({"quota_snapshots": "junk"}) == {}
318366

319367

320368
def test_default_client_hosts():

0 commit comments

Comments
 (0)