coding-proxy 0.5.1a9__py3-none-any.whl → 0.5.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coding/proxy/config/config.default.yaml +13 -3
- coding/proxy/config/session_policy.py +35 -1
- coding/proxy/model/__init__.py +2 -0
- coding/proxy/model/vendor.py +15 -0
- coding/proxy/routing/executor.py +78 -14
- coding/proxy/routing/quota_guard.py +31 -7
- coding/proxy/routing/retry.py +13 -4
- coding/proxy/routing/router.py +2 -0
- coding/proxy/server/app.py +1 -0
- coding/proxy/server/dashboard.py +355 -31
- coding/proxy/server/routes.py +48 -0
- coding/proxy/vendors/antigravity.py +5 -2
- coding/proxy/vendors/base.py +2 -1
- coding/proxy/vendors/copilot.py +2 -1
- coding/proxy/vendors/zhipu.py +2 -2
- {coding_proxy-0.5.1a9.dist-info → coding_proxy-0.5.2.dist-info}/METADATA +5 -6
- {coding_proxy-0.5.1a9.dist-info → coding_proxy-0.5.2.dist-info}/RECORD +20 -20
- {coding_proxy-0.5.1a9.dist-info → coding_proxy-0.5.2.dist-info}/WHEEL +1 -1
- {coding_proxy-0.5.1a9.dist-info → coding_proxy-0.5.2.dist-info}/entry_points.txt +0 -0
- {coding_proxy-0.5.1a9.dist-info → coding_proxy-0.5.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -534,9 +534,9 @@ pricing:
|
|
|
534
534
|
# ── 智谱 GLM ──
|
|
535
535
|
- vendor: zhipu
|
|
536
536
|
model: glm-5.2 # 待区分长短上下文定价
|
|
537
|
-
input_cost_per_mtok: ¥
|
|
538
|
-
output_cost_per_mtok: ¥
|
|
539
|
-
cache_read_cost_per_mtok: ¥
|
|
537
|
+
input_cost_per_mtok: ¥8.00
|
|
538
|
+
output_cost_per_mtok: ¥28.00
|
|
539
|
+
cache_read_cost_per_mtok: ¥2.00
|
|
540
540
|
- vendor: zhipu
|
|
541
541
|
model: glm-5.1 # 待区分长短上下文定价
|
|
542
542
|
input_cost_per_mtok: ¥6.00
|
|
@@ -704,3 +704,13 @@ session_policies:
|
|
|
704
704
|
title_vendor_bindings:
|
|
705
705
|
- prefix: "# 目标"
|
|
706
706
|
vendor: "zhipu"
|
|
707
|
+
# Session 标题豁免前缀:标题提取每一层(user 文本 / 工具结果 / 图片 / 元数据兜底)
|
|
708
|
+
# 产出的候选以任一前缀开头则跳过,继续向下一层回退。既用于过滤注入式 Prompt
|
|
709
|
+
# (如示例语言指令),也可豁免无信息量的合成兜底标题。大小写敏感 startswith。
|
|
710
|
+
# 例:添加 "[Session]" 可让 [Session] <model> 这类兜底标题不再写入,
|
|
711
|
+
# session 标题保持空,待后续真实输入经延迟补写回填。
|
|
712
|
+
# ⚠️ 自定义 yaml 中该字段为整体替换(loader 的 list 合并约定,非追加合并);
|
|
713
|
+
# 写空列表即关闭豁免。加载时会自动 strip + 去空 + 去重。
|
|
714
|
+
title_exempt_prefixes:
|
|
715
|
+
- "Write the title in the"
|
|
716
|
+
- "[Session]"
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from pydantic import BaseModel, Field
|
|
5
|
+
from pydantic import BaseModel, Field, field_validator
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
class SessionPolicyMatch(BaseModel):
|
|
@@ -81,3 +81,37 @@ class SessionPoliciesConfig(BaseModel):
|
|
|
81
81
|
"匹配规则按列表顺序求值,首次匹配生效。"
|
|
82
82
|
),
|
|
83
83
|
)
|
|
84
|
+
title_exempt_prefixes: list[str] = Field(
|
|
85
|
+
default_factory=list,
|
|
86
|
+
description=(
|
|
87
|
+
"Session 标题豁免前缀名单。标题提取的每一层(user TEXT 噪声剥离、"
|
|
88
|
+
"TOOL_RESULT 摘要、IMAGE 计数、元数据兜底)产出的候选,若以任一前缀"
|
|
89
|
+
"开头,则视为豁免、继续向下一层回退;全部层级均被豁免时返回空串,"
|
|
90
|
+
"调用方据此跳过写库,session 标题保持空待后续真实输入回填。"
|
|
91
|
+
"既用于过滤注入式 Prompt(如示例语言指令),也可豁免无信息量的合成"
|
|
92
|
+
"兜底标题(如 [Session]、[Tool call]、[Tool output])。"
|
|
93
|
+
"大小写敏感的 startswith 匹配,与 title_vendor_bindings 语义一致。"
|
|
94
|
+
"加载时会自动 strip + 去空 + 去重;空字符串前缀会被丢弃"
|
|
95
|
+
"(防空串 startswith 恒真导致全量误豁免)。"
|
|
96
|
+
),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
@field_validator("title_exempt_prefixes", mode="after")
|
|
100
|
+
@classmethod
|
|
101
|
+
def _normalize_exempt_prefixes(cls, value: list[str]) -> list[str]:
|
|
102
|
+
"""归一化豁免前缀:strip + 去空 + 去重保序.
|
|
103
|
+
|
|
104
|
+
空字符串前缀必须丢弃——``"".startswith`` 恒真会豁免一切用户输入,
|
|
105
|
+
导致 Level 1 标题提取永久失效。
|
|
106
|
+
"""
|
|
107
|
+
seen: set[str] = set()
|
|
108
|
+
result: list[str] = []
|
|
109
|
+
for item in value:
|
|
110
|
+
if not isinstance(item, str):
|
|
111
|
+
continue
|
|
112
|
+
cleaned = item.strip()
|
|
113
|
+
if not cleaned or cleaned in seen:
|
|
114
|
+
continue
|
|
115
|
+
seen.add(cleaned)
|
|
116
|
+
result.append(cleaned)
|
|
117
|
+
return result
|
coding/proxy/model/__init__.py
CHANGED
|
@@ -25,6 +25,7 @@ from .vendor import ( # noqa: F401
|
|
|
25
25
|
UsageInfo,
|
|
26
26
|
VendorCapabilities,
|
|
27
27
|
VendorResponse,
|
|
28
|
+
decode_error_body,
|
|
28
29
|
decode_json_body,
|
|
29
30
|
extract_error_message,
|
|
30
31
|
sanitize_headers_for_synthetic_response,
|
|
@@ -83,6 +84,7 @@ __all__ = [
|
|
|
83
84
|
"CopilotModelCatalog",
|
|
84
85
|
"RequestCapabilities",
|
|
85
86
|
"UsageInfo",
|
|
87
|
+
"decode_error_body",
|
|
86
88
|
"decode_json_body",
|
|
87
89
|
"extract_error_message",
|
|
88
90
|
"sanitize_headers_for_synthetic_response",
|
coding/proxy/model/vendor.py
CHANGED
|
@@ -75,6 +75,20 @@ def extract_error_message(
|
|
|
75
75
|
return text[:500] if text else None
|
|
76
76
|
|
|
77
77
|
|
|
78
|
+
def decode_error_body(raw: bytes, limit: int = 500) -> str:
|
|
79
|
+
"""将上游错误响应体(bytes)安全解码为可读文本,供日志展示.
|
|
80
|
+
|
|
81
|
+
直接以 ``%s`` 格式化 ``bytes`` 会走 ``repr()``,导致非 ASCII 的 UTF-8
|
|
82
|
+
字节被转义为 ``\\xe6\\x82\\xa8`` 之类的不可读序列(中文乱码)。本函数:
|
|
83
|
+
|
|
84
|
+
- 使用 ``errors="replace"`` 容忍非法字节,非法字节降级为 ``�`` 而非抛异常,
|
|
85
|
+
确保日志路径绝对健壮;
|
|
86
|
+
- 先整体解码再按字符截断,避免在多字节 UTF-8 边界切断产生乱码
|
|
87
|
+
(因此 ``limit`` 语义为「字符数」而非「字节数」)。
|
|
88
|
+
"""
|
|
89
|
+
return raw.decode("utf-8", errors="replace")[:limit]
|
|
90
|
+
|
|
91
|
+
|
|
78
92
|
# ═══════════════════════════════════════════════════════════════
|
|
79
93
|
# 供应商核心数据类型
|
|
80
94
|
# ═══════════════════════════════════════════════════════════════
|
|
@@ -229,6 +243,7 @@ __all__ = [
|
|
|
229
243
|
"CopilotMisdirectedRequest",
|
|
230
244
|
"CopilotModelCatalog",
|
|
231
245
|
# 工具函数
|
|
246
|
+
"decode_error_body",
|
|
232
247
|
"decode_json_body",
|
|
233
248
|
"extract_error_message",
|
|
234
249
|
"sanitize_headers_for_synthetic_response",
|
coding/proxy/routing/executor.py
CHANGED
|
@@ -148,14 +148,30 @@ def _sanitize_user_text(raw: str) -> str:
|
|
|
148
148
|
# ─────────────────────────────────────────────────────────────────
|
|
149
149
|
|
|
150
150
|
|
|
151
|
-
def _extract_title_from_user_text(
|
|
152
|
-
|
|
151
|
+
def _extract_title_from_user_text(
|
|
152
|
+
messages: list[CanonicalMessagePart],
|
|
153
|
+
exempt_prefixes: list[str] | None = None,
|
|
154
|
+
) -> str:
|
|
155
|
+
"""Level 1: 从 user TEXT 部分提取经噪声剥离后的首条非空文本.
|
|
156
|
+
|
|
157
|
+
``exempt_prefixes`` 非空时,清洗后文本以任一前缀开头则跳过该输入、继续向后
|
|
158
|
+
查找——用于过滤注入式 Prompt,避免其被误用作 Session 标题。匹配作用于
|
|
159
|
+
``_sanitize_user_text`` 清洗后的纯文本(而非带 XML 标签的原始 raw)。
|
|
160
|
+
"""
|
|
153
161
|
for part in messages:
|
|
154
162
|
if part.role != "user" or part.type != CanonicalPartType.TEXT:
|
|
155
163
|
continue
|
|
156
164
|
cleaned = _sanitize_user_text(part.text)
|
|
157
|
-
if cleaned:
|
|
158
|
-
|
|
165
|
+
if not cleaned:
|
|
166
|
+
continue
|
|
167
|
+
if exempt_prefixes and any(cleaned.startswith(p) for p in exempt_prefixes):
|
|
168
|
+
logger.debug(
|
|
169
|
+
"Title candidate skipped by exempt prefix %r (snippet=%r)",
|
|
170
|
+
next(p for p in exempt_prefixes if cleaned.startswith(p)),
|
|
171
|
+
cleaned[:60],
|
|
172
|
+
)
|
|
173
|
+
continue
|
|
174
|
+
return cleaned[:_SESSION_TITLE_MAX_LEN]
|
|
159
175
|
return ""
|
|
160
176
|
|
|
161
177
|
|
|
@@ -193,23 +209,52 @@ def _extract_title_from_metadata(request: CanonicalRequest) -> str:
|
|
|
193
209
|
return ""
|
|
194
210
|
|
|
195
211
|
|
|
196
|
-
def _extract_session_title(
|
|
212
|
+
def _extract_session_title(
|
|
213
|
+
request: CanonicalRequest,
|
|
214
|
+
exempt_prefixes: list[str] | None = None,
|
|
215
|
+
) -> str:
|
|
197
216
|
"""从规范化请求中提取 session 标题 — 多层级回退策略。
|
|
198
217
|
|
|
199
218
|
依次尝试: user TEXT 噪声剥离 → TOOL_RESULT 摘要 → IMAGE 计数 → 元数据兜底。
|
|
200
|
-
|
|
219
|
+
任一层级产出候选且未被豁免即返回,确保 Dashboard 尽可能展示有辨识度的标题。
|
|
220
|
+
|
|
221
|
+
``exempt_prefixes`` 对所有层级统一生效:任一层产出的候选标题若以任一前缀
|
|
222
|
+
开头,则视为豁免、继续向下一层回退。Level 1 内部仍保留「逐条消息跳过」
|
|
223
|
+
语义(清洗后文本以豁免前缀开头则跳过该条、继续查找下一条 user TEXT);
|
|
224
|
+
本函数在编排层对每层最终候选再做一次 ``_is_exempt`` 拦截,使 Level 2/3/4
|
|
225
|
+
的合成标题(如 ``[Tool output]``、``[N Image(s)]``、``[Tool call]``、
|
|
226
|
+
``[Session]``)也能被用户显式豁免。全部层级均被豁免时返回空串,调用方
|
|
227
|
+
``if title:`` 据此跳过写库,session 标题保持空,待后续请求经
|
|
228
|
+
``update_empty_session_title`` 回填有意义标题。默认 ``None`` 时行为与历史一致。
|
|
201
229
|
"""
|
|
230
|
+
# 防御性过滤空串前缀:"" startswith 恒真会误豁免一切。入参虽经配置层与
|
|
231
|
+
# 构造器两层归一化,模块级直接调用(如测试)仍可能传入 [""],此处兜底。
|
|
232
|
+
prefixes = [p for p in (exempt_prefixes or []) if p]
|
|
233
|
+
|
|
234
|
+
def _is_exempt(candidate: str) -> bool:
|
|
235
|
+
"""候选标题是否命中任一豁免前缀(大小写敏感 startswith)。"""
|
|
236
|
+
return bool(prefixes) and any(candidate.startswith(p) for p in prefixes)
|
|
237
|
+
|
|
202
238
|
messages = request.messages
|
|
239
|
+
# Level 1: 内部已对每条 user TEXT 做豁免跳过;外层 _is_exempt 对其最终候选
|
|
240
|
+
# 再做一次拦截(正常路径下冗余,作为 _sanitize_user_text 一致性兜底)。
|
|
241
|
+
title = _extract_title_from_user_text(messages, exempt_prefixes=prefixes)
|
|
242
|
+
if title and not _is_exempt(title):
|
|
243
|
+
return title[:_SESSION_TITLE_MAX_LEN]
|
|
244
|
+
# Level 2 / Level 3: 候选为合成标题,统一经 _is_exempt 拦截后回退。
|
|
203
245
|
for extractor in (
|
|
204
|
-
_extract_title_from_user_text,
|
|
205
246
|
_extract_title_from_tool_results,
|
|
206
247
|
_extract_title_from_images,
|
|
207
248
|
):
|
|
208
249
|
title = extractor(messages)
|
|
209
|
-
if title:
|
|
250
|
+
if title and not _is_exempt(title):
|
|
210
251
|
return title[:_SESSION_TITLE_MAX_LEN]
|
|
211
|
-
# Level 4
|
|
212
|
-
|
|
252
|
+
# Level 4: 签名不同(依赖 request 元数据)。被豁免则落到末尾返回空串,
|
|
253
|
+
# 使调用方 if title: 跳过写库、保留空标题待后续回填。
|
|
254
|
+
title = _extract_title_from_metadata(request)
|
|
255
|
+
if title and not _is_exempt(title):
|
|
256
|
+
return title[:_SESSION_TITLE_MAX_LEN]
|
|
257
|
+
return ""
|
|
213
258
|
|
|
214
259
|
|
|
215
260
|
def _build_semantic_rejection_diagnostic(body: dict[str, Any]) -> str:
|
|
@@ -614,6 +659,7 @@ class _RouteExecutor:
|
|
|
614
659
|
reauth_coordinator: Any | None = None,
|
|
615
660
|
session_policy_resolver: SessionPolicyResolver | None = None,
|
|
616
661
|
title_vendor_bindings: list[TitleVendorBinding] | None = None,
|
|
662
|
+
title_exempt_prefixes: list[str] | None = None,
|
|
617
663
|
) -> None:
|
|
618
664
|
self._router = router
|
|
619
665
|
self._tiers = tiers
|
|
@@ -622,6 +668,13 @@ class _RouteExecutor:
|
|
|
622
668
|
self._reauth_coordinator = reauth_coordinator
|
|
623
669
|
self._policy_resolver = session_policy_resolver or SessionPolicyResolver()
|
|
624
670
|
self._title_vendor_bindings = title_vendor_bindings or []
|
|
671
|
+
# 豁免前缀名单:构造期二次归一化(strip + 去空),双重防御配置层 field_validator。
|
|
672
|
+
# 即便绕过配置层直接构造 executor,也能避免空串 startswith 恒真与纯空白失配。
|
|
673
|
+
self._title_exempt_prefixes: list[str] = [
|
|
674
|
+
stripped
|
|
675
|
+
for p in (title_exempt_prefixes or [])
|
|
676
|
+
if isinstance(p, str) and (stripped := p.strip())
|
|
677
|
+
]
|
|
625
678
|
self._validate_title_vendor_bindings()
|
|
626
679
|
|
|
627
680
|
# Tier 名称 → OAuth provider 名称的映射
|
|
@@ -676,6 +729,17 @@ class _RouteExecutor:
|
|
|
676
729
|
seen.add(tier.name)
|
|
677
730
|
return ordered
|
|
678
731
|
|
|
732
|
+
def _extract_session_title(self, request: CanonicalRequest) -> str:
|
|
733
|
+
"""封装模块级标题提取,注入实例持有的豁免前缀名单.
|
|
734
|
+
|
|
735
|
+
将 ``self._title_exempt_prefixes`` 透传给模块级 ``_extract_session_title``,
|
|
736
|
+
使 Level 1 能跳过以豁免前缀开头的注入式 Prompt。4 处标题提取调用点统一
|
|
737
|
+
经此方法,避免重复透传(零透传污染)。
|
|
738
|
+
"""
|
|
739
|
+
return _extract_session_title(
|
|
740
|
+
request, exempt_prefixes=self._title_exempt_prefixes
|
|
741
|
+
)
|
|
742
|
+
|
|
679
743
|
def _apply_title_based_policy(self, session_key: str, title: str) -> None:
|
|
680
744
|
"""根据 Session 标题前缀自动绑定供应商.
|
|
681
745
|
|
|
@@ -790,7 +854,7 @@ class _RouteExecutor:
|
|
|
790
854
|
canonical_request.trace_id,
|
|
791
855
|
)
|
|
792
856
|
if is_new_session:
|
|
793
|
-
title = _extract_session_title(canonical_request)
|
|
857
|
+
title = self._extract_session_title(canonical_request)
|
|
794
858
|
if title:
|
|
795
859
|
await self._recorder.set_session_title(
|
|
796
860
|
canonical_request.session_key, title
|
|
@@ -798,7 +862,7 @@ class _RouteExecutor:
|
|
|
798
862
|
self._apply_title_based_policy(canonical_request.session_key, title)
|
|
799
863
|
else:
|
|
800
864
|
# 延迟标题补写: 若 session 尚无标题,尝试从当前请求中提取并回写。
|
|
801
|
-
title = _extract_session_title(canonical_request)
|
|
865
|
+
title = self._extract_session_title(canonical_request)
|
|
802
866
|
if title:
|
|
803
867
|
await self._recorder.update_empty_session_title(
|
|
804
868
|
canonical_request.session_key, title
|
|
@@ -977,7 +1041,7 @@ class _RouteExecutor:
|
|
|
977
1041
|
canonical_request.trace_id,
|
|
978
1042
|
)
|
|
979
1043
|
if is_new_session:
|
|
980
|
-
title = _extract_session_title(canonical_request)
|
|
1044
|
+
title = self._extract_session_title(canonical_request)
|
|
981
1045
|
if title:
|
|
982
1046
|
await self._recorder.set_session_title(
|
|
983
1047
|
canonical_request.session_key, title
|
|
@@ -985,7 +1049,7 @@ class _RouteExecutor:
|
|
|
985
1049
|
self._apply_title_based_policy(canonical_request.session_key, title)
|
|
986
1050
|
else:
|
|
987
1051
|
# 延迟标题补写: 若 session 尚无标题,尝试从当前请求中提取并回写。
|
|
988
|
-
title = _extract_session_title(canonical_request)
|
|
1052
|
+
title = self._extract_session_title(canonical_request)
|
|
989
1053
|
if title:
|
|
990
1054
|
await self._recorder.update_empty_session_title(
|
|
991
1055
|
canonical_request.session_key, title
|
|
@@ -175,15 +175,39 @@ class QuotaGuard:
|
|
|
175
175
|
)
|
|
176
176
|
|
|
177
177
|
def reset(self) -> None:
|
|
178
|
-
"""
|
|
178
|
+
"""手动复位配额守卫(保留滑动窗口用量计数).
|
|
179
|
+
|
|
180
|
+
- 用量未超阈值 / 守卫非 EXCEEDED → 状态机回到 WITHIN_QUOTA;
|
|
181
|
+
- 用量确已超阈值 → 保持 QUOTA_EXCEEDED:不伪造用量,也不走
|
|
182
|
+
WITHIN_QUOTA → QUOTA_EXCEEDED 回环(回环会把 ``_last_probe`` 刷成
|
|
183
|
+
当前时刻,令探测恢复凭空推迟一个 probe_interval,反复复位即饿死探测)。
|
|
184
|
+
|
|
185
|
+
两种分支均清除 cap 错误卡死标志并还原探测间隔。``_entries`` / ``_total``
|
|
186
|
+
记录的是真实用量,清零会使 ``usage_percent`` 永久归零(基线仅在进程
|
|
187
|
+
启动时回填),任何情况下不予触碰。
|
|
188
|
+
"""
|
|
179
189
|
with self._lock:
|
|
180
|
-
self.
|
|
181
|
-
self.
|
|
182
|
-
|
|
183
|
-
logger.info(
|
|
184
|
-
"Quota guard [%s]: manually reset to WITHIN_QUOTA",
|
|
185
|
-
self._window_label,
|
|
190
|
+
self._expire()
|
|
191
|
+
over = self._budget > 0 and self._total >= int(
|
|
192
|
+
self._budget * self._threshold
|
|
186
193
|
)
|
|
194
|
+
if over and self._state == QuotaState.QUOTA_EXCEEDED:
|
|
195
|
+
self._cap_error_active = False
|
|
196
|
+
self._effective_probe_interval = self._probe_interval
|
|
197
|
+
logger.info(
|
|
198
|
+
"Quota guard [%s]: manually reset (usage %d tokens over "
|
|
199
|
+
"threshold, EXCEEDED state kept, probe interval restored)",
|
|
200
|
+
self._window_label,
|
|
201
|
+
self._total,
|
|
202
|
+
)
|
|
203
|
+
else:
|
|
204
|
+
self._transition_to(QuotaState.WITHIN_QUOTA)
|
|
205
|
+
logger.info(
|
|
206
|
+
"Quota guard [%s]: manually reset to WITHIN_QUOTA "
|
|
207
|
+
"(usage %d tokens preserved)",
|
|
208
|
+
self._window_label,
|
|
209
|
+
self._total,
|
|
210
|
+
)
|
|
187
211
|
|
|
188
212
|
def get_info(self) -> dict:
|
|
189
213
|
"""获取配额守卫状态信息."""
|
coding/proxy/routing/retry.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""传输层重试策略 — 指数退避与
|
|
1
|
+
"""传输层重试策略 — 指数退避与 Equal Jitter.
|
|
2
2
|
|
|
3
3
|
与 Circuit Breaker 正交互:
|
|
4
4
|
- Retry 处理瞬态网络抖动(秒级恢复)
|
|
@@ -68,15 +68,24 @@ def is_retryable_status(status_code: int) -> bool:
|
|
|
68
68
|
|
|
69
69
|
|
|
70
70
|
def calculate_delay(attempt: int, cfg: RetryConfig) -> float:
|
|
71
|
-
"""计算第 N 次重试的延迟(毫秒),含指数退避和
|
|
71
|
+
"""计算第 N 次重试的延迟(毫秒),含指数退避和 Equal Jitter.
|
|
72
|
+
|
|
73
|
+
Equal Jitter 策略: temp = min(initial * backoff^attempt, max);
|
|
74
|
+
delay = temp/2 + random(0, temp/2),落在 [temp/2, temp]。
|
|
75
|
+
相较 Full Jitter (random(0, temp)),Equal Jitter 保留一半固定基线,
|
|
76
|
+
使相邻重试的延迟区间仅边界相切,呈现单调非递减的指数形态,
|
|
77
|
+
同时保留抖动以防惊群。
|
|
78
|
+
|
|
79
|
+
契约边界:单调非递减依赖 ``backoff_multiplier >= 2.0`` 且未触及
|
|
80
|
+
``max_delay_ms`` 封顶;封顶后各 attempt 区间退化为同一 [max/2, max]
|
|
81
|
+
(当前 Zhipu ``max_retries=4`` 触及不到该边界)。
|
|
72
82
|
|
|
73
|
-
Full Jitter 策略: delay = random(0, min(initial * backoff^attempt, max))
|
|
74
83
|
参考: AWS "Exponential Backoff And Jitter" (Marc Brooker, 2015)
|
|
75
84
|
"""
|
|
76
85
|
delay = cfg.initial_delay_ms * (cfg.backoff_multiplier**attempt)
|
|
77
86
|
delay = min(delay, cfg.max_delay_ms)
|
|
78
87
|
|
|
79
88
|
if cfg.jitter:
|
|
80
|
-
delay = random.uniform(0, delay)
|
|
89
|
+
delay = delay / 2 + random.uniform(0, delay / 2)
|
|
81
90
|
|
|
82
91
|
return delay
|
coding/proxy/routing/router.py
CHANGED
|
@@ -40,6 +40,7 @@ class RequestRouter:
|
|
|
40
40
|
compat_session_store: CompatSessionStore | None = None,
|
|
41
41
|
session_policy_resolver: SessionPolicyResolver | None = None,
|
|
42
42
|
title_vendor_bindings: list[TitleVendorBinding] | None = None,
|
|
43
|
+
title_exempt_prefixes: list[str] | None = None,
|
|
43
44
|
) -> None:
|
|
44
45
|
if not tiers:
|
|
45
46
|
raise ValueError("至少需要一个供应商层级")
|
|
@@ -59,6 +60,7 @@ class RequestRouter:
|
|
|
59
60
|
reauth_coordinator=reauth_coordinator,
|
|
60
61
|
session_policy_resolver=session_policy_resolver,
|
|
61
62
|
title_vendor_bindings=title_vendor_bindings,
|
|
63
|
+
title_exempt_prefixes=title_exempt_prefixes,
|
|
62
64
|
)
|
|
63
65
|
|
|
64
66
|
def set_pricing_table(self, table: PricingTable) -> None:
|
coding/proxy/server/app.py
CHANGED
|
@@ -162,6 +162,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
|
|
162
162
|
compat_session_store,
|
|
163
163
|
session_policy_resolver=SessionPolicyResolver(config.session_policies.policies),
|
|
164
164
|
title_vendor_bindings=config.session_policies.title_vendor_bindings,
|
|
165
|
+
title_exempt_prefixes=config.session_policies.title_exempt_prefixes,
|
|
165
166
|
)
|
|
166
167
|
|
|
167
168
|
app = FastAPI(title="coding-proxy", version=__version__, lifespan=lifespan)
|
coding/proxy/server/dashboard.py
CHANGED
|
@@ -11,28 +11,111 @@ from fastapi.responses import HTMLResponse, Response
|
|
|
11
11
|
|
|
12
12
|
from ..logging.db import TimePeriod
|
|
13
13
|
|
|
14
|
+
# ── 品牌图标:Tabler prompt 核心笔划(> 与 _)+ 通透青绿圆环 ──────────────
|
|
15
|
+
# 设计(方案 d05):全透明底 + 青绿渐变细圆环(stroke 0.5,仅原 1/3,通透若隐)+
|
|
16
|
+
# 饱和青绿渐变 >_ 笔划(stroke 2.5)。极细环与饱和笔划形成权重对比,>_ 为绝对主角;
|
|
17
|
+
# 青绿(#22d3ee -> #2dd4bf)承载终端/代码语义,通透明快。基础笔划取自 Tabler prompt
|
|
18
|
+
# (chevron M5 7l5 5l-5 5 + 下划线 M13 17l6 0,下划线长 6 单位、不会小尺寸点化)。
|
|
19
|
+
# 渐变用 gradientUnits="userSpaceOnUse" + 绝对坐标:纯水平下划线包围盒高度为 0,若用
|
|
20
|
+
# 默认 objectBoundingBox 渐变会映射失效而不着色(下划线消失),userSpaceOnUse 规避。
|
|
21
|
+
# 单一事实源:_PROMPT_PATHS 与 _LOGO_DEFS 同时供 favicon SVG(f-string)与页面
|
|
22
|
+
# logo({{PROMPT}} / {{LOGO_DEFS}} 模板替换)消费。
|
|
23
|
+
_BRAND_FROM, _BRAND_TO = "#22d3ee", "#2dd4bf"
|
|
24
|
+
_LOGO_DEFS = (
|
|
25
|
+
'<defs><linearGradient id="cpBrand" gradientUnits="userSpaceOnUse" '
|
|
26
|
+
'x1="4" y1="4" x2="20" y2="20">'
|
|
27
|
+
f'<stop offset="0" stop-color="{_BRAND_FROM}"/>'
|
|
28
|
+
f'<stop offset="1" stop-color="{_BRAND_TO}"/>'
|
|
29
|
+
"</linearGradient></defs>"
|
|
30
|
+
)
|
|
31
|
+
_PROMPT_PATHS = '<path d="M5 7l5 5l-5 5" /><path d="M13 17l6 0" />'
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ── Favicon (SVG, 现代浏览器主选) ──────────────────────────────────────────
|
|
35
|
+
def _build_favicon_svg() -> str:
|
|
36
|
+
"""生成 24×24 SVG favicon:通透青绿圆环 + 品牌渐变 prompt 笔划(方案 d05).
|
|
37
|
+
|
|
38
|
+
全透明底 + 青绿渐变细圆环(``r=11``、``stroke-width=0.5``、``stroke-opacity=.55``,
|
|
39
|
+
通透若隐)+ 饱和青绿渐变 ``>`` 与 ``_`` 笔划(``stroke-width=2.5``)。极细环与饱和
|
|
40
|
+
笔划形成权重对比,``>_`` 为视觉主角。独立 SVG 文档无 CSS 上下文,``currentColor``
|
|
41
|
+
不可靠,故渐变复用 ``_LOGO_DEFS``(userSpaceOnUse,规避水平下划线不着色)单一事实源。
|
|
42
|
+
"""
|
|
43
|
+
return (
|
|
44
|
+
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">'
|
|
45
|
+
f"{_LOGO_DEFS}"
|
|
46
|
+
'<circle cx="12" cy="12" r="11" fill="none" stroke="url(#cpBrand)" '
|
|
47
|
+
'stroke-width="0.5" stroke-opacity=".55"/>'
|
|
48
|
+
f'<g fill="none" stroke="url(#cpBrand)" stroke-width="2.5" '
|
|
49
|
+
f'stroke-linecap="round" stroke-linejoin="round">{_PROMPT_PATHS}</g>'
|
|
50
|
+
"</svg>"
|
|
51
|
+
)
|
|
52
|
+
|
|
14
53
|
|
|
15
|
-
# ── Favicon (
|
|
54
|
+
# ── Favicon (ICO, 32×32 光栅回退) ─────────────────────────────────────────
|
|
16
55
|
def _build_favicon() -> bytes:
|
|
17
|
-
"""程序化生成
|
|
56
|
+
"""程序化生成 32×32 ICO:全透明底 + 青绿渐变 prompt 笔划(旧浏览器/Safari 回退).
|
|
57
|
+
|
|
58
|
+
项目无 Pillow/cairosvg 等图像库,故以纯 Python 按像素光栅化:全透明底 + 青绿渐变
|
|
59
|
+
(#22d3ee -> #2dd4bf)``>`` 折线与 ``_`` 下划线。沿用「全零 AND-mask + per-pixel
|
|
60
|
+
alpha」透明方案(现代渲染器按 alpha 通道处理透明)。方案 d05 的细圆环(0.5px)在
|
|
61
|
+
32px 下不足 1 像素、无法渲染,故 ICO 省略圆环、仅保留饱和 ``>_`` 笔划(符合「图标
|
|
62
|
+
为主角、环极弱」的设计意图),完整外观由 SVG 主版承载。
|
|
63
|
+
"""
|
|
64
|
+
import math
|
|
18
65
|
import struct
|
|
19
66
|
|
|
20
|
-
width
|
|
67
|
+
width = height = 32
|
|
68
|
+
scale = width / 24.0 # SVG 24 单位 -> 像素
|
|
69
|
+
|
|
70
|
+
# 图标笔划青绿渐变:#22d3ee -> #2dd4bf(与 _LOGO_DEFS 同源)
|
|
71
|
+
r0, g0, b0 = 0x22, 0xD3, 0xEE
|
|
72
|
+
r1, g1, b1 = 0x2D, 0xD4, 0xBF
|
|
73
|
+
|
|
74
|
+
# 像素缓冲:[B, G, R, A],默认全透明(全透底,无容器填充)
|
|
75
|
+
buf: list[list[list[int]]] = [
|
|
76
|
+
[[0, 0, 0, 0] for _ in range(width)] for _ in range(height)
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
def brand_at(px: float, py: float) -> tuple[int, int, int]:
|
|
80
|
+
"""按对角参数 t 返回 (px,py) 处的青绿渐变 RGB(与 SVG url(#cpBrand) 同向)."""
|
|
81
|
+
t = (px + py) / (width + height - 2)
|
|
82
|
+
return (
|
|
83
|
+
int(r0 + (r1 - r0) * t),
|
|
84
|
+
int(g0 + (g1 - g0) * t),
|
|
85
|
+
int(b0 + (b1 - b0) * t),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def stamp(px: float, py: float) -> None:
|
|
89
|
+
"""以 (px, py) 为中心盖 ~3px 青绿渐变方块(笔划加粗,保证小尺寸可辨识)."""
|
|
90
|
+
ix, iy = int(round(px)), int(round(py))
|
|
91
|
+
cr, cg, cb = brand_at(px, py)
|
|
92
|
+
for oy in (-1, 0, 1):
|
|
93
|
+
for ox in (-1, 0, 1):
|
|
94
|
+
nx, ny = ix + ox, iy + oy
|
|
95
|
+
if 0 <= nx < width and 0 <= ny < height:
|
|
96
|
+
buf[ny][nx] = [cb, cg, cr, 255]
|
|
97
|
+
|
|
98
|
+
def line(x0: float, y0: float, x1: float, y1: float) -> None:
|
|
99
|
+
"""稠密采样 + stamp 形成青绿渐变粗线段."""
|
|
100
|
+
dist = math.hypot(x1 - x0, y1 - y0)
|
|
101
|
+
steps = max(1, int(dist * 3))
|
|
102
|
+
for i in range(steps + 1):
|
|
103
|
+
s = i / steps
|
|
104
|
+
stamp(x0 + (x1 - x0) * s, y0 + (y1 - y0) * s)
|
|
105
|
+
|
|
106
|
+
# prompt 笔划(SVG 24 单位 -> 像素)
|
|
107
|
+
# > 折线 (5,7)->(10,12)->(5,17);_ 下划线 (13,17)->(19,17)
|
|
108
|
+
line(5 * scale, 7 * scale, 10 * scale, 12 * scale)
|
|
109
|
+
line(10 * scale, 12 * scale, 5 * scale, 17 * scale)
|
|
110
|
+
line(13 * scale, 17 * scale, 19 * scale, 17 * scale)
|
|
111
|
+
|
|
112
|
+
# 3) 打包 ICO(BMP bottom-up;全零 AND-mask,信任 per-pixel alpha 实现圆角透明)
|
|
21
113
|
pixel_rows: list[bytes] = []
|
|
22
|
-
cx, cy = width / 2.0, height / 2.0
|
|
23
114
|
for y in range(height - 1, -1, -1): # BMP bottom-up
|
|
24
115
|
row = bytearray()
|
|
25
116
|
for x in range(width):
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
if dx * dx + dy * dy > (width / 2.0) ** 2:
|
|
29
|
-
row.extend([0, 0, 0, 0]) # 圆外透明
|
|
30
|
-
else:
|
|
31
|
-
t = (x + (height - 1 - y)) / (width + height - 2)
|
|
32
|
-
r = int(88 + (188 - 88) * t)
|
|
33
|
-
g = int(166 + (140 - 166) * t)
|
|
34
|
-
b = 255
|
|
35
|
-
row.extend([b, g, r, 255]) # BGRA
|
|
117
|
+
b, g, r, a = buf[y][x]
|
|
118
|
+
row.extend([b, g, r, a]) # BGRA
|
|
36
119
|
pixel_rows.append(bytes(row))
|
|
37
120
|
|
|
38
121
|
bmp_hdr = struct.pack(
|
|
@@ -50,6 +133,7 @@ def _build_favicon() -> bytes:
|
|
|
50
133
|
|
|
51
134
|
|
|
52
135
|
_FAVICON_ICO: bytes = _build_favicon()
|
|
136
|
+
_FAVICON_SVG: str = _build_favicon_svg()
|
|
53
137
|
|
|
54
138
|
logger = logging.getLogger(__name__)
|
|
55
139
|
|
|
@@ -61,21 +145,24 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
61
145
|
<meta charset="UTF-8" />
|
|
62
146
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
63
147
|
<title>Coding Proxy Dashboard</title>
|
|
148
|
+
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
64
149
|
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
|
65
150
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
66
151
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
67
|
-
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet" />
|
|
152
|
+
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&display=swap" rel="stylesheet" />
|
|
68
153
|
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
|
|
69
154
|
<style>
|
|
70
155
|
:root {
|
|
71
156
|
--bg: #0a0e14;
|
|
72
157
|
--bg-card: #12161e;
|
|
73
158
|
--bg-card-hover: #181d27;
|
|
159
|
+
--bg-secondary: #161b24;
|
|
74
160
|
--border: rgba(255,255,255,.06);
|
|
75
161
|
--border-subtle: rgba(255,255,255,.04);
|
|
76
162
|
--text-primary: #e6edf3;
|
|
77
163
|
--text-secondary: #8b949e;
|
|
78
164
|
--text-tertiary: #6e7681;
|
|
165
|
+
--text-muted: #6e7681;
|
|
79
166
|
--accent-blue: #58a6ff;
|
|
80
167
|
--accent-green: #3fb950;
|
|
81
168
|
--accent-yellow: #d29922;
|
|
@@ -117,19 +204,19 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
117
204
|
display: flex;
|
|
118
205
|
align-items: center;
|
|
119
206
|
justify-content: space-between;
|
|
207
|
+
flex-wrap: wrap;
|
|
208
|
+
gap: 8px 16px;
|
|
120
209
|
position: sticky;
|
|
121
210
|
top: 0;
|
|
122
211
|
z-index: 100;
|
|
123
212
|
}
|
|
124
|
-
.header-left { display: flex; align-items: center; gap: 12px; }
|
|
213
|
+
.header-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
|
214
|
+
.header-left h1 { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
125
215
|
.logo {
|
|
126
216
|
width: 32px; height: 32px;
|
|
127
|
-
background: var(--gradient-primary);
|
|
128
|
-
border-radius: 10px;
|
|
129
217
|
display: flex; align-items: center; justify-content: center;
|
|
130
|
-
font-size: 15px; font-weight: 700; color: #fff;
|
|
131
|
-
box-shadow: 0 4px 12px rgba(102,126,234,.25);
|
|
132
218
|
}
|
|
219
|
+
.logo svg { width: 28px; height: 28px; display: block; filter: drop-shadow(0 0 3px rgba(45,212,191,.3)); }
|
|
133
220
|
h1 { font-size: 18px; font-weight: 600; color: var(--text-primary); letter-spacing: -.3px; }
|
|
134
221
|
.header-right { display: flex; align-items: center; gap: 12px; }
|
|
135
222
|
.badge {
|
|
@@ -159,8 +246,8 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
159
246
|
/* ── KPI 卡片 ── */
|
|
160
247
|
.kpi-grid {
|
|
161
248
|
display: grid;
|
|
162
|
-
grid-template-columns: repeat(
|
|
163
|
-
gap:
|
|
249
|
+
grid-template-columns: repeat(6, minmax(0, 1fr));
|
|
250
|
+
gap: var(--gap-section);
|
|
164
251
|
margin-bottom: var(--gap-section);
|
|
165
252
|
}
|
|
166
253
|
.kpi-card {
|
|
@@ -198,12 +285,25 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
198
285
|
.kpi-icon { font-size: 15px; opacity: .8; }
|
|
199
286
|
.kpi-label { font-size: 13px; color: var(--text-secondary); font-weight: 600; letter-spacing: .2px; }
|
|
200
287
|
.kpi-value {
|
|
201
|
-
font-size: 32px; font-weight: 700; line-height: 1.2;
|
|
288
|
+
font-size: clamp(20px, 2.2vw, 32px); font-weight: 700; line-height: 1.2;
|
|
202
289
|
font-family: 'JetBrains Mono', monospace;
|
|
203
290
|
letter-spacing: -1px;
|
|
204
291
|
}
|
|
205
|
-
#kpi-cost-today {
|
|
292
|
+
#kpi-cost-today {
|
|
293
|
+
font-size: clamp(15px, 1.3vw + 0.25rem, 20px);
|
|
294
|
+
white-space: normal;
|
|
295
|
+
word-break: keep-all;
|
|
296
|
+
overflow-wrap: anywhere;
|
|
297
|
+
line-height: 1.25;
|
|
298
|
+
}
|
|
206
299
|
.kpi-sub { font-size: 13px; color: var(--text-tertiary); margin-top: 5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
|
|
300
|
+
/* ── KPI 响应式:桌面/笔记本/平板横屏(≥1024px)强制 6 列单行,杜绝数值裁剪;窄屏优雅降级 ── */
|
|
301
|
+
@media (max-width: 1023px) {
|
|
302
|
+
.kpi-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
303
|
+
}
|
|
304
|
+
@media (max-width: 480px) {
|
|
305
|
+
.kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
|
306
|
+
}
|
|
207
307
|
.color-blue { color: var(--accent-blue); }
|
|
208
308
|
.color-green { color: var(--accent-green); }
|
|
209
309
|
.color-yellow { color: var(--accent-yellow); }
|
|
@@ -250,6 +350,19 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
250
350
|
margin-bottom: 16px;
|
|
251
351
|
display: flex; align-items: center; justify-content: space-between;
|
|
252
352
|
}
|
|
353
|
+
/* 卡片标题栏右侧操作控件(.card-title 的 space-between 自动推至右端) */
|
|
354
|
+
.btn-card-action {
|
|
355
|
+
padding: 4px 10px; border-radius: 6px;
|
|
356
|
+
background: rgba(48,54,61,.4); border: 1px solid rgba(255,255,255,.08);
|
|
357
|
+
color: var(--text-secondary); font-size: 12px; font-weight: 500;
|
|
358
|
+
letter-spacing: 0; cursor: pointer; white-space: nowrap;
|
|
359
|
+
transition: all .15s ease;
|
|
360
|
+
}
|
|
361
|
+
.btn-card-action:hover:not(:disabled) {
|
|
362
|
+
background: var(--bg-card-hover); color: var(--text-primary);
|
|
363
|
+
border-color: rgba(88,166,255,.3);
|
|
364
|
+
}
|
|
365
|
+
.btn-card-action:disabled { opacity: .35; cursor: default; }
|
|
253
366
|
.chart-wrap { position: relative; height: 260px; min-width: 0; }
|
|
254
367
|
.chart-wrap-lg { position: relative; height: 260px; min-width: 0; }
|
|
255
368
|
.chart-wrap-xl { position: relative; height: 280px; min-width: 0; }
|
|
@@ -331,6 +444,17 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
331
444
|
height: 100%; border-radius: 2px;
|
|
332
445
|
transition: width .6s cubic-bezier(.4,0,.2,1);
|
|
333
446
|
}
|
|
447
|
+
/* ── 供应商状态:拖拽排序(Pointer Events,手柄发起) ── */
|
|
448
|
+
.vendor-item.dragging { opacity: .4; }
|
|
449
|
+
.drag-handle {
|
|
450
|
+
display: flex; align-items: center; flex-shrink: 0;
|
|
451
|
+
color: var(--text-tertiary); font-size: 15px; line-height: 1;
|
|
452
|
+
cursor: grab; user-select: none; touch-action: none; padding: 0 2px;
|
|
453
|
+
opacity: 0; transition: opacity .2s ease;
|
|
454
|
+
}
|
|
455
|
+
.drag-handle:active { cursor: grabbing; }
|
|
456
|
+
.vendor-item:hover .drag-handle { opacity: .55; }
|
|
457
|
+
.drag-handle:hover { opacity: 1 !important; color: var(--text-secondary); }
|
|
334
458
|
/* ── 故障转移表 ── */
|
|
335
459
|
.ft-table-wrap { overflow-x: auto; }
|
|
336
460
|
table { width: 100%; border-collapse: collapse; }
|
|
@@ -571,6 +695,11 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
571
695
|
border-color: rgba(88,166,255,.2);
|
|
572
696
|
}
|
|
573
697
|
.tab-btn:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; }
|
|
698
|
+
.range-btn:focus-visible,
|
|
699
|
+
.btn-refresh:focus-visible,
|
|
700
|
+
.page-btn:focus-visible,
|
|
701
|
+
.btn-card-action:focus-visible,
|
|
702
|
+
.copy-btn:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; }
|
|
574
703
|
.tab-pane { display: none; }
|
|
575
704
|
.tab-pane.active { display: block; }
|
|
576
705
|
|
|
@@ -700,12 +829,21 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
700
829
|
0%,100% { color: inherit; }
|
|
701
830
|
40% { color: #f87171; }
|
|
702
831
|
}
|
|
832
|
+
/* ── 尊重「减少动态效果」系统偏好(前庭敏感用户)── */
|
|
833
|
+
@media (prefers-reduced-motion: reduce) {
|
|
834
|
+
.kpi-card, .card { animation: none !important; }
|
|
835
|
+
*, *::before, *::after {
|
|
836
|
+
transition-duration: .01ms !important;
|
|
837
|
+
animation-duration: .01ms !important;
|
|
838
|
+
animation-iteration-count: 1 !important;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
703
841
|
</style>
|
|
704
842
|
</head>
|
|
705
843
|
<body>
|
|
706
844
|
<header>
|
|
707
845
|
<div class="header-left">
|
|
708
|
-
<div class="logo">
|
|
846
|
+
<div class="logo"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="url(#cpBrand)" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">{{LOGO_DEFS}}<circle cx="12" cy="12" r="11" fill="none" stroke="url(#cpBrand)" stroke-width="0.5" stroke-opacity=".55"/><g>{{PROMPT}}</g></svg></div>
|
|
709
847
|
<h1>Coding Proxy Dashboard</h1>
|
|
710
848
|
<span class="badge" id="version-badge">v-.-.-</span>
|
|
711
849
|
</div>
|
|
@@ -780,7 +918,7 @@ _DASHBOARD_HTML = """<!DOCTYPE html>
|
|
|
780
918
|
<!-- 供应商状态 + 请求量趋势折线图 -->
|
|
781
919
|
<div class="charts-grid">
|
|
782
920
|
<div class="card">
|
|
783
|
-
<div class="card-title"
|
|
921
|
+
<div class="card-title">供应商状态<button type="button" class="btn-card-action" id="btn-vendor-reset" onclick="resetVendorStatus(this)" aria-label="复位供应商状态" title="复位所有供应商的熔断 / 限流 / 配额守卫状态(保留额度用量与优先级)">⟲ 状态复位</button></div>
|
|
784
922
|
<div class="vendor-list" id="vendor-list">
|
|
785
923
|
<div class="empty">加载中…</div>
|
|
786
924
|
</div>
|
|
@@ -1252,12 +1390,15 @@ function renderQuotaBar(qg) {
|
|
|
1252
1390
|
}
|
|
1253
1391
|
|
|
1254
1392
|
function updateVendorStatus(status) {
|
|
1393
|
+
// 拖拽进行中 / 重排序 POST 未决时跳过重渲染,避免抢占正在操作的 DOM
|
|
1394
|
+
if (_tierDrag.active || _tierDrag.inFlight) return;
|
|
1255
1395
|
const tiers = status.tiers || [];
|
|
1256
1396
|
const list = document.getElementById('vendor-list');
|
|
1257
1397
|
if (!tiers.length) {
|
|
1258
1398
|
list.innerHTML = '<div class="empty"><div class="empty-icon">🔌</div>无供应商数据</div>';
|
|
1259
1399
|
return;
|
|
1260
1400
|
}
|
|
1401
|
+
const reorderable = tiers.length >= 2;
|
|
1261
1402
|
list.innerHTML = tiers.map(tier => {
|
|
1262
1403
|
const cb = tier.circuit_breaker || {};
|
|
1263
1404
|
const cbClass = cbStateClass(cb.state);
|
|
@@ -1269,10 +1410,15 @@ function updateVendorStatus(status) {
|
|
|
1269
1410
|
if (tier.weekly_quota_guard) quotaHTML += renderQuotaBar(tier.weekly_quota_guard);
|
|
1270
1411
|
|
|
1271
1412
|
const rlInfo = tier.rate_limit || {};
|
|
1272
|
-
const rlHtml = rlInfo.
|
|
1413
|
+
const rlHtml = rlInfo.is_rate_limited ? `<span class="status-badge sb-warn">限速中</span>` : '';
|
|
1273
1414
|
|
|
1274
|
-
|
|
1415
|
+
// Pointer Events 重排:仅需 data-vendor 定位;手柄作为拖拽发起点(无原生 draggable)
|
|
1416
|
+
const dragAttrs = ` data-vendor="${tier.name}"`;
|
|
1417
|
+
const handle = reorderable ? `<div class="drag-handle" title="拖拽调整优先级">⠿</div>` : '';
|
|
1418
|
+
|
|
1419
|
+
return `<div class="vendor-item"${dragAttrs}>
|
|
1275
1420
|
<div class="vendor-info">
|
|
1421
|
+
${handle}
|
|
1276
1422
|
<div class="vendor-avatar">${initial}</div>
|
|
1277
1423
|
<span class="vendor-name">${tier.name}</span>
|
|
1278
1424
|
</div>
|
|
@@ -1285,6 +1431,173 @@ function updateVendorStatus(status) {
|
|
|
1285
1431
|
}).join('');
|
|
1286
1432
|
}
|
|
1287
1433
|
|
|
1434
|
+
// ── 供应商状态:拖拽调整优先级(Pointer Events 重排,运行时生效,不重置配额) ────
|
|
1435
|
+
// 采用 Pointer Events 而非原生 HTML5 DnD:后者触屏不支持、跨浏览器易「拿不起来」,
|
|
1436
|
+
// 是业界公认脆弱的重排序方案(故 SortableJS / dnd-kit 等均改用指针事件)。
|
|
1437
|
+
const _tierDrag = {
|
|
1438
|
+
active: false, // 已越过阈值、进入拖拽
|
|
1439
|
+
srcName: null, // 被拖拽 vendor 名
|
|
1440
|
+
srcEl: null, // 被拖拽行
|
|
1441
|
+
pointerId: null, // 捕获的指针 ID
|
|
1442
|
+
startY: 0, // pointerdown 起点 Y
|
|
1443
|
+
origOrder: null, // 拖拽开始时的顺序快照(无变化则跳过 PUT)
|
|
1444
|
+
inFlight: false, // PUT 未决
|
|
1445
|
+
};
|
|
1446
|
+
const _TIER_DRAG_THRESHOLD = 4; // px,越过才判定为拖拽(否则视作点击)
|
|
1447
|
+
|
|
1448
|
+
function _tierCurrentOrder(listEl) {
|
|
1449
|
+
return Array.from(listEl.querySelectorAll('.vendor-item'))
|
|
1450
|
+
.map(function(el) { return el.dataset.vendor; })
|
|
1451
|
+
.filter(Boolean);
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
// 依据指针 Y 与各兄弟行中点比较,即时(乐观)重排 DOM
|
|
1455
|
+
function _tierDragMoveTo(listEl, clientY) {
|
|
1456
|
+
const dragged = _tierDrag.srcEl;
|
|
1457
|
+
if (!dragged) return;
|
|
1458
|
+
const siblings = Array.from(listEl.querySelectorAll('.vendor-item'))
|
|
1459
|
+
.filter(function(el) { return el !== dragged; });
|
|
1460
|
+
for (var i = 0; i < siblings.length; i++) {
|
|
1461
|
+
const rect = siblings[i].getBoundingClientRect();
|
|
1462
|
+
if (clientY < rect.top + rect.height / 2) {
|
|
1463
|
+
if (dragged !== siblings[i] && dragged.nextElementSibling !== siblings[i]) {
|
|
1464
|
+
listEl.insertBefore(dragged, siblings[i]);
|
|
1465
|
+
}
|
|
1466
|
+
return;
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
if (listEl.lastElementChild !== dragged) listEl.appendChild(dragged); // 落到末尾
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
function _tierDragReset() {
|
|
1473
|
+
if (_tierDrag.srcEl) {
|
|
1474
|
+
if (_tierDrag.pointerId != null) {
|
|
1475
|
+
try { _tierDrag.srcEl.releasePointerCapture(_tierDrag.pointerId); } catch (_) {}
|
|
1476
|
+
}
|
|
1477
|
+
_tierDrag.srcEl.classList.remove('dragging');
|
|
1478
|
+
}
|
|
1479
|
+
_tierDrag.active = false;
|
|
1480
|
+
_tierDrag.srcName = null;
|
|
1481
|
+
_tierDrag.srcEl = null;
|
|
1482
|
+
_tierDrag.pointerId = null;
|
|
1483
|
+
_tierDrag.startY = 0;
|
|
1484
|
+
_tierDrag.origOrder = null;
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
function initTierDrag() {
|
|
1488
|
+
// 指针事件委托绑定在静态容器 #vendor-list 上一次;子节点重渲染后仍生效
|
|
1489
|
+
const list = document.getElementById('vendor-list');
|
|
1490
|
+
if (!list || list.dataset.dndBound === '1') return;
|
|
1491
|
+
list.dataset.dndBound = '1';
|
|
1492
|
+
|
|
1493
|
+
list.addEventListener('pointerdown', function(e) {
|
|
1494
|
+
if (e.button != null && e.button !== 0) return; // 仅主指针/左键
|
|
1495
|
+
const handle = e.target && e.target.closest && e.target.closest('.drag-handle');
|
|
1496
|
+
if (!handle) return; // 仅从手柄发起,避免误触与文本选择
|
|
1497
|
+
const item = handle.closest('.vendor-item');
|
|
1498
|
+
if (!item || !item.dataset.vendor) return;
|
|
1499
|
+
if (list.querySelectorAll('.vendor-item').length < 2) return;
|
|
1500
|
+
_tierDrag.srcEl = item;
|
|
1501
|
+
_tierDrag.srcName = item.dataset.vendor;
|
|
1502
|
+
_tierDrag.pointerId = e.pointerId;
|
|
1503
|
+
_tierDrag.startY = e.clientY;
|
|
1504
|
+
try { item.setPointerCapture(e.pointerId); } catch (_) {} // 捕获后 DOM 重排不丢事件
|
|
1505
|
+
e.preventDefault(); // 阻止文本选择
|
|
1506
|
+
});
|
|
1507
|
+
|
|
1508
|
+
list.addEventListener('pointermove', function(e) {
|
|
1509
|
+
if (!_tierDrag.srcEl || e.pointerId !== _tierDrag.pointerId) return;
|
|
1510
|
+
if (!_tierDrag.active) {
|
|
1511
|
+
if (Math.abs(e.clientY - _tierDrag.startY) < _TIER_DRAG_THRESHOLD) return;
|
|
1512
|
+
_tierDrag.active = true; // 越阈值 → 正式进入拖拽
|
|
1513
|
+
_tierDrag.origOrder = _tierCurrentOrder(list);
|
|
1514
|
+
_tierDrag.srcEl.classList.add('dragging');
|
|
1515
|
+
}
|
|
1516
|
+
e.preventDefault();
|
|
1517
|
+
_tierDragMoveTo(list, e.clientY);
|
|
1518
|
+
});
|
|
1519
|
+
|
|
1520
|
+
function _tierDragFinish(commit) {
|
|
1521
|
+
if (!_tierDrag.srcEl) return;
|
|
1522
|
+
const wasActive = _tierDrag.active;
|
|
1523
|
+
const order = _tierCurrentOrder(list);
|
|
1524
|
+
const orig = _tierDrag.origOrder;
|
|
1525
|
+
_tierDragReset();
|
|
1526
|
+
if (!wasActive) return; // 仅点击手柄未拖动 → 空操作
|
|
1527
|
+
if (!commit) { _tierRevertToList(); return; } // 取消 → 回滚服务端真实顺序
|
|
1528
|
+
if (orig && order.join(',') === orig.join(',')) return; // 顺序未变 → 跳过 PUT
|
|
1529
|
+
persistTierOrder(order); // 提交新顺序(PUT + 失败回滚)
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
list.addEventListener('pointerup', function(e) {
|
|
1533
|
+
if (!_tierDrag.srcEl || e.pointerId !== _tierDrag.pointerId) return;
|
|
1534
|
+
_tierDragFinish(true);
|
|
1535
|
+
});
|
|
1536
|
+
list.addEventListener('pointercancel', function(e) {
|
|
1537
|
+
if (!_tierDrag.srcEl || e.pointerId !== _tierDrag.pointerId) return;
|
|
1538
|
+
_tierDragFinish(false);
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
function persistTierOrder(names) {
|
|
1543
|
+
if (_tierDrag.inFlight) return; // 防并发:上一次未决则忽略
|
|
1544
|
+
if (!Array.isArray(names) || names.length < 2) return;
|
|
1545
|
+
_tierDrag.inFlight = true;
|
|
1546
|
+
fetch('/api/tier-order', {
|
|
1547
|
+
method: 'PUT',
|
|
1548
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1549
|
+
body: JSON.stringify({ vendors: names })
|
|
1550
|
+
}).then(function(res) {
|
|
1551
|
+
_tierDrag.inFlight = false; // 先清守卫,允许随后的 refreshOverview 重渲染
|
|
1552
|
+
if (res.ok) {
|
|
1553
|
+
// 服务端已更新顺序;刷新以同步请求趋势图等的排序
|
|
1554
|
+
if (!_tierDrag.active) refreshOverview().catch(function() {});
|
|
1555
|
+
} else {
|
|
1556
|
+
console.error('tier-order rejected:', res.status);
|
|
1557
|
+
_tierRevertToList();
|
|
1558
|
+
}
|
|
1559
|
+
}).catch(function(e) {
|
|
1560
|
+
_tierDrag.inFlight = false;
|
|
1561
|
+
console.error('tier-order failed:', e);
|
|
1562
|
+
_tierRevertToList();
|
|
1563
|
+
});
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
function _tierRevertToList() {
|
|
1567
|
+
// 回滚到服务端真实顺序(PUT 失败 → 服务端顺序未变)
|
|
1568
|
+
fetchJSON('/api/status').then(function(status) {
|
|
1569
|
+
updateVendorStatus(status);
|
|
1570
|
+
}).catch(function() {});
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
// ── 供应商状态:一键复位(熔断 / 限流 / 配额守卫状态;不动额度用量与优先级)────
|
|
1574
|
+
var _vendorResetInFlight = false;
|
|
1575
|
+
function resetVendorStatus(btn) {
|
|
1576
|
+
if (_vendorResetInFlight) return; // 防并发,同 persistTierOrder 范式
|
|
1577
|
+
_vendorResetInFlight = true;
|
|
1578
|
+
var label = btn.textContent;
|
|
1579
|
+
btn.disabled = true;
|
|
1580
|
+
btn.textContent = '复位中…';
|
|
1581
|
+
// 无 body → 服务端跳过重排序,仅对全部 tier 复位弹性设施状态
|
|
1582
|
+
fetch('/api/reset', { method: 'POST' }).then(function(res) {
|
|
1583
|
+
if (!res.ok) throw new Error(res.status);
|
|
1584
|
+
btn.textContent = '✓ 已复位';
|
|
1585
|
+
// 复位已生效,状态刷新失败不应误报失败、诱导重复点击 → 单独吞掉
|
|
1586
|
+
return fetchJSON('/api/status').then(function(status) {
|
|
1587
|
+
updateVendorStatus(status); // 定向重渲染,不等 10 分钟轮询
|
|
1588
|
+
}).catch(function() {});
|
|
1589
|
+
}).catch(function(e) {
|
|
1590
|
+
console.error('vendor reset failed:', e);
|
|
1591
|
+
btn.textContent = '✗ 失败';
|
|
1592
|
+
}).finally(function() {
|
|
1593
|
+
setTimeout(function() {
|
|
1594
|
+
btn.textContent = label;
|
|
1595
|
+
btn.disabled = false;
|
|
1596
|
+
_vendorResetInFlight = false;
|
|
1597
|
+
}, 1500);
|
|
1598
|
+
});
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1288
1601
|
// ── Model Calling 实时状态 ────────────────────────────────
|
|
1289
1602
|
function updateModelCalling(status) {
|
|
1290
1603
|
var wrap = document.getElementById('model-calling-wrap');
|
|
@@ -2120,6 +2433,7 @@ function switchTab(name) {
|
|
|
2120
2433
|
fetchJSON('/api/dashboard/summary?days=7').then(function(s) {
|
|
2121
2434
|
if (s && s.version) document.getElementById('version-badge').textContent = 'v' + s.version;
|
|
2122
2435
|
}).catch(function(){});
|
|
2436
|
+
initTierDrag(); // 绑定供应商列表拖拽(事件委托,幂等)
|
|
2123
2437
|
refresh(); // 仅加载初始页签的数据
|
|
2124
2438
|
setInterval(refresh, 600000); // 每 10 分钟刷新当前页签
|
|
2125
2439
|
if (initial === 'overview') startModelCallingPoll();
|
|
@@ -2127,7 +2441,7 @@ function switchTab(name) {
|
|
|
2127
2441
|
</script>
|
|
2128
2442
|
</body>
|
|
2129
2443
|
</html>
|
|
2130
|
-
"""
|
|
2444
|
+
""".replace("{{PROMPT}}", _PROMPT_PATHS).replace("{{LOGO_DEFS}}", _LOGO_DEFS)
|
|
2131
2445
|
|
|
2132
2446
|
|
|
2133
2447
|
# ── 数据计算工具 ──────────────────────────────────────────────────────────
|
|
@@ -2204,10 +2518,20 @@ def register_dashboard_routes(app: Any) -> None:
|
|
|
2204
2518
|
"""返回内嵌 favicon."""
|
|
2205
2519
|
return Response(content=_FAVICON_ICO, media_type="image/x-icon")
|
|
2206
2520
|
|
|
2521
|
+
@app.get("/favicon.svg", include_in_schema=False)
|
|
2522
|
+
async def favicon_svg() -> Response:
|
|
2523
|
+
"""返回 SVG favicon(现代浏览器优先)."""
|
|
2524
|
+
return Response(content=_FAVICON_SVG, media_type="image/svg+xml")
|
|
2525
|
+
|
|
2207
2526
|
@app.get("/dashboard", response_class=HTMLResponse, include_in_schema=False)
|
|
2208
2527
|
async def dashboard() -> HTMLResponse:
|
|
2209
|
-
"""返回 Dashboard HTML 页面.
|
|
2210
|
-
|
|
2528
|
+
"""返回 Dashboard HTML 页面.
|
|
2529
|
+
|
|
2530
|
+
内联 JS/CSS 随版本变化,禁用缓存以免浏览器留存旧内联脚本掩盖前端修复。
|
|
2531
|
+
"""
|
|
2532
|
+
return HTMLResponse(
|
|
2533
|
+
content=_DASHBOARD_HTML, headers={"Cache-Control": "no-cache"}
|
|
2534
|
+
)
|
|
2211
2535
|
|
|
2212
2536
|
@app.get("/api/dashboard/summary")
|
|
2213
2537
|
async def dashboard_summary(request: Request, days: int = 7) -> Response:
|
coding/proxy/server/routes.py
CHANGED
|
@@ -386,6 +386,53 @@ def register_admin_routes(app: Any, router: Any) -> None:
|
|
|
386
386
|
)
|
|
387
387
|
|
|
388
388
|
|
|
389
|
+
def register_tier_order_route(app: Any, router: Any) -> None:
|
|
390
|
+
"""注册运行时 N-tier 链路顺序调整路由(纯重排序,不重置熔断器/配额守卫)."""
|
|
391
|
+
|
|
392
|
+
@app.put("/api/tier-order")
|
|
393
|
+
async def update_tier_order(request: Request) -> Response:
|
|
394
|
+
"""替换整个 N-tier 链路顺序.
|
|
395
|
+
|
|
396
|
+
JSON body: ``{"vendors": ["v1", "v2", ...]}``(需覆盖所有当前启用的 vendor)。
|
|
397
|
+
与 ``/api/reset`` 的重排序语义一致,但**不会**重置熔断器/配额守卫/rate limit,
|
|
398
|
+
以保留当日用量统计(供 Web 拖拽调整优先级使用)。
|
|
399
|
+
"""
|
|
400
|
+
try:
|
|
401
|
+
body = await request.json()
|
|
402
|
+
except Exception:
|
|
403
|
+
return json_error_response(
|
|
404
|
+
400, error_type="invalid_request_error", message="body must be JSON"
|
|
405
|
+
)
|
|
406
|
+
if not isinstance(body, dict):
|
|
407
|
+
return json_error_response(
|
|
408
|
+
400,
|
|
409
|
+
error_type="invalid_request_error",
|
|
410
|
+
message="body must be a JSON object",
|
|
411
|
+
)
|
|
412
|
+
raw = body.get("vendors")
|
|
413
|
+
if not isinstance(raw, list) or not raw:
|
|
414
|
+
return json_error_response(
|
|
415
|
+
400,
|
|
416
|
+
error_type="invalid_request_error",
|
|
417
|
+
message="requires non-empty 'vendors' list",
|
|
418
|
+
)
|
|
419
|
+
vendor_names = [str(v) for v in raw]
|
|
420
|
+
try:
|
|
421
|
+
router.reorder_tiers(vendor_names)
|
|
422
|
+
except ValueError as exc:
|
|
423
|
+
return json_error_response(
|
|
424
|
+
400, error_type="invalid_request_error", message=str(exc)
|
|
425
|
+
)
|
|
426
|
+
return Response(
|
|
427
|
+
content=json.dumps(
|
|
428
|
+
{"ok": True, "tier_order": router.get_vendor_names()},
|
|
429
|
+
ensure_ascii=False,
|
|
430
|
+
).encode(),
|
|
431
|
+
status_code=200,
|
|
432
|
+
media_type="application/json",
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
|
|
389
436
|
def register_session_vendor_routes(app: Any, router: Any) -> None:
|
|
390
437
|
"""注册 Session-Vendor 运行时绑定路由."""
|
|
391
438
|
|
|
@@ -518,6 +565,7 @@ def register_all_routes(
|
|
|
518
565
|
register_concurrency_route(app, router)
|
|
519
566
|
register_copilot_routes(app, router)
|
|
520
567
|
register_admin_routes(app, router)
|
|
568
|
+
register_tier_order_route(app, router)
|
|
521
569
|
register_session_vendor_routes(app, router)
|
|
522
570
|
if reauth_coordinator:
|
|
523
571
|
register_reauth_routes(app, reauth_coordinator)
|
|
@@ -24,6 +24,7 @@ from .base import (
|
|
|
24
24
|
VendorCapabilities,
|
|
25
25
|
VendorResponse,
|
|
26
26
|
_sanitize_headers_for_synthetic_response,
|
|
27
|
+
decode_error_body,
|
|
27
28
|
)
|
|
28
29
|
|
|
29
30
|
# GoogleOAuthTokenManager 已从 antigravity_token_manager.py 合并至本文件末尾
|
|
@@ -532,14 +533,16 @@ class AntigravityVendor(TokenBackendMixin, BaseVendor):
|
|
|
532
533
|
if response.status_code >= 400:
|
|
533
534
|
self._on_error_status(response.status_code)
|
|
534
535
|
error_body = await response.aread()
|
|
536
|
+
# 检测用完整解码文本(判定性逻辑不应受日志展示上限影响);
|
|
537
|
+
# 日志展示则用 decode_error_body 的 500 字符截断版本。
|
|
535
538
|
self._mark_scope_error_if_needed(
|
|
536
|
-
error_body.decode("utf-8", errors="
|
|
539
|
+
error_body.decode("utf-8", errors="replace"),
|
|
537
540
|
)
|
|
538
541
|
logger.warning(
|
|
539
542
|
"%s stream error: status=%d body=%s",
|
|
540
543
|
self.get_name(),
|
|
541
544
|
response.status_code,
|
|
542
|
-
error_body
|
|
545
|
+
decode_error_body(error_body),
|
|
543
546
|
)
|
|
544
547
|
raise httpx.HTTPStatusError(
|
|
545
548
|
f"{self.get_name()} API error: {response.status_code}",
|
coding/proxy/vendors/base.py
CHANGED
|
@@ -25,6 +25,7 @@ from ..model.vendor import ( # noqa: F401
|
|
|
25
25
|
UsageInfo,
|
|
26
26
|
VendorCapabilities,
|
|
27
27
|
VendorResponse,
|
|
28
|
+
decode_error_body,
|
|
28
29
|
decode_json_body,
|
|
29
30
|
extract_error_message,
|
|
30
31
|
sanitize_headers_for_synthetic_response,
|
|
@@ -328,7 +329,7 @@ class BaseVendor(ABC):
|
|
|
328
329
|
"%s stream error: status=%d body=%s",
|
|
329
330
|
self.get_name(),
|
|
330
331
|
response.status_code,
|
|
331
|
-
error_body
|
|
332
|
+
decode_error_body(error_body),
|
|
332
333
|
)
|
|
333
334
|
raise httpx.HTTPStatusError(
|
|
334
335
|
f"{self.get_name()} API error: {response.status_code}",
|
coding/proxy/vendors/copilot.py
CHANGED
|
@@ -25,6 +25,7 @@ from .base import (
|
|
|
25
25
|
VendorResponse,
|
|
26
26
|
_decode_json_body,
|
|
27
27
|
_extract_error_message,
|
|
28
|
+
decode_error_body,
|
|
28
29
|
)
|
|
29
30
|
from .copilot_models import ( # noqa: F401
|
|
30
31
|
CopilotMisdirectedRequest,
|
|
@@ -423,7 +424,7 @@ class CopilotVendor(TokenBackendMixin, BaseVendor):
|
|
|
423
424
|
"%s stream error: status=%d body=%s",
|
|
424
425
|
self.get_name(),
|
|
425
426
|
response.status_code,
|
|
426
|
-
error_body
|
|
427
|
+
decode_error_body(error_body),
|
|
427
428
|
)
|
|
428
429
|
raise httpx.HTTPStatusError(
|
|
429
430
|
f"{self.get_name()} API error: {response.status_code}",
|
coding/proxy/vendors/zhipu.py
CHANGED
|
@@ -16,7 +16,7 @@ Anthropic Messages API 协议,本模块做以下适配:
|
|
|
16
16
|
额外提供 429/529 专用重试挽回机制:
|
|
17
17
|
- 429 Rate Limit(限流)与 529 Overloaded(并发过载)共用同一退避策略
|
|
18
18
|
- max_attempt = 5(1 初始 + 4 重试)
|
|
19
|
-
- 指数退避 +
|
|
19
|
+
- 指数退避 + Equal Jitter(区间 0.5–1s → 1–2s → 2–4s → 4–8s)
|
|
20
20
|
- 优先尊重 server retry-after header
|
|
21
21
|
|
|
22
22
|
并发限流由 BaseVendor._concurrency_controller 统一管控
|
|
@@ -238,7 +238,7 @@ class ZhipuVendor(NativeAnthropicVendor):
|
|
|
238
238
|
以"限流退避"语义(429)解析 header:``parse_rate_limit_headers``
|
|
239
239
|
仅对 429/403 解析 retry-after,故此处固定传 429,
|
|
240
240
|
使 529 也能尊重 server retry-after,与 429 行为一致。
|
|
241
|
-
无 server 信号时回退到指数退避 +
|
|
241
|
+
无 server 信号时回退到指数退避 + Equal Jitter。
|
|
242
242
|
"""
|
|
243
243
|
rl_info = parse_rate_limit_headers(headers, 429, None)
|
|
244
244
|
server_delay_s = compute_effective_retry_seconds(rl_info)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: coding-proxy
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.2
|
|
4
4
|
Summary: A High-Availability, Transparent, and Smart Multi-Vendor Proxy for Claude Code. Support Claude Plans, GitHub Copilot, Google Antigravity, ZAI/GLM, MiniMax, Qwen, Xiaomi, Kimi, Doubao...
|
|
5
5
|
Project-URL: Source Code, https://github.com/ThreeFish-AI/coding-proxy
|
|
6
6
|
Project-URL: User Guide, https://github.com/ThreeFish-AI/coding-proxy/blob/master/docs/user-guide.md
|
|
@@ -29,7 +29,7 @@ Description-Content-Type: text/markdown
|
|
|
29
29
|
|
|
30
30
|
<div align="center">
|
|
31
31
|
|
|
32
|
-
#
|
|
32
|
+
# <img src="assets/logo.svg" alt="coding-proxy" width="32" height="32" align="absmiddle"> coding-proxy
|
|
33
33
|
|
|
34
34
|
**A High-Availability, Transparent, and Smart Multi-Vendor Proxy for Claude Code**
|
|
35
35
|
|
|
@@ -152,7 +152,7 @@ graph RL
|
|
|
152
152
|
|
|
153
153
|
Client["💻<br/>Client (Claude Code)"]:::client
|
|
154
154
|
|
|
155
|
-
subgraph CodingProxy["
|
|
155
|
+
subgraph CodingProxy["coding-proxy"]
|
|
156
156
|
direction RL
|
|
157
157
|
|
|
158
158
|
Router["RequestRouter<br/><code>routing/router.py</code>"]:::router
|
|
@@ -202,7 +202,6 @@ To ensure this project outlives us all (long-term maintainability), we offer exh
|
|
|
202
202
|
|
|
203
203
|
- 📖 **[User Guide](./docs/user-guide.md)** — From installation and bare-minimum configs to the semantic breakdown of every `config.yaml` field and common troubleshooting manuals. (Currently in Chinese)
|
|
204
204
|
- 🏗️ **[Architecture Framework](./docs/framework.md)** — A meticulous decoding of underlying design patterns (Template Method, Circuit Breaker, State Machine, etc.), targeted at devs who want to peek into the matrix or contribute new vendors. (Currently in Chinese)
|
|
205
|
-
- 🤝 **[Engineering Guidelines (AGENTS.md)](./AGENTS.md)** — The systemic context mindset and AI Agent collaboration protocol. It preaches **refactoring, reuse, and orthogonal abstractions** and serves as the ultimate guiding light for all development in this repository.
|
|
206
205
|
|
|
207
206
|
---
|
|
208
207
|
|
|
@@ -216,5 +215,5 @@ During our chaotic yet rewarding exploration of engineering practices, we were h
|
|
|
216
215
|
---
|
|
217
216
|
|
|
218
217
|
<div align="center">
|
|
219
|
-
<sub>Built with 🧠, ❤️, and an absurd amount of coffee by ThreeFish-AI </sub>
|
|
218
|
+
<sub>Built with 🧠, ❤️, and an absurd amount of coffee by <a href="https://github.com/ThreeFish-AI">ThreeFish-AI</a> · Released under the <a href="./LICENSE">Apache License 2.0</a>.</sub>
|
|
220
219
|
</div>
|
|
@@ -17,13 +17,13 @@ coding/proxy/compat/canonical.py,sha256=-zcuEwZ402xeH3C545RmuYRkT2HDuvFloyFydDv8
|
|
|
17
17
|
coding/proxy/compat/session_store.py,sha256=B9IFjjQJnHMg1244m__jG9gnqGWi26-JyEtwopEri6Q,5244
|
|
18
18
|
coding/proxy/config/__init__.py,sha256=hzgU5noJGecjj13UY38cC_p6jpWO3GO7okSW-A2XkJ0,127
|
|
19
19
|
coding/proxy/config/auth_schema.py,sha256=LYrJQU_fgW-6AoQdjXt4-MgPJjXjv9HrghlCcZwotnA,696
|
|
20
|
-
coding/proxy/config/config.default.yaml,sha256=
|
|
20
|
+
coding/proxy/config/config.default.yaml,sha256=TKIHDUb4uS0zc-c-I-ix_fK3MEGuI-PABPoOc-6kPio,23717
|
|
21
21
|
coding/proxy/config/loader.py,sha256=1J_RBJgjuC8RwB2mwewLMS7vy9WEhUqttZG2igeDm-w,8984
|
|
22
22
|
coding/proxy/config/resiliency.py,sha256=GnzY-LoyfFqXFM1l6xEru418v-cKlv97-HM0noGPdks,1308
|
|
23
23
|
coding/proxy/config/routing.py,sha256=MWTUq6QaYDmoXEARN9EBAptC6TSGK2yezNiaVk3kaXY,12196
|
|
24
24
|
coding/proxy/config/schema.py,sha256=q1mlpnSMoVneDqzCSBR88xCgKG6aVu11ikdbMzWM27I,13542
|
|
25
25
|
coding/proxy/config/server.py,sha256=4yY7i3WYOjtyZtZqHMtkjqHZ2W6D_ffEwVIfzxRar90,1002
|
|
26
|
-
coding/proxy/config/session_policy.py,sha256=
|
|
26
|
+
coding/proxy/config/session_policy.py,sha256=0aV6bXKAyS5CkiVH3z4sBNksghaioyOwk3Zql3Gu10k,4356
|
|
27
27
|
coding/proxy/config/vendors.py,sha256=9_Pgj9U6zOZVUV3UlA9P8BlKSDlj34g4p0lCy_bdimE,3472
|
|
28
28
|
coding/proxy/convert/__init__.py,sha256=0D3Q9TdY_AWCaMMf9f_i3jn0RIiWmqlcIAA79Ki8uJc,458
|
|
29
29
|
coding/proxy/convert/anthropic_to_gemini.py,sha256=9mRQ0CRAGJyWQADNlfMqoCJ_vY8ZZBGWaS_R8Vbe_l0,13201
|
|
@@ -36,13 +36,13 @@ coding/proxy/logging/__init__.py,sha256=6zEh2CELMJ5aZvM6PNCOFlZ55De8xoC6QNyMAa9W
|
|
|
36
36
|
coding/proxy/logging/db.py,sha256=gXWryj_kuUxRlLXpcvKuK1z9n_da9o-zB8qn9sd3-qg,28234
|
|
37
37
|
coding/proxy/logging/formatters.py,sha256=8LDqiNAxGcfn9fsHqZzdK9TKGqOGNAOls75B1byBjnM,823
|
|
38
38
|
coding/proxy/logging/stats.py,sha256=jDQWFiqrj5IXtCM_tt2iykCzOdqq22_HaE8d9e__p30,12316
|
|
39
|
-
coding/proxy/model/__init__.py,sha256=
|
|
39
|
+
coding/proxy/model/__init__.py,sha256=cwGwy35mJzwN_6Q5B9nCUhzJ_Idg97D3G4Nc1PLOEQg,3995
|
|
40
40
|
coding/proxy/model/auth.py,sha256=NiiIPdLdxPtuHNrsGoxFASUXwJU5pkDuVRorQe_1Z-Q,934
|
|
41
41
|
coding/proxy/model/compat.py,sha256=D1ngBbtQb39cbtCsmxbMBiH8Hyu3rVU-fZPB_4TBj6M,5120
|
|
42
42
|
coding/proxy/model/constants.py,sha256=rDCG9kZMkwlfrxlt0HGU-SkC2oxqlVw_Yva6s-lQZmQ,1038
|
|
43
43
|
coding/proxy/model/pricing.py,sha256=nmwsJK4XRBsKYt_1LQsjMXkA9uIjqev4b5fSJANmPQc,1814
|
|
44
44
|
coding/proxy/model/token.py,sha256=yCh-66_nFDAk7wKbYy-9ymdgae3SaJ47-fkYfYLO3Oo,1818
|
|
45
|
-
coding/proxy/model/vendor.py,sha256=
|
|
45
|
+
coding/proxy/model/vendor.py,sha256=1X3a3Z4989c0ejPThNIawQIj53P7Wd0qwtaCL1Y6x-k,8643
|
|
46
46
|
coding/proxy/native_api/__init__.py,sha256=tnsl69cAolOirVsz7M04duXV9HCVXRDX4DAj6A1Xw-c,3008
|
|
47
47
|
coding/proxy/native_api/config.py,sha256=oh5jtLRJ2dMqV1d3bNHNQ4wxL-cL3GlFallQMEkuRTM,4266
|
|
48
48
|
coding/proxy/native_api/handler.py,sha256=Vb4CsO5xl8yoBf_R3aLMfCoTZQuuyKA0mdJfDFArHXk,30016
|
|
@@ -56,32 +56,32 @@ coding/proxy/native_api/extractors/openai.py,sha256=bPdkcR_2g7zb-F8P7CGumVqv_chR
|
|
|
56
56
|
coding/proxy/routing/__init__.py,sha256=2Tpc6MQ5Oy_w-YlEWQVDSgcSgiHp3OwKOABIjj5kfHA,1595
|
|
57
57
|
coding/proxy/routing/circuit_breaker.py,sha256=hOyoY_RWB5dTVbipyuiWfAelnva3cZRLbXrSmSn8KTs,8096
|
|
58
58
|
coding/proxy/routing/error_classifier.py,sha256=SoJsExbfzduBOC04tKv9RdQqkzA-tQxbPapU5duNJqA,4204
|
|
59
|
-
coding/proxy/routing/executor.py,sha256=
|
|
59
|
+
coding/proxy/routing/executor.py,sha256=PCj4yvMccGZu99ZrOjJ1aeiAmapeYUBVBCqG0ZmKCt0,60473
|
|
60
60
|
coding/proxy/routing/model_mapper.py,sha256=yc5PW7c9x6wfs7wGdbm-G5pFwg-kPTim6A2mKZ3sQgc,2803
|
|
61
|
-
coding/proxy/routing/quota_guard.py,sha256=
|
|
61
|
+
coding/proxy/routing/quota_guard.py,sha256=e8e-TQJvizv996QpoXHP2jKnDeV4Cem_HQY7DBxvbZY,9129
|
|
62
62
|
coding/proxy/routing/rate_limit.py,sha256=i2cCqtbmXrP6wjRUTWXLP4DdYwVj0C4o59QdYGkPQj0,5122
|
|
63
|
-
coding/proxy/routing/retry.py,sha256=
|
|
64
|
-
coding/proxy/routing/router.py,sha256=
|
|
63
|
+
coding/proxy/routing/retry.py,sha256=iRtuMSwXgGi_FPRi5mopTicdbEs_xrrKCXs83QjCz1c,2912
|
|
64
|
+
coding/proxy/routing/router.py,sha256=qqI3-cqdwArnBr0d8L0rLlkisu4HRsxhs-PwZAY8TiA,6311
|
|
65
65
|
coding/proxy/routing/session_manager.py,sha256=GXeqLmHBlbcK49vNV_fDZnW8pVumeTJkiDB3ijKIsow,3145
|
|
66
66
|
coding/proxy/routing/session_policy.py,sha256=U46jidS3y7MgfcIQtOa8k0SBnkdRO0Jybe3ph4q-br4,4725
|
|
67
67
|
coding/proxy/routing/tier.py,sha256=OBrJiMxfLCxXvZfARD5oNmuhpYASKnyrW9sOCHLdQ1g,7777
|
|
68
68
|
coding/proxy/routing/usage_parser.py,sha256=ZwPuMGtXAwdIOKrXLpdtA4nCmc83ViF6kw5JnivRC6s,10426
|
|
69
69
|
coding/proxy/routing/usage_recorder.py,sha256=PHUHotCt3VaKkdJizMpPGsUOAj-f5qz9JKeiLEnFNgA,8779
|
|
70
70
|
coding/proxy/server/__init__.py,sha256=KeH7mEu36v9v27m3VgeSxSeFz9sLTJrxS_EVATJ7Vks,20
|
|
71
|
-
coding/proxy/server/app.py,sha256=
|
|
72
|
-
coding/proxy/server/dashboard.py,sha256=
|
|
71
|
+
coding/proxy/server/app.py,sha256=3MYE8-Vsxpt1SVqTKReMKNREBsh_LHKIFq1B4jhfeL8,7121
|
|
72
|
+
coding/proxy/server/dashboard.py,sha256=srt75I9EO586mEtQw7OhPkBwulO7xIAVHmj_hWvBTUw,108257
|
|
73
73
|
coding/proxy/server/factory.py,sha256=L0d0AA0fpkV-gynM85u1l5dXY1OQ5A_p_-PV0XlFGQs,10272
|
|
74
74
|
coding/proxy/server/responses.py,sha256=i0ugnLRNOdRYGHEWxkwsxR35ChmdMQsSaD8AjRluTn4,2167
|
|
75
|
-
coding/proxy/server/routes.py,sha256=
|
|
75
|
+
coding/proxy/server/routes.py,sha256=5f9ONVckM3LG2AftBW6YahelhjkP6XlgaYSH7MvXUp4,22362
|
|
76
76
|
coding/proxy/streaming/__init__.py,sha256=0al5TC-zJt8Bz0CibTmd8WPza-Cs-qcuZWvT2fKPqHI,23
|
|
77
77
|
coding/proxy/streaming/anthropic_compat.py,sha256=cycYiJ-glN88OmfLTR7FroHRethONlEcK0PT78KqGbA,21202
|
|
78
78
|
coding/proxy/vendors/__init__.py,sha256=fehSpQ2-kUlZY6N8cNMGVJYMXspQmi3V4e0FgC4Ay4k,1011
|
|
79
79
|
coding/proxy/vendors/alibaba.py,sha256=vYhvk8hZEeOpqUrtGT-uaK89y6uolrDUAT2BvTD_IQY,876
|
|
80
80
|
coding/proxy/vendors/anthropic.py,sha256=1l6c4w0OHER0i8a81C9Z74lx1myQ2ut4lRo_58yY1m0,4221
|
|
81
|
-
coding/proxy/vendors/antigravity.py,sha256=
|
|
82
|
-
coding/proxy/vendors/base.py,sha256=
|
|
81
|
+
coding/proxy/vendors/antigravity.py,sha256=sjQP6NfpaXrsJs_RcVJW7xhmXBM4tOCIRrQlRZCQBkM,22740
|
|
82
|
+
coding/proxy/vendors/base.py,sha256=hKagGqLKuEUAU74NLAHjNRFvtJEZlGTJXcQTe9IOAKs,15872
|
|
83
83
|
coding/proxy/vendors/concurrency.py,sha256=KSMlBDTmz--Mf7-i2hBtc16bMLVvrSW_SEpVQKNKzNg,8271
|
|
84
|
-
coding/proxy/vendors/copilot.py,sha256=
|
|
84
|
+
coding/proxy/vendors/copilot.py,sha256=n-dDCSD6XFbiBq6XjyK66VzhQtSPbLH4NIg25SKWIGU,29626
|
|
85
85
|
coding/proxy/vendors/copilot_models.py,sha256=UckIQYA4qLyNwEA09koQGBOZ65Nxhuo3ytUuDNqtzRU,15514
|
|
86
86
|
coding/proxy/vendors/copilot_token_manager.py,sha256=_sZBSFr4sFF2BuP-ZWexQxbN3R8TZs9CJ_d62LvyeBw,6710
|
|
87
87
|
coding/proxy/vendors/copilot_urls.py,sha256=YxaR6zmPdrySzsotJx6PjNIu2JIGG6N1D8kZs77oUCM,404
|
|
@@ -92,9 +92,9 @@ coding/proxy/vendors/mixins.py,sha256=eZd_vlsPCKUNOEWSxWTDDb5i24GUIE3_JZDsj5LMr0
|
|
|
92
92
|
coding/proxy/vendors/native_anthropic.py,sha256=SxtM71PDci0gqLqiwCrFnT410SnSoD7FhLwcZuGB8tU,10074
|
|
93
93
|
coding/proxy/vendors/token_manager.py,sha256=s10t4Com0jNnKGkPyJ_HpG5SjHrCEJvfArEOAaPKA_k,4189
|
|
94
94
|
coding/proxy/vendors/xiaomi.py,sha256=E-GcmJBZh7GOtDFonxZmlf0hKRhrlrXzL0IxHFRYcRo,860
|
|
95
|
-
coding/proxy/vendors/zhipu.py,sha256=
|
|
96
|
-
coding_proxy-0.5.
|
|
97
|
-
coding_proxy-0.5.
|
|
98
|
-
coding_proxy-0.5.
|
|
99
|
-
coding_proxy-0.5.
|
|
100
|
-
coding_proxy-0.5.
|
|
95
|
+
coding/proxy/vendors/zhipu.py,sha256=GaLaWssa4c1lcukQL4nOtzji8jxEUJFrZtFgOkXTKaM,11127
|
|
96
|
+
coding_proxy-0.5.2.dist-info/METADATA,sha256=xmjagSIjcqdvGye5aFGQrvWnlaoknK_2mPmR7fZpqKM,11259
|
|
97
|
+
coding_proxy-0.5.2.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
98
|
+
coding_proxy-0.5.2.dist-info/entry_points.txt,sha256=moIVzt5ho0Wk9B47LOo2SEAbhzuDDHWi-EfM30U0XBg,54
|
|
99
|
+
coding_proxy-0.5.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
100
|
+
coding_proxy-0.5.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|