coding-proxy 0.1.2__tar.gz → 0.1.3__tar.gz

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.
Files changed (137) hide show
  1. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/CHANGELOG.md +13 -0
  2. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/PKG-INFO +1 -1
  3. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/pyproject.toml +1 -1
  4. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/circuit_breaker.py +31 -8
  5. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/tier.py +4 -1
  6. coding_proxy-0.1.3/src/coding/proxy/vendors/anthropic.py +105 -0
  7. coding_proxy-0.1.3/tests/test_circuit_breaker.py +155 -0
  8. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_tier.py +67 -0
  9. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_vendors.py +187 -1
  10. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/uv.lock +1 -1
  11. coding_proxy-0.1.2/src/coding/proxy/vendors/anthropic.py +0 -48
  12. coding_proxy-0.1.2/tests/test_circuit_breaker.py +0 -49
  13. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/.github/workflows/ci.yml +0 -0
  14. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/.github/workflows/coverage.yml +0 -0
  15. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/.github/workflows/promote.yml +0 -0
  16. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/.github/workflows/release.yml +0 -0
  17. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/.gitignore +0 -0
  18. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/AGENTS.md +0 -0
  19. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/CLAUDE.md +0 -0
  20. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/LICENSE +0 -0
  21. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/README.md +0 -0
  22. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/docs/ci-cd.md +0 -0
  23. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/docs/framework.md +0 -0
  24. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/docs/user-guide.md +0 -0
  25. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/docs/zh-CN/README.md +0 -0
  26. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/__init__.py +0 -0
  27. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/__init__.py +0 -0
  28. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/__main__.py +0 -0
  29. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/auth/__init__.py +0 -0
  30. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/auth/providers/__init__.py +0 -0
  31. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/auth/providers/base.py +0 -0
  32. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/auth/providers/github.py +0 -0
  33. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/auth/providers/google.py +0 -0
  34. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/auth/runtime.py +0 -0
  35. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/auth/store.py +0 -0
  36. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/cli/__init__.py +0 -0
  37. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/cli/auth_commands.py +0 -0
  38. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/compat/__init__.py +0 -0
  39. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/compat/canonical.py +0 -0
  40. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/compat/session_store.py +0 -0
  41. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/__init__.py +0 -0
  42. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/auth_schema.py +0 -0
  43. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/config.default.yaml +0 -0
  44. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/loader.py +0 -0
  45. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/resiliency.py +0 -0
  46. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/routing.py +0 -0
  47. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/schema.py +0 -0
  48. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/server.py +0 -0
  49. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/config/vendors.py +0 -0
  50. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/convert/__init__.py +0 -0
  51. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/convert/anthropic_to_gemini.py +0 -0
  52. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/convert/anthropic_to_openai.py +0 -0
  53. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/convert/gemini_sse_adapter.py +0 -0
  54. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/convert/gemini_to_anthropic.py +0 -0
  55. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/convert/openai_to_anthropic.py +0 -0
  56. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/logging/__init__.py +0 -0
  57. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/logging/db.py +0 -0
  58. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/logging/stats.py +0 -0
  59. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/model/__init__.py +0 -0
  60. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/model/auth.py +0 -0
  61. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/model/compat.py +0 -0
  62. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/model/constants.py +0 -0
  63. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/model/pricing.py +0 -0
  64. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/model/token.py +0 -0
  65. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/model/vendor.py +0 -0
  66. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/pricing.py +0 -0
  67. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/__init__.py +0 -0
  68. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/error_classifier.py +0 -0
  69. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/executor.py +0 -0
  70. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/model_mapper.py +0 -0
  71. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/quota_guard.py +0 -0
  72. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/rate_limit.py +0 -0
  73. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/retry.py +0 -0
  74. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/router.py +0 -0
  75. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/session_manager.py +0 -0
  76. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/usage_parser.py +0 -0
  77. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/routing/usage_recorder.py +0 -0
  78. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/server/__init__.py +0 -0
  79. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/server/app.py +0 -0
  80. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/server/factory.py +0 -0
  81. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/server/request_normalizer.py +0 -0
  82. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/server/responses.py +0 -0
  83. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/server/routes.py +0 -0
  84. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/streaming/__init__.py +0 -0
  85. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/streaming/anthropic_compat.py +0 -0
  86. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/__init__.py +0 -0
  87. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/antigravity.py +0 -0
  88. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/base.py +0 -0
  89. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/copilot.py +0 -0
  90. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/copilot_models.py +0 -0
  91. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/copilot_token_manager.py +0 -0
  92. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/copilot_urls.py +0 -0
  93. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/mixins.py +0 -0
  94. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/token_manager.py +0 -0
  95. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/src/coding/proxy/vendors/zhipu.py +0 -0
  96. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/__init__.py +0 -0
  97. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_antigravity.py +0 -0
  98. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_app_routes.py +0 -0
  99. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_auto_login.py +0 -0
  100. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_cli_usage.py +0 -0
  101. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_compat.py +0 -0
  102. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_config_init.py +0 -0
  103. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_config_loader.py +0 -0
  104. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_convert_request.py +0 -0
  105. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_convert_response.py +0 -0
  106. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_convert_sse.py +0 -0
  107. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_copilot.py +0 -0
  108. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_copilot_convert_request.py +0 -0
  109. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_copilot_convert_response.py +0 -0
  110. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_copilot_models.py +0 -0
  111. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_copilot_urls.py +0 -0
  112. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_currency.py +0 -0
  113. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_error_classifier.py +0 -0
  114. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_mixins.py +0 -0
  115. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_model_auth.py +0 -0
  116. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_model_compat.py +0 -0
  117. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_model_constants.py +0 -0
  118. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_model_mapper.py +0 -0
  119. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_model_pricing.py +0 -0
  120. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_model_token.py +0 -0
  121. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_model_vendor.py +0 -0
  122. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_parse_usage.py +0 -0
  123. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_pricing.py +0 -0
  124. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_quota_guard.py +0 -0
  125. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_rate_limit.py +0 -0
  126. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_request_normalizer.py +0 -0
  127. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_router_chain.py +0 -0
  128. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_router_executor.py +0 -0
  129. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_runtime_reauth.py +0 -0
  130. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_schema.py +0 -0
  131. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_streaming_anthropic_compat.py +0 -0
  132. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_tiers_config.py +0 -0
  133. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_token_logger.py +0 -0
  134. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_token_manager.py +0 -0
  135. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_types.py +0 -0
  136. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_vendor_streaming.py +0 -0
  137. {coding_proxy-0.1.2 → coding_proxy-0.1.3}/tests/test_zhipu.py +0 -0
