coding-proxy 0.2.0a2__py3-none-any.whl → 0.2.1__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.
@@ -104,11 +104,18 @@ def start(
104
104
  # 打印启动品牌横幅
105
105
  print_banner(console, host=cfg.server.host, port=cfg.server.port)
106
106
 
107
+ # 解析文件日志路径:未显式配置时使用默认值
108
+ _file_path: str | None = cfg.logging.file or "coding-proxy.log"
107
109
  uvicorn.run(
108
110
  fastapi_app,
109
111
  host=cfg.server.host,
110
112
  port=cfg.server.port,
111
- log_config=build_log_config(cfg.logging.level),
113
+ log_config=build_log_config(
114
+ level=cfg.logging.level,
115
+ file_path=_file_path,
116
+ max_bytes=cfg.logging.max_bytes,
117
+ backup_count=cfg.logging.backup_count,
118
+ ),
112
119
  )
113
120
 
114
121
 
@@ -8,6 +8,9 @@ server:
8
8
 
9
9
  logging:
10
10
  level: "INFO"
11
+ # file: "coding-proxy.log" # 文件日志路径;设为 null 或空字符串禁用
12
+ # max_bytes: 5242880 # 单文件上限(5 MB),触发轮转
13
+ # backup_count: 5 # 保留 gzip 压缩备份文件数
11
14
 
12
15
  # === 降级链路优先级(可选) ===
13
16
  #
@@ -232,11 +235,15 @@ model_mapping:
232
235
  # Google Antigravity 模型映射
233
236
  - pattern: "claude-sonnet-.*"
234
237
  vendors: ["antigravity"]
235
- target: "claude-sonnet-4-6-thinking"
238
+ target: "Claude Sonnet 4.6"
236
239
  is_regex: true
237
240
  - pattern: "claude-opus-.*"
238
241
  vendors: ["antigravity"]
239
- target: "claude-opus-4-6-thinking"
242
+ target: "Claude Opus 4.6 Thinking"
243
+ is_regex: true
244
+ - pattern: "claude-haiku-.*"
245
+ vendors: ["antigravity"]
246
+ target: "Gemini 3 Flash"
240
247
  is_regex: true
241
248
  # 智谱 GLM 映射(官方原生 Anthropic 兼容端点)
242
249
  # glm-5v-turbo 完整承载 Claude Code 满血能力(tool calling / thinking / 多模态)
@@ -349,6 +356,12 @@ pricing:
349
356
  output_cost_per_mtok: $25.0
350
357
  cache_write_cost_per_mtok: $6.25
351
358
  cache_read_cost_per_mtok: $0.50
359
+ - vendor: copilot
360
+ model: Claude Opus 4.6
361
+ input_cost_per_mtok: $5.0
362
+ output_cost_per_mtok: $25.0
363
+ cache_write_cost_per_mtok: $6.25
364
+ cache_read_cost_per_mtok: $0.50
352
365
  - vendor: copilot
353
366
  model: Claude Sonnet 4.6
354
367
  input_cost_per_mtok: $3.0
@@ -373,6 +386,12 @@ pricing:
373
386
  output_cost_per_mtok: $5
374
387
  cache_write_cost_per_mtok: $1.25
375
388
  cache_read_cost_per_mtok: $0.10
389
+ - vendor: copilot
390
+ model: Claude Haiku 4.5
391
+ input_cost_per_mtok: $1
392
+ output_cost_per_mtok: $5
393
+ cache_write_cost_per_mtok: $1.25
394
+ cache_read_cost_per_mtok: $0.10
376
395
  # ── Google Antigravity(参照 Anthropic 定价估算) ──
377
396
  - vendor: antigravity
378
397
  model: claude-opus-4-6-thinking
@@ -17,8 +17,20 @@ class DatabaseConfig(BaseModel):
17
17
 
18
18
 
19
19
  class LoggingConfig(BaseModel):
20
+ """日志配置.
21
+
22
+ Attributes:
23
+ level: 控制台日志级别(INFO / WARNING / DEBUG 等)。
24
+ file: 文件日志路径。为 ``None`` 时使用默认值 ``coding-proxy.log``;
25
+ 设为空字符串可禁用文件日志。
26
+ max_bytes: 单个日志文件最大字节数(触发轮转)。默认 5 MB。
27
+ backup_count: 保留的已压缩备份文件数。默认 5。
28
+ """
29
+
20
30
  level: str = "INFO"
21
31
  file: str | None = None
32
+ max_bytes: int = 5 * 1024 * 1024
33
+ backup_count: int = 5
22
34
 
23
35
 
24
36
  __all__ = ["ServerConfig", "DatabaseConfig", "LoggingConfig"]
@@ -34,6 +34,7 @@ class AntigravityConfig(BaseModel):
34
34
  model_endpoint: str = "models/claude-sonnet-4-20250514"
35
35
  timeout_ms: int = 300000
36
36
  safety_settings: dict[str, str] | None = None
37
+ project_id: str = "" # GCP Project ID(v1internal 协议必填)
37
38
 
38
39
 
39
40
  class ZhipuConfig(BaseModel):
@@ -1,11 +1,92 @@
1
- """日志模块."""
1
+ """日志模块.
2
+
3
+ 提供 uvicorn 兼容的 dictConfig 构建、文件日志字符串格式化器、
4
+ 以及 gzip 压缩轮转支持。
5
+ """
2
6
 
3
7
  from __future__ import annotations
4
8
 
9
+ import gzip
10
+ import logging
11
+ import logging.handlers
12
+ import os
13
+ from pathlib import Path
14
+
15
+ from .formatters import FileFormatter
16
+
17
+ # ── 常量 ────────────────────────────────────────────────────────
18
+
19
+ _DEFAULT_MAX_BYTES = 5 * 1024 * 1024 # 5 MB per file
20
+ _DEFAULT_BACKUP_COUNT = 5 # Keep 5 rotated backups
21
+ _FILE_LOG_LEVEL = "DEBUG" # File logs capture everything
22
+
23
+
24
+ def _gzip_namer(default_name: str) -> str:
25
+ """RotatingFileHandler namer: 为轮转文件添加 .gz 后缀."""
26
+ return default_name + ".gz"
27
+
28
+
29
+ def _gzip_rotator(source: str, dest: str) -> None:
30
+ """RotatingFileHandler rotator: 将源文件 gzip 压缩后写入目标.
31
+
32
+ 流程:
33
+ 1. 读取 source 文件全部内容
34
+ 2. gzip 压缩写入 dest 文件
35
+ 3. 删除 source 原文件
36
+ """
37
+ with open(source, "rb") as f_in:
38
+ data = f_in.read()
39
+ with open(dest, "wb") as f_out:
40
+ f_out.write(gzip.compress(data, compresslevel=6))
41
+ os.remove(source)
42
+
43
+
44
+ def _create_rotating_file_handler(
45
+ *,
46
+ filename: str,
47
+ maxBytes: int = _DEFAULT_MAX_BYTES,
48
+ backupCount: int = _DEFAULT_BACKUP_COUNT,
49
+ encoding: str = "utf-8",
50
+ ) -> logging.handlers.RotatingFileHandler:
51
+ """创建带 gzip 压缩轮转的 RotatingFileHandler(dictConfig 兼容工厂函数).
52
+
53
+ ``logging.config.dictConfig`` 仅支持通过构造函数 kwargs 配置 handler,
54
+ 而 ``namer`` / ``rotator`` 是实例属性而非构造参数,因此需要通过工厂函数注入。
55
+ """
56
+ handler = logging.handlers.RotatingFileHandler(
57
+ filename=filename,
58
+ maxBytes=maxBytes,
59
+ backupCount=backupCount,
60
+ encoding=encoding,
61
+ )
62
+ handler.namer = _gzip_namer
63
+ handler.rotator = _gzip_rotator
64
+ return handler
65
+
5
66
 
6
- def build_log_config(level: str = "INFO") -> dict:
7
- """构建 uvicorn log_config,使用 yyyy-MM-dd HH:mm:ss 时间格式."""
8
- return {
67
+ def build_log_config(
68
+ level: str = "INFO",
69
+ file_path: str | None = None,
70
+ max_bytes: int = _DEFAULT_MAX_BYTES,
71
+ backup_count: int = _DEFAULT_BACKUP_COUNT,
72
+ ) -> dict:
73
+ """构建 uvicorn log_config,支持双写(控制台 + 文件).
74
+
75
+ Args:
76
+ level: 控制台日志级别(默认 INFO)。
77
+ file_path: 文件日志路径。为 ``None`` 时仅输出到控制台(向后兼容)。
78
+ max_bytes: 单个日志文件最大字节数(默认 5 MB)。
79
+ backup_count: 保留的轮转备份文件数(默认 5)。
80
+
81
+ Returns:
82
+ 符合 ``logging.config.dictConfig`` 规范的字典。
83
+
84
+ 双写行为:
85
+ - 控制台:人类可读格式,级别由 ``level`` 参数控制(handler 级别过滤)
86
+ - 文件:字符串格式(与控制台风格一致),固定 DEBUG 级别(捕获所有日志)
87
+ - 当 ``file_path`` 为 ``None`` 或空字符串时,退化为纯控制台模式(向后兼容)
88
+ """
89
+ config: dict = {
9
90
  "version": 1,
10
91
  "disable_existing_loggers": False,
11
92
  "formatters": {
@@ -26,11 +107,13 @@ def build_log_config(level: str = "INFO") -> dict:
26
107
  "formatter": "default",
27
108
  "class": "logging.StreamHandler",
28
109
  "stream": "ext://sys.stderr",
110
+ "level": level,
29
111
  },
30
112
  "access": {
31
113
  "formatter": "access",
32
114
  "class": "logging.StreamHandler",
33
115
  "stream": "ext://sys.stdout",
116
+ "level": "INFO",
34
117
  },
35
118
  },
36
119
  "loggers": {
@@ -48,3 +131,58 @@ def build_log_config(level: str = "INFO") -> dict:
48
131
  },
49
132
  },
50
133
  }