@@ -4,6 +4,19 @@
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [v0.1.3](https://github.com/ThreeFish-AI/coding-proxy/releases/tag/v0.1.3) — 2026-04-07
8
+
9
+ > [!IMPORTANT]
10
+ >
11
+ > **🔥 跨供应商"身份危机" + 熔断器"装死"双杀!**
12
+ >
13
+ > Zhipu 的 thinking blocks 偷渡到 Anthropic 被当场识破 → 400 无限循环降级?斩了。429 限流后熔断器嘴上说"我没事"身体却已躺平?修了。两大隐蔽 Bug 一锅端,跨供应商丝滑切换从此告别"薛定谔的可用性"。
14
+
15
+ ### ✨ 核心亮点
16
+
17
+ - **Thinking Blocks "安检门"**:Anthropic 对请求体 deepcopy 后,**精准剥离** assistant messages 中的 `thinking` / `redacted_thinking` blocks。Zhipu → Anthropic 迁移时历史思考签名不再越界,400 `invalid_request_error` 彻底根除,其他供应商零影响;
18
+ - **熔断器 Force-Open 闪电响应**:为 `record_failure()` 新增 `force_open` 参数——当检测到 429/403 携带 `retry_after_seconds`(即 Rate Limit 硬信号)时,**跳过累积阈值直接 OPEN**,状态展示与实际可用性分秒对齐;非 429 错误(5xx、超时等)保持原有累积行为不变。
19
+
7
20
  ## [v0.1.2](https://github.com/ThreeFish-AI/coding-proxy/releases/tag/v0.1.2) — 2026-04-06
8
21
 
9
22
  > [!IMPORTANT]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: coding-proxy
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: A High-Availability, Transparent, and Smart Multi-Vendor Proxy for Claude Code. Support Claude Plans, GitHub Copilot, Google Antigravity, ZAI/GLM.
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "coding-proxy"
3
- version = "0.1.2"
3
+ version = "0.1.3"
4
4
  description = "A High-Availability, Transparent, and Smart Multi-Vendor Proxy for Claude Code. Support Claude Plans, GitHub Copilot, Google Antigravity, ZAI/GLM."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -70,12 +70,20 @@ class CircuitBreaker:
70
70
  # 正常状态下成功,无需操作
71
71
  pass
72
72
 
73
- def record_failure(self, retry_after_seconds: float | None = None) -> None:
73
+ def record_failure(
74
+ self,
75
+ retry_after_seconds: float | None = None,
76
+ *,
77
+ force_open: bool = False,
78
+ ) -> None:
74
79
  """记录一次失败调用.
75
80
 
76
81
  Args:
77
82
  retry_after_seconds: 从响应头解析出的建议恢复时间(秒)。
78
83
  若提供且大于当前指数退避值,将覆盖以避免过早探测。
84
+ force_open: 是否忽略 failure_threshold,立即将熔断器转为 OPEN。
85
+ 用于 429/rate limit 等具有明确恢复窗口的错误,
86
+ 此类错误无需多次采样即可确定供应商不可用。
79
87
  """
80
88
  with self._lock:
81
89
  self._failure_count += 1
@@ -90,9 +98,16 @@ class CircuitBreaker:
90
98
  self._current_recovery,
91
99
  )
92
100
  elif self._state == CircuitState.CLOSED:
93
- if self._failure_count >= self._failure_threshold:
101
+ if force_open or self._failure_count >= self._failure_threshold:
94
102
  self._transition_to(CircuitState.OPEN)
95
- if (
103
+ # force_open 场景下,retry-after 是权威信号(如 429 Retry-After),
104
+ # 即使不超过当前退避值也应采用;非 force_open 时仅在有优势时覆盖。
105
+ if force_open and retry_after_seconds is not None:
106
+ self._current_recovery = min(
107
+ retry_after_seconds,
108
+ self._max_recovery,
109
+ )
110
+ elif (
96
111
  retry_after_seconds
97
112
  and retry_after_seconds > self._current_recovery
98
113
  ):
@@ -100,11 +115,19 @@ class CircuitBreaker:
100
115
  retry_after_seconds,
101
116
  self._max_recovery,
102
117
  )
103
- logger.warning(
104
- "Circuit breaker: CLOSED → OPEN (%d consecutive failures, next retry in %ds)",
105
- self._failure_count,
106
- self._current_recovery,
107
- )
118
+ if force_open:
119
+ logger.warning(
120
+ "Circuit breaker: CLOSED → OPEN "
121
+ "(forced, rate-limited, next retry in %ds)",
122
+ self._current_recovery,
123
+ )
124
+ else:
125
+ logger.warning(
126
+ "Circuit breaker: CLOSED → OPEN "
127
+ "(%d consecutive failures, next retry in %ds)",
128
+ self._failure_count,
129
+ self._current_recovery,
130
+ )
108
131
 
109
132
  def reset(self) -> None:
110
133
  """手动重置熔断器为 CLOSED 状态."""
@@ -85,7 +85,10 @@ class VendorTier:
85
85
  rate_limit_deadline: 精确的 rate limit 截止 monotonic 时间戳