134
+
135
+ # ── 条件注入:文件日志基础设施 ────────────────────────────
136
+ if file_path:
137
+ # 确保日志目录存在
138
+ log_file = Path(file_path)
139
+ log_file.parent.mkdir(parents=True, exist_ok=True)
140
+
141
+ # 注入文件日志字符串 formatter
142
+ config["formatters"]["file_fmt"] = {
143
+ "()": "coding.proxy.logging.formatters.FileFormatter",
144
+ }
145
+
146
+ # 注入 RotatingFileHandler(gzip 压缩轮转)
147
+ # 使用工厂函数(而非 class + namer/rotator kwargs),
148
+ # 因为 dictConfig 不支持将 namer/rotator 作为构造参数传递
149
+ config["handlers"]["file"] = {
150
+ "formatter": "file_fmt",
151
+ "()": "coding.proxy.logging._create_rotating_file_handler",
152
+ "filename": str(log_file.resolve()),
153
+ "maxBytes": max_bytes,
154
+ "backupCount": backup_count,
155
+ "encoding": "utf-8",
156
+ }
157
+
158
+ # 为每个 logger 添加 file handler
159
+ # 注意:uvicorn.error 无 handlers 键(通过 propagate 继承 uvicorn 的 handler)
160
+ for logger_name in (
161
+ "uvicorn",
162
+ "uvicorn.error",
163
+ "uvicorn.access",
164
+ "coding.proxy",
165
+ ):
166
+ logger_cfg = config["loggers"][logger_name]
167
+ handlers = logger_cfg.get("handlers", [])
168
+ if isinstance(handlers, list):
169
+ handlers.append("file")
170
+ logger_cfg["handlers"] = handlers
171
+ else:
172
+ logger_cfg["handlers"] = [handlers, "file"]
173
+
174
+ # Logger 级别设为 DEBUG(让所有消息通过到 file handler)
175
+ # Console handler 已设 level 过滤,确保控制台仅输出 INFO+
176
+ config["loggers"]["coding.proxy"]["level"] = _FILE_LOG_LEVEL
177
+ config["loggers"]["uvicorn"]["level"] = _FILE_LOG_LEVEL
178
+ config["loggers"]["uvicorn.error"]["level"] = _FILE_LOG_LEVEL
179
+
180
+ return config
181
+
182
+
183
+ __all__ = [
184
+ "build_log_config",
185
+ "FileFormatter",
186
+ "_gzip_namer",
187
+ "_gzip_rotator",
188
+ ]
@@ -0,0 +1,27 @@
1
+ """文件日志格式化器(字符串输出).
2
+
3
+ 为文件日志提供人类可读的字符串格式输出,
4
+ 与控制台输出风格一致,便于人工阅读和 grep 检索。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+
11
+
12
+ class FileFormatter(logging.Formatter):
13
+ """将 LogRecord 格式化为单行可读字符串.
14
+
15
+ 输出格式:``2026-04-11 16:51:13 INFO ModelCall: vendor=zhipu ...``
16
+
17
+ 设计要点:
18
+ - 时间戳使用 ``yyyy-MM-dd HH:mm:ss`` 格式(与控制台一致)
19
+ - 日志级别左对齐 5 字符宽度,保证多行对齐美观
20
+ - 无 ANSI 颜色码(文件输出不需要终端转义)
21
+ """
22
+
23
+ def __init__(self) -> None:
24
+ super().__init__(
25
+ fmt="%(asctime)s %(levelname)-5s %(message)s",
26
+ datefmt="%Y-%m-%d %H:%M:%S",
27
+ )
@@ -32,11 +32,14 @@ class CircuitBreaker:
32
32
  recovery_timeout_seconds: int = 300,
33
33
  success_threshold: int = 2,
34
34
  max_recovery_seconds: int = 3600,
35
+ *,
36
+ vendor_name: str = "",
35
37
  ) -> None:
36
38
  self._failure_threshold = failure_threshold
37
39
  self._recovery_timeout = recovery_timeout_seconds
38
40
  self._success_threshold = success_threshold
39
41
  self._max_recovery = max_recovery_seconds
42
+ self._vendor_label = f" [{vendor_name}]" if vendor_name else ""
40
43
 
41
44
  self._state = CircuitState.CLOSED
42
45
  self._failure_count = 0
@@ -65,7 +68,13 @@ class CircuitBreaker:
65
68
  self._success_count += 1
66
69
  if self._success_count >= self._success_threshold:
67
70
  self._transition_to(CircuitState.CLOSED)
68
- logger.info("Circuit breaker: HALF_OPEN → CLOSED (recovered)")
71
+ logger.info(
72
+ "Circuit breaker%s: HALF_OPEN → CLOSED "
73
+ "(recovered, %d/%d consecutive successes)",
74
+ self._vendor_label,
75
+ self._success_count,
76
+ self._success_threshold,
77
+ )
69
78
  elif self._state == CircuitState.CLOSED:
70
79
  # 正常状态下成功,无需操作
71
80
  pass
@@ -94,7 +103,10 @@ class CircuitBreaker:
94
103
  self._transition_to(CircuitState.OPEN)
95
104
  self._backoff_recovery(hint_seconds=retry_after_seconds)
96
105
  logger.warning(
97
- "Circuit breaker: HALF_OPEN → OPEN (recovery failed, next retry in %ds)",
106
+ "Circuit breaker%s: HALF_OPEN → OPEN "
107
+ "(recovery probe failed, backoff %ds → next retry in %ds)",
108
+ self._vendor_label,
109
+ self._current_recovery,
98
110
  self._current_recovery,
99
111
  )
100
112
  elif self._state == CircuitState.CLOSED:
@@ -117,14 +129,17 @@ class CircuitBreaker:
117
129
  )
118
130
  if force_open:
119
131
  logger.warning(
120
- "Circuit breaker: CLOSED → OPEN "
121
- "(forced, rate-limited, next retry in %ds)",
132
+ "Circuit breaker%s: CLOSED → OPEN "
133
+ "(forced, rate-limited, retry-after=%ss → next retry in %ds)",
134
+ self._vendor_label,
135
+ retry_after_seconds or "N/A",
122
136
  self._current_recovery,
123
137
  )
124
138
  else:
125
139
  logger.warning(
126
- "Circuit breaker: CLOSED → OPEN "
140
+ "Circuit breaker%s: CLOSED → OPEN "
127
141
  "(%d consecutive failures, next retry in %ds)",
142
+ self._vendor_label,
128
143
  self._failure_count,
129
144
  self._current_recovery,
130
145
  )
@@ -134,7 +149,9 @@ class CircuitBreaker:
134
149
  with self._lock:
135
150
  self._transition_to(CircuitState.CLOSED)
136
151
  self._current_recovery = self._recovery_timeout
137
- logger.info("Circuit breaker: manually reset to CLOSED")
152
+ logger.info(
153
+ "Circuit breaker%s: manually reset to CLOSED", self._vendor_label
154
+ )
138
155
 
139
156
  def get_info(self) -> dict:
140
157
  """获取熔断器状态信息."""
@@ -157,7 +174,13 @@ class CircuitBreaker:
157
174
  elapsed = time.monotonic() - self._last_failure_time
158
175
  if elapsed >= self._current_recovery:
159
176
  self._transition_to(CircuitState.HALF_OPEN)
160
- logger.info("Circuit breaker: OPEN → HALF_OPEN (recovery timeout)")
177
+ elapsed_s = int(elapsed)
178
+ logger.info(
179
+ "Circuit breaker%s: OPEN → HALF_OPEN (recovery timeout, waited %ds/%ds)",
180
+ self._vendor_label,
181
+ elapsed_s,
182
+ self._current_recovery,
183
+ )
161
184
 
162
185
  def _transition_to(self, new_state: CircuitState) -> None:
163
186
  self._state = new_state
@@ -48,9 +48,13 @@ logger = logging.getLogger(__name__)
48
48
 
49
49
 
50
50
  def _log_http_error_detail(
51
- tier_name: str, exc: Exception, *, is_stream: bool = False
51
+ tier_name: str,
52
+ exc: Exception,
53
+ *,
54
+ is_stream: bool = False,
55
+ tier: VendorTier | None = None,
52
56
  ) -> None:
53
- """记录 HTTP 错误的详细信息(状态码 / 响应体摘要 / 异常类型).
57
+ """记录 HTTP 错误的详细信息(状态码 / 响应体摘要 / 异常类型 / 熔断器快照).
54
58
 
55
59
  替代原先单行 ``logger.warning("Tier %s stream failed: %s", ...)``,
56
60
  在非 200 响应时输出更丰富的诊断上下文,便于跟踪上游故障根因。
@@ -78,6 +82,14 @@ def _log_http_error_detail(
78
82
  detail_parts.append(f" error_msg={err.get('message', 'N/A')[:200]}")
79
83
  else:
80
84
  detail_parts.append(f" message={str(exc)[:300]}")
85
+ # 熔断器状态快照
86
+ if tier and tier.circuit_breaker:
87
+ cb = tier.circuit_breaker
88
+ cb_info = cb.get_info()
89
+ detail_parts.append(
90
+ f" circuit_breaker={cb_info['state']} "
91
+ f"(failures={cb_info['failure_count']}/{cb._failure_threshold})"
92
+ )
81
93
  logger.warning("\n".join(detail_parts))
82
94
 
83
95
 
@@ -268,6 +280,12 @@ class _RouteExecutor:
268
280
  duration = int((time.monotonic() - start) * 1000)
269
281
  model = body.get("model", "unknown")
270
282
  model_served = usage.get("model_served") or tier.vendor.map_model(model)
283
+ if failed_tier_name is not None:
284
+ logger.info(
285
+ "Tier %s stream succeeded (took over from failed tier: %s)",
286
+ tier.name,
287
+ failed_tier_name,
288
+ )
271
289
  self._recorder.log_model_call(
272
290
  vendor=tier.name,
273
291
  model_requested=model,
@@ -310,7 +328,7 @@ class _RouteExecutor:
310
328
  httpx.ConnectError,
311
329
  httpx.ReadError,
312
330
  ) as exc:
313
- _log_http_error_detail(tier.name, exc, is_stream=True)
331
+ _log_http_error_detail(tier.name, exc, is_stream=True, tier=tier)
314
332
  (
315
333
  should_continue,
316
334
  failed_tier_name,
@@ -325,6 +343,7 @@ class _RouteExecutor:
325
343
  request_body=body,
326
344
  )
327
345
  if should_continue:
346
+ self._log_failover_transition(tier, exc, self._tiers, i)
328
347
  continue
329
348
  if is_last:
330
349
  raise
@@ -399,6 +418,12 @@ class _RouteExecutor:
399
418
  duration = int((time.monotonic() - start) * 1000)
400
419
  model = body.get("model", "unknown")
401
420
  model_served = resp.model_served or tier.vendor.map_model(model)
421
+ if failed_tier_name is not None:
422
+ logger.info(
423
+ "Tier %s message succeeded (took over from failed tier: %s)",
424
+ tier.name,
425
+ failed_tier_name,
426
+ )
402
427
  self._recorder.log_model_call(
403
428
  vendor=tier.name,
404
429
  model_requested=model,
@@ -469,10 +494,15 @@ class _RouteExecutor:
469
494
  rate_limit_deadline=compute_rate_limit_deadline(rl_info),
470
495
  )
471
496
  if not is_last:
497
+ next_tier = (
498
+ self._tiers[i + 1] if i + 1 < len(self._tiers) else None
499
+ )
500
+ next_info = f" → next: {next_tier.name}" if next_tier else ""
472
501
  logger.warning(
473
- "Tier %s error %d, failing over",
502
+ "Tier %s error %d, failing over%s",
474
503
  tier.name,
475
504
  resp.status_code,
505
+ next_info,
476
506
  )
477
507
  failed_tier_name = tier.name
478
508
  continue
@@ -513,7 +543,7 @@ class _RouteExecutor:
513
543
  continue
514
544
 
515
545
  except (httpx.TimeoutException, httpx.ConnectError, httpx.ReadError) as exc:
516
- _log_http_error_detail(tier.name, exc, is_stream=False)
546
+ _log_http_error_detail(tier.name, exc, is_stream=False, tier=tier)
517
547
  tier.record_failure()
518
548
  failed_tier_name = tier.name
519
549
  if is_last:
@@ -694,6 +724,30 @@ class _RouteExecutor:
694
724
 
695
725
  return False, tier.name, exc
696
726
 
727
+ @staticmethod
728
+ def _log_failover_transition(
729
+ current_tier: VendorTier,
730
+ exc: Exception,
731
+ tiers: list[VendorTier],
732
+ current_index: int,
733
+ ) -> None:
734
+ """记录 vendor 轮转摘要日志(谁 → 谁,原因)."""
735
+ next_tier = tiers[current_index + 1] if current_index + 1 < len(tiers) else None
736
+ if next_tier is None:
737
+ return
738
+
739
+ # 提取错误摘要
740
+ reason = type(exc).__name__
741
+ if isinstance(exc, httpx.HTTPStatusError) and exc.response is not None:
742
+ reason = f"HTTP {exc.response.status_code}"
743
+
744
+ logger.info(
745
+ "Failover: %s → %s (reason: %s)",
746
+ current_tier.name,
747
+ next_tier.name,
748
+ reason,
749
+ )
750
+
697
751
  @staticmethod
698
752
  def _is_cap_error(resp: VendorResponse) -> bool:
699
753
  """判断是否为订阅用量上限错误."""
@@ -129,7 +129,7 @@ class QuotaGuard:
129
129
  int(self._effective_probe_interval),
130
130
  )
131
131
 
132
- def load_baseline(self, total_tokens: int) -> None:
132
+ def load_baseline(self, total_tokens: int, vendor: str | None = None) -> None:
133
133
  """从数据库加载窗口历史用量基线."""
134
134
  if not self._enabled or total_tokens <= 0:
135
135
  return
@@ -137,7 +137,14 @@ class QuotaGuard:
137
137
  midpoint = time.monotonic() - self._window / 2
138
138
  self._entries.append((midpoint, total_tokens))
139
139
  self._total += total_tokens
140
- logger.info("Quota guard: loaded baseline %d tokens", total_tokens)
140
+ if vendor:
141
+ logger.info(
142
+ "Quota guard [%s]: loaded baseline %d tokens",
143
+ vendor,
144
+ total_tokens,
145
+ )
146
+ else:
147
+ logger.info("Quota guard: loaded baseline %d tokens", total_tokens)
141
148
 
142
149
  def reset(self) -> None:
143
150
  """手动重置为 WITHIN_QUOTA 状态."""
@@ -155,11 +155,33 @@ class VendorTier:
155
155
  if not is_probe_scenario:
156
156
  return cb_allows and qg_allows and wqg_allows
157
157
 
158
+ # 构建探测上下文摘要
159
+ probe_context_parts: list[str] = []
160
+ if self.circuit_breaker:
161
+ cb_info = self.circuit_breaker.get_info()
162
+ probe_context_parts.append(
163
+ f"circuit_breaker={cb_info['state']}, "
164
+ f"failures={cb_info['failure_count']}"
165
+ )
166
+ if self._rate_limit_deadline > 0:
167
+ waited = int(time.monotonic() - self._rate_limit_deadline)
168
+ probe_context_parts.append(f"rate_limit_waited={waited}s")
169
+ probe_context = (
170
+ " (" + ", ".join(probe_context_parts) + ")" if probe_context_parts else ""
171
+ )
172
+
158
173
  # ── 第二层: Health Check 门控 ──
159
- logger.info("Tier %s: probe scenario, running health check", self.name)
174
+ logger.info(
175
+ "Tier %s: probe scenario%s, running health check",
176
+ self.name,
177
+ probe_context,
178
+ )
160
179
  healthy = await self.vendor.check_health()
161
180
  if not healthy:
162
- logger.warning("Tier %s: health check failed, staying degraded", self.name)
181
+ logger.warning(
182
+ "Tier %s: health check failed, staying degraded",
183
+ self.name,
184
+ )
163
185
  self.record_failure()
164
186
  return False
165
187
 
@@ -66,7 +66,7 @@ class UsageRecorder:
66
66
  )
67
67
  if cost_value is not None:
68
68
  cost_str = cost_value.format()
69
- logger.info(
69
+ logger.debug(
70
70
  "ModelCall: vendor=%s model_requested=%s model_served=%s "
71
71
  "duration=%dms tokens=[in:%d out:%d cache_create:%d cache_read:%d] cost=%s",
72
72
  vendor,
@@ -60,17 +60,14 @@ async def lifespan(app: FastAPI):
60
60
  tier.quota_guard.window_hours,
61
61
  vendor=tier.name,
62
62
  )
63
- tier.quota_guard.load_baseline(total)
63
+ tier.quota_guard.load_baseline(total, vendor=tier.name)
64
64
  if tier.weekly_quota_guard and tier.weekly_quota_guard.enabled:
65
65
  total = await token_logger.query_window_total(
66
66
  tier.weekly_quota_guard.window_hours,
67
67
  vendor=tier.name,
68
68
  )
69
- tier.weekly_quota_guard.load_baseline(total)
69
+ tier.weekly_quota_guard.load_baseline(total, vendor=tier.name)
70
70
 
71
- logger.info(
72
- "coding-proxy started: host=%s port=%d", config.server.host, config.server.port
73
- )
74
71
  yield
75
72
  await router.close()
76
73
  await compat_session_store.close()
@@ -109,7 +106,9 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
109
106
  vendor_cfg, config.failover, mapper, token_store
110
107
  )
111
108
  cb = (
112
- _build_circuit_breaker(vendor_cfg.circuit_breaker)
109
+ _build_circuit_breaker(
110
+ vendor_cfg.circuit_breaker, vendor_name=vendor_cfg.vendor
111
+ )
113
112
  if vendor_cfg.circuit_breaker
114
113
  else None
115
114
  )
@@ -91,13 +91,16 @@ def _find_copilot_vendor(router: Any) -> CopilotVendor | None:
91
91
  return None
92
92
 
93
93
 
94
- def _build_circuit_breaker(cfg: CircuitBreakerConfig) -> CircuitBreaker:
94
+ def _build_circuit_breaker(
95
+ cfg: CircuitBreakerConfig, *, vendor_name: str = ""
96
+ ) -> CircuitBreaker:
95
97
  """从配置构建熔断器实例."""
96
98
  return CircuitBreaker(
97
99
  failure_threshold=cfg.failure_threshold,
98
100
  recovery_timeout_seconds=cfg.recovery_timeout_seconds,
99
101
  success_threshold=cfg.success_threshold,
100
102
  max_recovery_seconds=cfg.max_recovery_seconds,
103
+ vendor_name=vendor_name,
101
104
  )
102
105
 
103
106
 
@@ -42,10 +42,9 @@ def normalize_anthropic_request(body: dict[str, Any]) -> NormalizationResult:
42
42
  处理策略:
43
43
  1. 移除供应商私有块(如 server_tool_use_delta)
44
44
  2. 重写无效/非标准的 tool_use / tool_result ID
45
- 3. **迁移错位的 tool_result 块**:Anthropic API 要求 ``tool_result`` 只能出现在
45
+ 3. **剥离错位的 tool_result 块**:Anthropic API 要求 ``tool_result`` 只能出现在
46
46
  ``user`` 消息中。当检测到非 user 消息中存在 ``tool_result`` 时,
47
- 自动将其提取并挂载到最近的前置 user 消息(或创建新的 user 消息),
48
- 防止上游返回 ``400 invalid_request_error`` 导致全链路降级失败。
47
+ 直接剥离以防止上游返回 ``400 invalid_request_error`` 导致全链路降级失败。
49
48
  """