86
86
  """
87
87
  if self.circuit_breaker:
88
- self.circuit_breaker.record_failure(retry_after_seconds=retry_after_seconds)
88
+ self.circuit_breaker.record_failure(
89
+ retry_after_seconds=retry_after_seconds,
90
+ force_open=(retry_after_seconds is not None),
91
+ )
89
92
  if self.quota_guard and is_cap_error:
90
93
  self.quota_guard.notify_cap_error(retry_after_seconds=retry_after_seconds)
91
94
  if self.weekly_quota_guard and is_cap_error:
@@ -0,0 +1,105 @@
1
+ """Anthropic 官方供应商 — 透传 OAuth token."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import logging
7
+ from typing import Any
8
+
9
+ from ..config.schema import AnthropicConfig, FailoverConfig
10
+ from .base import PROXY_SKIP_HEADERS, BaseVendor
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # 需要从 assistant messages 中剥离的 thinking block 类型
15
+ _THINKING_BLOCK_TYPES = {"thinking", "redacted_thinking"}
16
+
17
+
18
+ def _strip_thinking_blocks(body: dict[str, Any]) -> int:
19
+ """从 assistant messages 中移除 thinking / redacted_thinking blocks.
20
+
21
+ Anthropic API 要求 thinking blocks 的 ``signature`` 必须是其签发的有效签名。
22
+ 跨供应商迁移(如 Zhipu → Anthropic)后,conversation history 中可能包含
23
+ 非 Anthropic 签发的 signature,导致 400 ``invalid_request_error``。
24
+ 根据 Anthropic 官方文档,thinking blocks 可以被安全省略,不影响模型行为。
25
+
26
+ Returns:
27
+ 被移除的 thinking block 数量。
28
+ """
29
+ stripped = 0
30
+ for message in body.get("messages", []):
31
+ if not isinstance(message, dict) or message.get("role") != "assistant":
32
+ continue
33
+ content = message.get("content")
34
+ if not isinstance(content, list):
35
+ continue
36
+ original_len = len(content)
37
+ new_content = [
38
+ block
39
+ for block in content
40
+ if not (
41
+ isinstance(block, dict) and block.get("type") in _THINKING_BLOCK_TYPES
42
+ )
43
+ ]
44
+ removed = original_len - len(new_content)
45
+ if removed and not new_content:
46
+ logger.warning(
47
+ "anthropic: assistant message content became empty after "
48
+ "stripping %d thinking block(s); this may cause API errors",
49
+ removed,
50
+ )
51
+ message["content"] = new_content
52
+ stripped += removed
53
+ return stripped
54
+
55
+
56
+ class AnthropicVendor(BaseVendor):
57
+ """Anthropic 官方 API 供应商.
58
+
59
+ 透传 Claude Code 发来的 OAuth token 和请求体到 Anthropic API.
60
+ """
61
+
62
+ def __init__(
63
+ self, config: AnthropicConfig, failover_config: FailoverConfig
64
+ ) -> None:
65
+ super().__init__(config.base_url, config.timeout_ms, failover_config)
66
+
67
+ def get_name(self) -> str:
68
+ return "anthropic"
69
+
70
+ async def check_health(self) -> bool:
71
+ """Anthropic 健康检查 — 透明代理被动策略.
72
+
73
+ Anthropic 供应商作为透明代理,不管理凭证(auth 来自客户端请求头),
74
+ 无法独立发起 API 探测。健康状态通过 VendorTier 的 Rate Limit
75
+ Deadline 门控判定:仅在服务端声明的 rate limit 重置时间到期后,
76
+ 才允许使用下一个真实客户端请求作为探针。
77
+ """
78
+ return True
79
+
80
+ async def _prepare_request(
81
+ self,
82
+ request_body: dict[str, Any],
83
+ headers: dict[str, str],
84
+ ) -> tuple[dict[str, Any], dict[str, str]]:
85
+ """深拷贝请求体、剥离历史 thinking blocks,过滤无关请求头.
86
+
87
+ 深拷贝确保 Anthropic 的请求体修改不会污染后续 tier 的输入。
88
+ 剥离 thinking blocks 防止跨供应商 signature 不兼容导致 400 错误。
89
+ """
90
+ body = copy.deepcopy(request_body)
91
+ stripped = _strip_thinking_blocks(body)
92
+ if stripped:
93
+ logger.debug(
94
+ "anthropic: stripped %d thinking block(s) from conversation history",
95
+ stripped,
96
+ )
97
+
98
+ filtered = {
99
+ k: v for k, v in headers.items() if k.lower() not in PROXY_SKIP_HEADERS
100
+ }
101
+ return body, filtered
102
+
103
+
104
+ # 向后兼容别名
105
+ AnthropicBackend = AnthropicVendor
@@ -0,0 +1,155 @@
1
+ """熔断器状态转换单元测试."""
2
+
3
+ from coding.proxy.routing.circuit_breaker import CircuitBreaker, CircuitState
4
+
5
+
6
+ def test_initial_state_is_closed():
7
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=30)
8
+ assert cb.state == CircuitState.CLOSED
9
+
10
+
11
+ def test_closed_to_open():
12
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=30)
13
+ for _ in range(3):
14
+ cb.record_failure()
15
+ assert cb.state == CircuitState.OPEN
16
+
17
+
18
+ def test_open_rejects_requests():
19
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=300)
20
+ for _ in range(3):
21
+ cb.record_failure()
22
+ assert not cb.can_execute()
23
+
24
+
25
+ def test_reset_to_closed():
26
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=30)
27
+ for _ in range(3):
28
+ cb.record_failure()
29
+ assert cb.state == CircuitState.OPEN
30
+ cb.reset()
31
+ assert cb.state == CircuitState.CLOSED
32
+
33
+
34
+ def test_success_resets_failure_count():
35
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=30)
36
+ cb.record_failure()
37
+ cb.record_failure()
38
+ cb.record_success()
39
+ # 成功重置失败计数,再失败两次不会触发 OPEN
40
+ cb.record_failure()
41
+ cb.record_failure()
42
+ assert cb.state == CircuitState.CLOSED
43
+
44
+
45
+ def test_get_info():
46
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=30)
47
+ info = cb.get_info()
48
+ assert info["state"] == "closed"
49
+ assert info["failure_count"] == 0
50
+
51
+
52
+ # ── force_open: 429 / rate limit 立即开路 ──────────────────────
53
+
54
+
55
+ def test_force_open_immediately_opens_from_closed():
56
+ """force_open=True 时,单次失败即可从 CLOSED → OPEN(无需累积至阈值)."""
57
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=30)
58
+ assert cb.state == CircuitState.CLOSED
59
+
60
+ cb.record_failure(force_open=True)
61
+ assert cb.state == CircuitState.OPEN
62
+ assert not cb.can_execute()
63
+
64
+
65
+ def test_force_open_uses_retry_after_as_recovery():
66
+ """force_open + retry_after_seconds → 使用 server-hinted 恢复时间作为 recovery."""
67
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=300)
68
+
69
+ cb.record_failure(retry_after_seconds=60.0, force_open=True)
70
+ assert cb.state == CircuitState.OPEN
71
+
72
+ info = cb.get_info()
73
+ assert info["current_recovery_seconds"] == 60.0
74
+
75
+
76
+ def test_force_open_respects_max_recovery():
77
+ """force_open 的 retry_after 超过 max_recovery 时应被截断."""
78
+ cb = CircuitBreaker(
79
+ failure_threshold=3,
80
+ recovery_timeout_seconds=300,
81
+ max_recovery_seconds=3600,
82
+ )
83
+
84
+ cb.record_failure(retry_after_seconds=7200.0, force_open=True) # 2h > 1h max
85
+ info = cb.get_info()
86
+ assert info["current_recovery_seconds"] == 3600.0
87
+
88
+
89
+ def test_force_open_without_retry_uses_default_backoff():
90
+ """force_open 但无 retry_after → 使用默认 recovery_timeout 作为退避."""
91
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=300)
92
+
93
+ cb.record_failure(force_open=True) # 无 retry_after
94
+ info = cb.get_info()
95
+ assert info["current_recovery_seconds"] == 300
96
+
97
+
98
+ def test_force_open_in_half_open_stays_same_behavior():
99
+ """HALF_OPEN 状态下 force_open 不改变既有行为(本来就立即 OPEN).
100
+
101
+ 验证 HALF_OPEN 分支的 force_open 走的是同一条立即 OPEN 路径,
102
+ 与非 force_open 行为一致.
103
+ """
104
+ cb = CircuitBreaker(failure_threshold=1, recovery_timeout_seconds=30)
105
+ cb.record_failure() # CLOSED → OPEN
106
+ assert cb.state == CircuitState.OPEN
107
+
108
+ # 手动推进到 HALF_OPEN(将 last_failure_time 往前推超过 recovery)
109
+ import time as _time
110
+
111
+ cb._last_failure_time = _time.monotonic() - cb._recovery_timeout - 1
112
+ assert cb.state == CircuitState.HALF_OPEN
113
+
114
+ # HALF_OPEN 下任意失败(含 force_open)都应立即回到 OPEN
115
+ cb.record_failure(force_open=True)
116
+ # 断言:_check_recovery 未触发(刚进入 OPEN),state 应为 OPEN
117
+ assert cb.state == CircuitState.OPEN
118
+
119
+
120
+ def test_no_force_open_preserves_original_threshold():
121
+ """force_open=False(默认)保持原有的 failure_threshold 累积行为."""
122
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=30)
123
+
124
+ cb.record_failure() # count=1, still CLOSED
125
+ assert cb.state == CircuitState.CLOSED
126
+
127
+ cb.record_failure() # count=2, still CLOSED
128
+ assert cb.state == CircuitState.CLOSED
129
+
130
+ cb.record_failure() # count=3, → OPEN
131
+ assert cb.state == CircuitState.OPEN
132
+
133
+
134
+ def test_force_open_with_small_hint_overrides_current():
135
+ """force_open 时即使 hint < current_recovery 也使用 hint(429 权威信号).
136
+
137
+ 模拟场景:CB 已因累积失败进入 OPEN(current_recovery 较大),
138
+ 随后 reset 回 CLOSED,再收到带较短 retry-after 的 429.
139
+ """
140
+ cb = CircuitBreaker(failure_threshold=3, recovery_timeout_seconds=300)
141
+ # 先通过正常累积进入 OPEN,建立较大的 current_recovery
142
+ cb.record_failure()
143
+ cb.record_failure()
144
+ cb.record_failure() # → OPEN, current_recovery=300
145
+ assert cb.state == CircuitState.OPEN
146
+
147
+ # reset 回 CLOSED(模拟恢复后重试)
148
+ cb.reset()
149
+ assert cb.state == CircuitState.CLOSED
150
+ assert cb.get_info()["current_recovery_seconds"] == 300
151
+
152
+ # 再一次 force_open,hint 较小 — 应使用权威 hint
153
+ cb.record_failure(retry_after_seconds=10.0, force_open=True)
154
+ info = cb.get_info()
155
+ assert info["current_recovery_seconds"] == 10.0
@@ -355,3 +355,70 @@ def test_record_failure_non_cap_no_weekly_qg_notify():
355
355
  tier = VendorTier(vendor=_make_vendor(), weekly_quota_guard=wqg)
356
356
  tier.record_failure(is_cap_error=False)
357
357
  assert wqg.can_use_primary()
358
+
359
+
360
+ # ── 429 → CB immediate open 集成测试 ───────────────────────────
361
+
362
+
363
+ def test_record_failure_with_retry_after_forces_cb_open():
364
+ """提供 retry_after_seconds 时,CB 应立即进入 OPEN(单次即可,无需累积至阈值).
365
+
366
+ 模拟 executor 解析 429 响应头后调用 tier.record_failure(retry_after_seconds=...)
367
+ 的完整链路.
368
+ """
369
+ cb = CircuitBreaker(failure_threshold=3) # 默认阈值 3
370
+ tier = VendorTier(vendor=_make_vendor(), circuit_breaker=cb)
371
+
372
+ # 模拟 429 响应:单次 record_failure 即应打开 CB
373
+ tier.record_failure(
374
+ retry_after_seconds=60.0,
375
+ rate_limit_deadline=time.monotonic() + 66,
376
+ )
377
+
378
+ assert cb.state == CircuitState.OPEN # 核心断言:单次即 OPEN
379
+ assert tier.is_rate_limited # deadline 也应设置
380
+
381
+
382
+ def test_record_failure_without_retry_after_preserves_threshold():
383
+ """不提供 retry_after_seconds 时,CB 保持原有累积行为(非 429 场景).
384
+
385
+ 如连接超时、5xx 等不携带 retry-after 的错误,仍需累积至 failure_threshold.
386
+ """
387
+ cb = CircuitBreaker(failure_threshold=3)
388
+ tier = VendorTier(vendor=_make_vendor(), circuit_breaker=cb)
389
+
390
+ tier.record_failure() # count=1
391
+ assert cb.state == CircuitState.CLOSED # 未达阈值
392
+
393
+ tier.record_failure() # count=2
394
+ assert cb.state == CircuitState.CLOSED # 未达阈值
395
+
396
+ tier.record_failure() # count=3 → OPEN
397
+ assert cb.state == CircuitState.OPEN
398
+
399
+
400
+ def test_record_failure_429_cb_open_and_rl_deadline_consistent():
401
+ """429 场景下 CB state 与 rate_limit_deadline 语义一致.
402
+
403
+ 验证修复前的核心矛盾已解决:
404
+ - 修复前:CB=closed(误导)但 rate_limited=true(实际拦截)
405
+ - 修复后:CB=open(一致)且 rate_limited=true(双重保护)
406
+ """
407
+ cb = CircuitBreaker(failure_threshold=3)
408
+ tier = VendorTier(vendor=_make_vendor("anthropic"), circuit_breaker=cb)
409
+
410
+ future = time.monotonic() + 66
411
+ tier.record_failure(
412
+ is_cap_error=False,
413
+ retry_after_seconds=60.0,
414
+ rate_limit_deadline=future,
415
+ )
416
+
417
+ # CB 应为 OPEN(而非 CLOSED)
418
+ assert cb.state == CircuitState.OPEN
419
+ # can_execute 应返回 False(CB + RL deadline 双重保护)
420
+ assert not tier.can_execute()
421
+ # rate limit 信息也应反映限制状态
422
+ rl_info = tier.get_rate_limit_info()
423
+ assert rl_info["is_rate_limited"] is True
424
+ assert rl_info["remaining_seconds"] > 59
@@ -37,13 +37,199 @@ async def test_anthropic_prepare_request_filters_headers():
37
37
  "anthropic-version": "2023-06-01",