50
49
  normalized = copy.deepcopy(body)
51
50
  adaptations: list[str] = []
@@ -182,15 +181,6 @@ def normalize_anthropic_request(body: dict[str, Any]) -> NormalizationResult:
182
181
  if stripped_misplaced:
183
182
  _emit_misplaced_tool_result_summary(stripped_misplaced)
184
183
 
185
- # ── 后处理:迁移错位的 tool_result 块 ──────────────────────
186
- # Anthropic API 强制要求 tool_result 仅存在于 user 消息中。
187
- # 多 vendor 场景下(尤其是降级恢复后的对话历史),可能出现
188
- # tool_result 残留在 assistant / system 等非 user 消息中的情况,
189
- # 导致 Anthropic 返回 400 invalid_request_error 并触发全链路降级。
190
- relocated = _relocate_misplaced_tool_results(normalized, adaptations)
191
- if relocated > 0:
192
- adaptations.append(f"tool_result_relocated_from_non_user_messages({relocated})")
193
-
194
184
  return NormalizationResult(
195
185
  body=normalized,
196
186
  adaptations=sorted(set(adaptations)),
@@ -258,108 +248,3 @@ def _emit_misplaced_tool_result_summary(
258
248
  known_count,
259
249
  ", ".join(sorted(known_id_set)),
260
250
  )
261
-
262
-
263
- def _relocate_misplaced_tool_results(
264
- body: dict[str, Any],
265
- adaptations: list[str],
266
- ) -> int:
267
- """检测并将非 user 消息中的 tool_result 块迁移到合法位置.
268
-
269
- 策略:
270
- 1. 扫描所有消息,识别非 user 消息中的 tool_result 块
271
- 2. 将这些块从原消息中移除
272
- 3. 将它们挂载到最近的前置 user 消息末尾(或创建新 user 消息)
273
-
274
- Returns:
275
- 被迁移的 tool_result 块数量。
276
- """
277
- messages = body.get("messages", [])
278
- if not messages:
279
- return 0
280
-
281
- displaced_results: list[tuple[int, dict[str, Any]]] = [] # (msg_idx, block)
282
-
283
- for msg_idx, message in enumerate(messages):
284
- if not isinstance(message, dict):
285
- continue
286
- role = message.get("role")
287
- if role == "user":
288
- continue
289
- content = message.get("content")
290
- if not isinstance(content, list):
291
- continue
292
-
293
- cleaned_content: list[Any] = []
294
- for block in content:
295
- if (
296
- isinstance(block, dict)
297
- and block.get("type") == "tool_result"
298
- and block.get("tool_use_id")
299
- ):
300
- displaced_results.append((msg_idx, dict(block)))
301
- logger.debug(
302
- "发现错位 tool_result: messages[%d], tool_use_id=%s, "
303
- "将迁移至最近的 user 消息",
304
- msg_idx,
305
- block.get("tool_use_id", ""),
306
- )
307
- else:
308
- cleaned_content.append(block)
309
- message["content"] = cleaned_content
310
-
311
- if not displaced_results:
312
- return 0
313
-
314
- # 查找或创建目标 user 消息:优先选择离错位块最近的前置 user 消息
315
- first_displaced_idx = displaced_results[0][0]
316
- target_msg_idx = _find_nearest_user_message(messages, first_displaced_idx)
317
-
318
- if target_msg_idx is None:
319
- # 无前置 user 消息:在消息列表头部插入一个新的 user 消息
320
- messages.insert(
321
- 0,
322
- {
323
- "role": "user",
324
- "content": [block for _, block in displaced_results],
325
- },
326
- )
327
- logger.info(
328
- "已创建新 user 消息(索引 0)以容纳 %d 个错位 tool_result 块",
329
- len(displaced_results),
330
- )
331
- else:
332
- target_msg = messages[target_msg_idx]
333
- target_content = target_msg.get("content")
334
- if not isinstance(target_content, list):
335
- target_content = []
336
- target_msg["content"] = target_content
337
- for _, block in displaced_results:
338
- target_content.append(block)
339
- logger.info(
340
- "已将 %d 个错位 tool_result 块迁移至 messages[%d] (role=user)",
341
- len(displaced_results),
342
- target_msg_idx,
343
- )
344
-
345
- return len(displaced_results)
346
-
347
-
348
- def _find_nearest_user_message(
349
- messages: list[dict[str, Any]],
350
- from_index: int,
351
- ) -> int | None:
352
- """查找离指定索引最近的前置 user 消息.
353
-
354
- Args:
355
- messages: 消息列表
356
- from_index: 起始搜索位置(不包含此位置)
357
-
358
- Returns:
359
- 最近的前置 user 消息索引,若无则返回 None。
360
- """
361
- for idx in range(from_index - 1, -1, -1):
362
- msg = messages[idx]
363
- if isinstance(msg, dict) and msg.get("role") == "user":
364
- return idx
365
- return None
@@ -1,9 +1,10 @@
1
- """Google Antigravity Claude 供应商 — OAuth2 认证 + Gemini 格式转换."""
1
+ """Google Antigravity Claude 供应商 — OAuth2 认证 + Gemini/v1internal 格式转换."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import logging
7
+ import uuid
7
8
  from collections.abc import AsyncIterator
8
9
  from typing import Any
9
10
 
@@ -31,6 +32,15 @@ from .token_manager import BaseTokenManager, TokenAcquireError, TokenErrorKind
31
32
 
32
33
  logger = logging.getLogger(__name__)
33
34
 
35
+ # v1internal 客户端指纹常量(与 Antigravity-Manager 对齐)
36
+ _V1INTERNAL_USER_AGENT = (
37
+ "Antigravity/4.1.31 (Macintosh; Intel Mac OS X 10_15_7) "
38
+ "Chrome/132.0.6834.160 Electron/39.2.3"
39
+ )
40
+ # Cloud Resource Manager API(用于自动发现 GCP project_id)
41
+ _CRM_PROJECTS_URL = "https://cloudresourcemanager.googleapis.com/v1/projects"
42
+ _V1INTERNAL_BASE_URL = "https://cloudcode-pa.googleapis.com/v1internal"
43
+
34
44
 
35
45
  # ── Google OAuth2 Token 管理器(原 antigravity_token_manager.py) ──
36
46
 
@@ -97,10 +107,10 @@ class GoogleOAuthTokenManager(BaseTokenManager):
97
107
  from ..auth.providers.google import GoogleOAuthProvider
98
108
 
99
109
  if not GoogleOAuthProvider.has_required_scopes(scope):
100
- raise TokenAcquireError.with_kind(
101
- "Google access_token 缺少 Antigravity 所需 scope",
102
- kind=TokenErrorKind.INSUFFICIENT_SCOPE,
103
- needs_reauth=True,
110
+ logger.warning(
111
+ "Google access_token scope 不完整(%s),"
112
+ "可能影响 Generative Language API 调用",
113
+ scope,
104
114
  )
105
115
  expires_in = data.get("expires_in", 3600)
106
116
  logger.info("Google OAuth token refreshed, expires_in=%ds", expires_in)
@@ -137,10 +147,124 @@ class AntigravityVendor(TokenBackendMixin, BaseVendor):
137
147
  self._default_model = config.model_endpoint.removeprefix("models/")
138
148
  self._last_request_adaptations: list[str] = []
139
149
  self._safety_settings = config.safety_settings
150
+ # v1internal 协议字段
151
+ self._project_id: str = config.project_id
152
+ self._session_id: str = uuid.uuid4().hex[:16]
153
+ self._message_count: int = 0
154
+ # project_id 自动发现状态
155
+ self._project_id_discovered: str = ""
156
+ self._project_discovery_attempted: bool = False
140
157
 
141
158
  def get_name(self) -> str:
142
159
  return "antigravity"
143
160
 
161
+ def _is_v1internal_mode(self) -> bool:
162
+ """检测是否启用 v1internal 协议模式(与 Antigravity-Manager 对齐)."""
163
+ return bool(self._effective_project_id) and "v1internal" in self._base_url
164
+
165
+ @property
166
+ def _effective_project_id(self) -> str:
167
+ """返回有效的 project_id:显式配置优先,否则使用自动发现的值."""
168
+ return self._project_id or self._project_id_discovered
169
+
170
+ async def _discover_project_id(self, access_token: str) -> str:
171
+ """通过 Cloud Resource Manager API 自动发现用户的 GCP project_id.
172
+
173
+ 利用已有的 cloud-platform OAuth scope 调用 CRM API 列出用户有权限的项目,
174
+ 选择合适的 project_id 后自动切换至 v1internal 模式。
175
+
176
+ Args:
177
+ access_token: 当前有效的 Google OAuth access_token
178
+
179
+ Returns:
180
+ 发现到的 project_id;失败返回空字符串
181
+ """
182
+ if self._project_discovery_attempted:
183
+ return self._project_id_discovered
184
+
185
+ # 已手动配置则跳过
186
+ if self._project_id:
187
+ self._project_discovery_attempted = True
188
+ return ""
189
+
190
+ self._project_discovery_attempted = True
191
+ client = self._get_client()
192
+ try:
193
+ response = await client.get(
194
+ _CRM_PROJECTS_URL,
195
+ headers={"authorization": f"Bearer {access_token}"},
196
+ )
197
+ response.raise_for_status()
198
+
199
+ data = response.json()
200
+ projects = data.get("projects", [])
201
+
202
+ if not projects:
203
+ logger.warning(
204
+ "GCP 项目自动发现完成但未找到任何项目,"
205
+ "回退至标准 GLA 模式。请手动配置 project_id 或确认账号已关联 GCP 项目。"
206
+ )
207
+ return ""
208
+
209
+ # 选择策略:优先 ACTIVE 状态的项目
210
+ selected = None
211
+ for p in projects:
212
+ if p.get("lifecycleState", "") == "ACTIVE":
213
+ selected = p
214
+ break
215
+ if selected is None:
216
+ for p in projects:
217
+ if p.get("lifecycleState", "") != "DELETE_REQUESTED":
218
+ selected = p
219
+ break
220
+ if selected is None:
221
+ selected = projects[0]
222
+
223
+ project_id = selected.get("projectId", "")
224
+ if not project_id:
225
+ logger.warning(
226
+ "GCP 项目 '%s' 缺少 projectId 字段,跳过。",
227
+ selected.get("name", "unknown"),
228
+ )
229
+ return ""
230
+
231
+ # 发现成功:原子性切换到 v1internal 模式
232
+ self._base_url = _V1INTERNAL_BASE_URL
233
+ self._project_id_discovered = project_id
234
+
235
+ # 重建 HTTP 客户端(base_url 是初始化参数)
236
+ if self._client is not None and not self._client.is_closed:
237
+ await self._client.aclose()
238
+ self._client = None
239
+
240
+ logger.info(
241
+ "GCP 项目自动发现成功: project_id=%s, name=%s, "
242
+ "已自动切换至 v1internal 协议模式",
243
+ project_id,
244
+ selected.get("name", "unknown"),
245
+ )
246
+ return project_id
247
+
248
+ except httpx.HTTPStatusError as exc:
249
+ logger.error(
250
+ "GCP 项目自动发现 API 错误 (HTTP %d),回退至标准 GLA 模式。%s",
251
+ exc.response.status_code,
252
+ exc,
253
+ )
254
+ return ""
255
+ except (httpx.TimeoutException, httpx.ConnectError) as exc:
256
+ logger.warning(
257
+ "GCP 项目自动发现网络异常,回退至标准 GLA 模式。%s",
258
+ exc,
259
+ )
260
+ return ""
261
+ except Exception as exc:
262
+ logger.error(
263
+ "GCP 项目自动发现未知异常,回退至标准 GLA 模式。%s",
264
+ exc,
265
+ )
266
+ return ""
267
+
144
268
  def get_capabilities(self) -> VendorCapabilities:
145
269
  return VendorCapabilities(
146
270
  supports_tools=True,
@@ -199,7 +323,12 @@ class AntigravityVendor(TokenBackendMixin, BaseVendor):
199
323
  request_body: dict[str, Any],
200
324
  headers: dict[str, str],
201
325
  ) -> tuple[dict[str, Any], dict[str, str]]:
202
- """转换 Anthropic 请求为 Gemini 格式,注入 Google OAuth token."""
326
+ """转换 Anthropic 请求并注入 Google OAuth token.
327
+
328
+ 支持两种协议模式:
329
+ - 标准 Gemini 模式:直接发送 Gemini 请求体到 generativelanguage.googleapis.com
330
+ - v1internal 模式:将请求体包裹在 v1internal 信封中发送到 cloudcode-pa.googleapis.com
331
+ """
203
332
  resolved_model = self.map_model(request_body.get("model", "unknown"))
204
333
  converted = convert_request(
205
334
  request_body,
@@ -209,6 +338,23 @@ class AntigravityVendor(TokenBackendMixin, BaseVendor):
209
338
  gemini_body = converted.body
210
339
  self._last_request_adaptations = converted.adaptations
211
340
  token = await self._token_manager.get_token()
341
+
342
+ # 懒加载:未配置 project_id 时自动发现并切换 v1internal 模式
343
+ if not self._project_id and not self._project_discovery_attempted:
344
+ discovered = await self._discover_project_id(token)
345
+ if discovered:
346
+ logger.info(
347
+ "已自动启用 v1internal 协议模式(project_id=%s)", discovered
348
+ )
349
+ else:
350
+ logger.info(
351
+ "无法自动发现 GCP project_id,继续使用标准 GLA 模式。"
352
+ "如需启用 v1internal 协议,请在配置中手动指定 project_id。"
353
+ )
354
+
355
+ if self._is_v1internal_mode():
356
+ return self._prepare_v1internal_request(gemini_body, resolved_model, token)
357
+
212
358
  new_headers = {
213
359
  "content-type": "application/json",
214
360
  "authorization": f"Bearer {token}",
@@ -222,10 +368,51 @@ class AntigravityVendor(TokenBackendMixin, BaseVendor):
222
368
  )
223
369
  return gemini_body, new_headers
224
370
 
371
+ def _prepare_v1internal_request(
372
+ self,
373
+ gemini_body: dict[str, Any],
374
+ resolved_model: str,
375
+ token: str,
376
+ ) -> tuple[dict[str, Any], dict[str, str]]:
377
+ """将 Gemini 请求体包裹在 v1internal 信封中(与 Antigravity-Manager 对齐).
378
+
379
+ v1internal 是 Google Cloud Code 内部 API 协议,接受与标准 GLA 相同的 OAuth 凭证,
380
+ 但需要特定的信封格式和客户端指纹 Headers。
381
+ """
382
+ self._message_count += 1
383
+ envelope = {
384
+ "project": self._effective_project_id,
385
+ "requestId": f"agent/antigravity/{self._session_id}/{self._message_count}",
386
+ "request": gemini_body,
387
+ "model": resolved_model,
388
+ "userAgent": "antigravity",
389
+ "requestType": "agent",
390
+ }
391
+ new_headers = {
392
+ "content-type": "application/json",
393
+ "authorization": f"Bearer {token}",
394
+ "user-agent": _V1INTERNAL_USER_AGENT,
395
+ "x-client-name": "antigravity",
396
+ "x-client-version": "4.1.31",
397
+ }
398
+ logger.debug(
399
+ "_prepare_v1internal_request: model=%s -> %s, project=%s, requestId=%s",
400
+ resolved_model,
401
+ resolved_model,
402
+ self._effective_project_id,
403
+ envelope["requestId"],
404
+ )
405
+ return envelope, new_headers
406
+
225
407
  def _mark_scope_error_if_needed(self, error_text: str) -> None:
226
408
  lowered = error_text.lower()
227
409
  if "access_token_scope_insufficient" not in lowered:
228
410
  return
411
+ logger.error(
412
+ "Generative Language API 拒绝访问(ACCESS_TOKEN_SCOPE_INSUFFICIENT)。"
413
+ "如使用标准 GLA 端点,请确认凭证已授权正确的 scope;"
414
+ "建议切换至 v1internal 协议(配置 project_id)以获得更好的兼容性。"
415
+ )
229
416
  self._token_manager.mark_error(
230
417
  "Google access_token scope 不足,当前凭证不能调用 Generative Language API",
231
418
  kind=TokenErrorKind.INSUFFICIENT_SCOPE,
@@ -243,6 +430,15 @@ class AntigravityVendor(TokenBackendMixin, BaseVendor):
243
430
  result["resolved_model"] = self._last_resolved_model
244
431
  if self._last_model_resolution_reason:
245
432
  result["model_resolution_reason"] = self._last_model_resolution_reason
433
+ # project_id 发现诊断
434
+ result["project_id_source"] = (
435
+ "configured"
436
+ if self._project_id
437
+ else ("discovered" if self._project_id_discovered else "none")
438
+ )
439
+ if self._project_id_discovered:
440
+ result["discovered_project_id"] = self._project_id_discovered
441
+ result["is_v1internal_mode"] = self._is_v1internal_mode()
246
442
  return result
247
443
 
248
444
  async def send_message(
@@ -250,11 +446,15 @@ class AntigravityVendor(TokenBackendMixin, BaseVendor):
250
446
  request_body: dict[str, Any],
251
447
  headers: dict[str, str],
252
448
  ) -> VendorResponse:
253
- """覆写: Gemini 端点 + 响应逆转换."""
449
+ """覆写: Gemini / v1internal 端点 + 响应逆转换."""
254
450
  body, prepared_headers = await self._prepare_request(request_body, headers)
255
451
  client = self._get_client()
256
452
  resolved_model = self._last_resolved_model
257
- endpoint = f"/models/{resolved_model}:generateContent"
453
+ endpoint = (
454
+ ":generateContent"
455
+ if self._is_v1internal_mode()
456
+ else f"/models/{resolved_model}:generateContent"
457
+ )
258
458
 
259
459
  logger.debug("send_message: POST %s", endpoint)
260
460
  response = await client.post(endpoint, json=body, headers=prepared_headers)
@@ -292,11 +492,15 @@ class AntigravityVendor(TokenBackendMixin, BaseVendor):
292
492
  request_body: dict[str, Any],
293
493
  headers: dict[str, str],
294
494
  ) -> AsyncIterator[bytes]:
295
- """覆写: Gemini SSE 流 -> Anthropic SSE 流适配."""
495
+ """覆写: Gemini / v1internal SSE 流 -> Anthropic SSE 流适配."""
296
496
  body, prepared_headers = await self._prepare_request(request_body, headers)
297
497
  client = self._get_client()
298
498
  resolved_model = self._last_resolved_model
299
- endpoint = f"/models/{resolved_model}:streamGenerateContent?alt=sse"
499
+ endpoint = (
500
+ ":streamGenerateContent?alt=sse"
501
+ if self._is_v1internal_mode()
502
+ else f"/models/{resolved_model}:streamGenerateContent?alt=sse"
503
+ )
300
504
 
301
505
  logger.debug("send_message_stream: POST %s", endpoint)
302
506
 
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: coding-proxy
3
- Version: 0.2.0a2
4
- Summary: A High-Availability, Transparent, and Smart Multi-Vendor Proxy for Claude Code. Support Claude Plans, GitHub Copilot, Google Antigravity, ZAI/GLM.
3
+ Version: 0.2.1
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
7
7
  Project-URL: Bug Tracker, https://github.com/ThreeFish-AI/coding-proxy/issues
@@ -56,7 +56,7 @@ When you're deeply immersed in your coding "zone" with **Claude Code** (or any A
56
56
 
57
57
  ## 🌟 Core Features
58
58
 
59
- - **⛓️ N-tier Chained Failover**: Automatically downgrades from official Claude Plans, gracefully falling back to GitHub Copilot, then Google Antigravity, with Zhipu GLM acting as the ultimate safety net.
59
+ - **⛓️ N-tier Chained Failover**: Autonomous descending sequence, supporting Claude's official plans, as well as Coding Plans from GitHub Copilot, Z AI, MiniMax, Alibaba Qwen, Xiaomi, Kimi, Doubao, etc.
60
60
  - **🛡️ Smart Resilience & Quota Guardians**: Every single vendor node comes fully armed with an independent **Circuit Breaker** and **Quota Guard** to proactively dodge avalanches without breaking a sweat.
61
61
  - **👻 Phantom-like Transparency**: **100% transparent** to the client! No code tweaks required. Overwrite `ANTHROPIC_BASE_URL` with a single line, and you're good to go.
62
62
  - **🔄 Universal Alchemy (Formats & Models)**: Native support for two-way request/streaming (SSE) translations between Anthropic ←→ Gemini. Plus, auto/DIY model name mapping (e.g., effortlessly morphing `claude-*` into `glm-*`).
@@ -9,7 +9,7 @@ coding/proxy/auth/providers/__init__.py,sha256=hnGL_aSHcMxiZHK6HKPWD0_tWSPcwuxwQ
9
9
  coding/proxy/auth/providers/base.py,sha256=TOtCi2b81-UBdEoWMv7HbYSmRxAjGSvnF1yBxazqai0,1092
10
10
  coding/proxy/auth/providers/github.py,sha256=xH6yygAzt8vI-MXV8EHl2tg4RcOmLaLBns93PBCyVG8,4835
11
11
  coding/proxy/auth/providers/google.py,sha256=MhbM5PXmgwQBgWCMDkhK_7GYyvS-IdPV4ATxKYH6WXM,8402
12
- coding/proxy/cli/__init__.py,sha256=4gOigkblVw_TgoR8NpkSQoe5vCYi7hAE66oGkQdWWfM,7617
12
+ coding/proxy/cli/__init__.py,sha256=glGVFdTj8fMLYSSWNtFGU4u9D2AoYBTLNgaSkjyQEnM,7911
13
13
  coding/proxy/cli/auth_commands.py,sha256=tN5jWJo8sJP8jgoN4WH5iTl9rhi4xWPLMptgeTHIFpE,9212
14
14
  coding/proxy/cli/banner.py,sha256=gat7QGpfocL0wiAw3-MSUsCviyc59Sf-XswOp7Pg6LI,1694
15
15
  coding/proxy/compat/__init__.py,sha256=-msRszArsk2YJJtOeaidYDd1tAQEzeE91LvCi1CyMis,721
@@ -17,21 +17,22 @@ 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=oVs8vDylKW9MflEZWgroFZlHV1IrqS2UdhyZu2OMtDY,15695
20
+ coding/proxy/config/config.default.yaml,sha256=UjtM6b4FNAJvilCm2fgjNvN5hPfDHt0EYKLlvL_0UDU,16404
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=aJMhfCRyoZIvemM3Q2_KV9rpWxUsFnoY0ZdCr4TwSs8,11765
24
24
  coding/proxy/config/schema.py,sha256=yDPQfxUzJToAfXH-fJxoujXoYAb6WMeq7VyySbvMYC8,12205
25
- coding/proxy/config/server.py,sha256=um6SJHat9Z_DPjE0AzpdbmbA0fTB0KovUlkNl_eJX-k,509
26
- coding/proxy/config/vendors.py,sha256=Kw4IctoZBgB4yd7GlnoubWHRrKqmqSC6zY87oH3EPTQ,2796
25
+ coding/proxy/config/server.py,sha256=NJbx4L1YuhfwmYpC8ZxiqUdqROoA0CfObWf-ujqjCPo,996
26
+ coding/proxy/config/vendors.py,sha256=11npZ5Ad9tDw6AtXjonVkU01rOkAQhnA5aRf7ZtyWPc,2868
27
27
  coding/proxy/convert/__init__.py,sha256=0D3Q9TdY_AWCaMMf9f_i3jn0RIiWmqlcIAA79Ki8uJc,458
28
28
  coding/proxy/convert/anthropic_to_gemini.py,sha256=9mRQ0CRAGJyWQADNlfMqoCJ_vY8ZZBGWaS_R8Vbe_l0,13201
29
29
  coding/proxy/convert/anthropic_to_openai.py,sha256=crE8gi780Tr-dI58hce75BiaKzlh_dEyzvMxwLgAa8A,13435
30
30
  coding/proxy/convert/gemini_sse_adapter.py,sha256=b7zQ9wBBn1bbG46WpLrAYOl0ExpyMTzpTorxoTadWaM,7395
31
31
  coding/proxy/convert/gemini_to_anthropic.py,sha256=EE_rUsLmWTsF2QSYWqIYzsjyk1mKXFp2sziqj_S2W5U,3446
32
32
  coding/proxy/convert/openai_to_anthropic.py,sha256=8rg8NZs_1up27MixrXRJAfmSiYrOkh_lkAJuytDGZow,3694
33
- coding/proxy/logging/__init__.py,sha256=UZDWoTbgQNZadUZs56DG4TDK-X9F7wYUjTMgl2wfXuk,1664
33
+ coding/proxy/logging/__init__.py,sha256=vql4zfdnvHZCTzajqMCGATu1uSA7zYWQiGTkk8Eq_zs,6647
34
34
  coding/proxy/logging/db.py,sha256=uARNaaAXWxemwfyybp660ujpi6UikNtFokG0pzXYwR8,19058
35
+ coding/proxy/logging/formatters.py,sha256=8LDqiNAxGcfn9fsHqZzdK9TKGqOGNAOls75B1byBjnM,823
35
36
  coding/proxy/logging/stats.py,sha256=JlhJC4a2RmuCjbaseSUONScbcgn41KNR_sNsZ0OScbw,9203
36
37
  coding/proxy/model/__init__.py,sha256=E8E59yabP-CF5GIwHE4OEGPLiJj3yTLjFWmCorkQTxc,3947
37
38
  coding/proxy/model/auth.py,sha256=NiiIPdLdxPtuHNrsGoxFASUXwJU5pkDuVRorQe_1Z-Q,934
@@ -41,22 +42,22 @@ coding/proxy/model/pricing.py,sha256=KHYsLQJJkEEuAeX8iB182znfpfSPTf9KI1hPchphqnc
41
42
  coding/proxy/model/token.py,sha256=yCh-66_nFDAk7wKbYy-9ymdgae3SaJ47-fkYfYLO3Oo,1818
42
43
  coding/proxy/model/vendor.py,sha256=Yg4AYN7tgjHaGWRGEccCs3AdO8vBc-KxIelnqRowpyo,7898
43
44
  coding/proxy/routing/__init__.py,sha256=2Tpc6MQ5Oy_w-YlEWQVDSgcSgiHp3OwKOABIjj5kfHA,1595
44
- coding/proxy/routing/circuit_breaker.py,sha256=fKodIYxJ-3hhil2rEjsGqvyHTspliN_eS8QyL3BFI8s,7189
45
+ coding/proxy/routing/circuit_breaker.py,sha256=hOyoY_RWB5dTVbipyuiWfAelnva3cZRLbXrSmSn8KTs,8096
45
46
  coding/proxy/routing/error_classifier.py,sha256=oDxp69sCb-pdfe1hWce29A9tsN3jAbhqfl2fRECBtCo,3747
46
- coding/proxy/routing/executor.py,sha256=xQw3rtHd00n3BBgUHzqAli1GUoFNOxc0odKEaq-Dw7A,28206
47
+ coding/proxy/routing/executor.py,sha256=vnXmmaWw0w49HhKsNine37Hnye04NSZ0vc9ghMzqLdQ,30268
47
48
  coding/proxy/routing/model_mapper.py,sha256=b72CGRdusLAwoq7p8-8TWAv9-Zv8BozssiZC8XnNTx4,3574
48
- coding/proxy/routing/quota_guard.py,sha256=VBJSgS1Wjw8RBwyfCdegWrBXGTbVmmU3bA3Tf81O8ns,6558
49
+ coding/proxy/routing/quota_guard.py,sha256=TRJs3mjdRMc_u0HCw-hZn--osha_m11dEtAUxOO2P5A,6806
49
50
  coding/proxy/routing/rate_limit.py,sha256=i2cCqtbmXrP6wjRUTWXLP4DdYwVj0C4o59QdYGkPQj0,5122
50
51
  coding/proxy/routing/retry.py,sha256=KEYVToBkBOtXdqY7He70RrtVWFqIpnOQf2VVksdLrlk,2386
51
52
  coding/proxy/routing/router.py,sha256=bXaglxuT-5qYzrSMk7ZE4mpQynP4Z6F2pm9hnCbdG90,3440
52
53
  coding/proxy/routing/session_manager.py,sha256=kpEPCo67CdsELX71hoe6G7sb2dcda7gTNL0FtpgRK7I,2950
53
- coding/proxy/routing/tier.py,sha256=U12Mw0eTE1AO5RuHNpoOuXDdujz_Hkx_iyIrqkZbtyA,7024
54
+ coding/proxy/routing/tier.py,sha256=OBrJiMxfLCxXvZfARD5oNmuhpYASKnyrW9sOCHLdQ1g,7777
54
55
  coding/proxy/routing/usage_parser.py,sha256=j4G0ArFduQ2D4Yeuad94DVlwdc-JvSh7SJLVzc-hLcs,8480
55
- coding/proxy/routing/usage_recorder.py,sha256=pSs2r79fOrrq2cWJP-P5KKFnnXf62-3gYLaxAwndFi0,6272
56
+ coding/proxy/routing/usage_recorder.py,sha256=pObOrX2yIITTiyojl1fJcqO0yWWpbP4KqsJvFdmlt04,6273
56
57
  coding/proxy/server/__init__.py,sha256=KeH7mEu36v9v27m3VgeSxSeFz9sLTJrxS_EVATJ7Vks,20
57
- coding/proxy/server/app.py,sha256=hxCKb8FVEOYCvC84agUtwECajtqLqNgkTIEpEySJaGs,5613
58
- coding/proxy/server/factory.py,sha256=I4asjFw_1ET49DC-xkCpfV7oyfSv4G6xUB_Z5N_SHY8,9920
59
- coding/proxy/server/request_normalizer.py,sha256=o0N27hnrBjWxsDQ_c8i7ooNcyv1NVVQFmdQLZO0BQxY,14648
58
+ coding/proxy/server/app.py,sha256=kRGgb772dZu8200LPnn7Nt0IU5oagcbBf_Vc5ynxxzE,5599
59
+ coding/proxy/server/factory.py,sha256=w8VFvxoogw9K9sO8MlT6bIP7xM7mR6sCohrZle9y_Gg,9985
60
+ coding/proxy/server/request_normalizer.py,sha256=F_mgxxuA3i7cN1CEWlto7Mm9VT_QG2QNspiUWeYVBpM,10511
60
61
  coding/proxy/server/responses.py,sha256=i0ugnLRNOdRYGHEWxkwsxR35ChmdMQsSaD8AjRluTn4,2167
61
62
  coding/proxy/server/routes.py,sha256=QeEsYczjvPfVhOrED2qe1V6CpwVBZbQHs8dP0OGdGXQ,11734
62
63
  coding/proxy/streaming/__init__.py,sha256=0al5TC-zJt8Bz0CibTmd8WPza-Cs-qcuZWvT2fKPqHI,23
@@ -64,7 +65,7 @@ coding/proxy/streaming/anthropic_compat.py,sha256=cycYiJ-glN88OmfLTR7FroHRethONl
64
65
  coding/proxy/vendors/__init__.py,sha256=fehSpQ2-kUlZY6N8cNMGVJYMXspQmi3V4e0FgC4Ay4k,1011
65
66
  coding/proxy/vendors/alibaba.py,sha256=vYhvk8hZEeOpqUrtGT-uaK89y6uolrDUAT2BvTD_IQY,876
66
67
  coding/proxy/vendors/anthropic.py,sha256=KA_fvOxagGBggH2pc3l9Zoyl_XYUyRdfR8bI-eVj_e4,6328
67
- coding/proxy/vendors/antigravity.py,sha256=zVl2fguxyIy3OjkosZYr2n5tR8dEEIjxazBEXY7v6BQ,13300
68
+ coding/proxy/vendors/antigravity.py,sha256=sz2-TSIUe9YDVen7A4d9K6lmhyh4jGWN3dppfabSJg0,21431
68
69
  coding/proxy/vendors/base.py,sha256=vrAaI_4uLtzaFcPWtBStVMHU5AgkCWTNLEgVeoHHgLE,14781
69
70
  coding/proxy/vendors/copilot.py,sha256=qAFTO2xMqnawaFlvZS2a9-7f_UEkfODIFfDlgOBiQl4,29590
70
71
  coding/proxy/vendors/copilot_models.py,sha256=UckIQYA4qLyNwEA09koQGBOZ65Nxhuo3ytUuDNqtzRU,15514
@@ -78,8 +79,8 @@ coding/proxy/vendors/native_anthropic.py,sha256=SxtM71PDci0gqLqiwCrFnT410SnSoD7F
78
79
  coding/proxy/vendors/token_manager.py,sha256=s10t4Com0jNnKGkPyJ_HpG5SjHrCEJvfArEOAaPKA_k,4189
79
80
  coding/proxy/vendors/xiaomi.py,sha256=E-GcmJBZh7GOtDFonxZmlf0hKRhrlrXzL0IxHFRYcRo,860
80
81
  coding/proxy/vendors/zhipu.py,sha256=3j_rqNFu1CX-B5ugtrL6Y1OeWSy9yiqsVa9Bi1ssaAA,1062
81
- coding_proxy-0.2.0a2.dist-info/METADATA,sha256=XoO6Pxu5OOCNg8X8Rya0rvx85IJfkA9bmUZVZXYjGxc,10782
82
- coding_proxy-0.2.0a2.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
83
- coding_proxy-0.2.0a2.dist-info/entry_points.txt,sha256=moIVzt5ho0Wk9B47LOo2SEAbhzuDDHWi-EfM30U0XBg,54
84
- coding_proxy-0.2.0a2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
85
- coding_proxy-0.2.0a2.dist-info/RECORD,,
82
+ coding_proxy-0.2.1.dist-info/METADATA,sha256=OMSKWneBEiokjw4UdfGaHzuFBAU8tAQh1YjHY90WVAA,10817
83
+ coding_proxy-0.2.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
84
+ coding_proxy-0.2.1.dist-info/entry_points.txt,sha256=moIVzt5ho0Wk9B47LOo2SEAbhzuDDHWi-EfM30U0XBg,54
85
+ coding_proxy-0.2.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
86
+ coding_proxy-0.2.1.dist-info/RECORD,,