38
38
  }
39
39
  prepared_body, prepared_headers = await vendor._prepare_request(body, headers)
40
- assert prepared_body is body # 不修改原始 body
40
+ assert prepared_body is not body # deepcopy: 返回新对象
41
+ assert prepared_body == body # 内容等价
41
42
  assert "host" not in prepared_headers
42
43
  assert "content-length" not in prepared_headers
43
44
  assert prepared_headers["authorization"] == "Bearer sk-test"
44
45
  assert prepared_headers["anthropic-version"] == "2023-06-01"
45
46
 
46
47
 
48
+ @pytest.mark.asyncio
49
+ async def test_anthropic_prepare_request_strips_thinking_blocks():
50
+ """Anthropic vendor 应剥离 assistant messages 中的 thinking blocks."""
51
+ vendor = AnthropicVendor(AnthropicConfig(), FailoverConfig())
52
+ body = {
53
+ "model": "claude-opus-4-6",
54
+ "messages": [
55
+ {
56
+ "role": "assistant",
57
+ "content": [
58
+ {
59
+ "type": "thinking",
60
+ "thinking": "Let me think about this...",
61
+ "signature": "zhipu-issued-signature",
62
+ },
63
+ {"type": "text", "text": "Here is my answer."},
64
+ ],
65
+ },
66
+ ],
67
+ }
68
+ prepared_body, _ = await vendor._prepare_request(body, {})
69
+
70
+ # thinking block 被剥离,text block 保留
71
+ content = prepared_body["messages"][0]["content"]
72
+ assert len(content) == 1
73
+ assert content[0]["type"] == "text"
74
+ assert content[0]["text"] == "Here is my answer."
75
+
76
+
77
+ @pytest.mark.asyncio
78
+ async def test_anthropic_prepare_request_strips_redacted_thinking_blocks():
79
+ """Anthropic vendor 应剥离 assistant messages 中的 redacted_thinking blocks."""
80
+ vendor = AnthropicVendor(AnthropicConfig(), FailoverConfig())
81
+ body = {
82
+ "model": "claude-opus-4-6",
83
+ "messages": [
84
+ {
85
+ "role": "assistant",
86
+ "content": [
87
+ {"type": "redacted_thinking", "data": "base64data"},
88
+ {"type": "text", "text": "response"},
89
+ ],
90
+ },
91
+ ],
92
+ }
93
+ prepared_body, _ = await vendor._prepare_request(body, {})
94
+
95
+ content = prepared_body["messages"][0]["content"]
96
+ assert len(content) == 1
97
+ assert content[0]["type"] == "text"
98
+
99
+
100
+ @pytest.mark.asyncio
101
+ async def test_anthropic_prepare_request_preserves_thinking_param():
102
+ """body 顶层的 thinking 参数(控制当前请求是否启用 thinking)不应被修改."""
103
+ vendor = AnthropicVendor(AnthropicConfig(), FailoverConfig())
104
+ body = {
105
+ "model": "claude-opus-4-6",
106
+ "thinking": {"type": "enabled", "budget_tokens": 10000},
107
+ "messages": [
108
+ {
109
+ "role": "assistant",
110
+ "content": [
111
+ {"type": "thinking", "thinking": "old thought", "signature": "sig"},
112
+ {"type": "text", "text": "old response"},
113
+ ],
114
+ },
115
+ {"role": "user", "content": "follow up"},
116
+ ],
117
+ }
118
+ prepared_body, _ = await vendor._prepare_request(body, {})
119
+
120
+ # 顶层 thinking 参数保留
121
+ assert prepared_body["thinking"] == {"type": "enabled", "budget_tokens": 10000}
122
+ # assistant message 的 thinking block 被剥离
123
+ assert len(prepared_body["messages"][0]["content"]) == 1
124
+ assert prepared_body["messages"][0]["content"][0]["type"] == "text"
125
+
126
+
127
+ @pytest.mark.asyncio
128
+ async def test_anthropic_prepare_request_does_not_mutate_original_body():
129
+ """deepcopy 验证:原始 body 不应被修改."""
130
+ vendor = AnthropicVendor(AnthropicConfig(), FailoverConfig())
131
+ body = {
132
+ "model": "claude-opus-4-6",
133
+ "messages": [
134
+ {
135
+ "role": "assistant",
136
+ "content": [
137
+ {"type": "thinking", "thinking": "thought", "signature": "sig"},
138
+ {"type": "text", "text": "response"},
139
+ ],
140
+ },
141
+ ],
142
+ }
143
+ await vendor._prepare_request(body, {})
144
+
145
+ # 原始 body 的 thinking block 应仍然存在
146
+ assert len(body["messages"][0]["content"]) == 2
147
+ assert body["messages"][0]["content"][0]["type"] == "thinking"
148
+
149
+
150
+ @pytest.mark.asyncio
151
+ async def test_anthropic_prepare_request_preserves_user_messages():
152
+ """user messages 不应被修改(thinking blocks 仅出现在 assistant messages 中)."""
153
+ vendor = AnthropicVendor(AnthropicConfig(), FailoverConfig())
154
+ body = {
155
+ "model": "claude-opus-4-6",
156
+ "messages": [
157
+ {
158
+ "role": "user",
159
+ "content": [
160
+ {"type": "text", "text": "hello"},
161
+ ],
162
+ },
163
+ ],
164
+ }
165
+ prepared_body, _ = await vendor._prepare_request(body, {})
166
+
167
+ content = prepared_body["messages"][0]["content"]
168
+ assert len(content) == 1
169
+ assert content[0]["type"] == "text"
170
+
171
+
172
+ @pytest.mark.asyncio
173
+ async def test_anthropic_prepare_request_handles_string_content():
174
+ """assistant message content 为字符串时应原样保留(不触发剥离逻辑)."""
175
+ vendor = AnthropicVendor(AnthropicConfig(), FailoverConfig())
176
+ body = {
177
+ "model": "claude-opus-4-6",
178
+ "messages": [
179
+ {"role": "assistant", "content": "plain text response"},
180
+ ],
181
+ }
182
+ prepared_body, _ = await vendor._prepare_request(body, {})
183
+ assert prepared_body["messages"][0]["content"] == "plain text response"
184
+
185
+
186
+ @pytest.mark.asyncio
187
+ async def test_anthropic_prepare_request_multi_turn_strips_all_thinking():
188
+ """多轮对话中所有 assistant thinking blocks 均应被剥离."""
189
+ vendor = AnthropicVendor(AnthropicConfig(), FailoverConfig())
190
+ body = {
191
+ "model": "claude-opus-4-6",
192
+ "messages": [
193
+ {
194
+ "role": "assistant",
195
+ "content": [
196
+ {"type": "thinking", "thinking": "thought 1", "signature": "s1"},
197
+ {"type": "text", "text": "response 1"},
198
+ ],
199
+ },
200
+ {"role": "user", "content": "follow up"},
201
+ {
202
+ "role": "assistant",
203
+ "content": [
204
+ {"type": "thinking", "thinking": "thought 2", "signature": "s2"},
205
+ {"type": "text", "text": "response 2"},
206
+ {
207
+ "type": "tool_use",
208
+ "id": "toolu_123",
209
+ "name": "bash",
210
+ "input": {"command": "pwd"},
211
+ },
212
+ ],
213
+ },
214
+ ],
215
+ }
216
+ prepared_body, _ = await vendor._prepare_request(body, {})
217
+
218
+ # 第一条 assistant message: thinking 被剥离,text 保留
219
+ content_0 = prepared_body["messages"][0]["content"]
220
+ assert len(content_0) == 1
221
+ assert content_0[0]["type"] == "text"
222
+
223
+ # user message 不变
224
+ assert prepared_body["messages"][1]["content"] == "follow up"
225
+
226
+ # 第三条 assistant message: thinking 被剥离,text + tool_use 保留
227
+ content_2 = prepared_body["messages"][2]["content"]
228
+ assert len(content_2) == 2
229
+ assert content_2[0]["type"] == "text"
230
+ assert content_2[1]["type"] == "tool_use"
231
+
232
+
47
233
  @pytest.mark.asyncio
48
234
  async def test_zhipu_prepare_request_maps_model():
49
235
  mapper = ModelMapper(
@@ -65,7 +65,7 @@ wheels = [
65
65
 
66
66
  [[package]]
67
67
  name = "coding-proxy"
68
- version = "0.1.2"
68
+ version = "0.1.3"
69
69
  source = { editable = "." }
70
70
  dependencies = [
71
71
  { name = "aiosqlite" },