coding-proxy 0.5.2a8__py3-none-any.whl → 0.6.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.
Files changed (43) hide show
  1. coding/proxy/auth/runtime.py +8 -0
  2. coding/proxy/auth/store.py +4 -4
  3. coding/proxy/cli/__init__.py +177 -50
  4. coding/proxy/cli/auth_commands.py +47 -8
  5. coding/proxy/cli/config_commands.py +232 -0
  6. coding/proxy/config/auth_schema.py +6 -2
  7. coding/proxy/config/config.default.yaml +55 -19
  8. coding/proxy/config/defaults.py +34 -0
  9. coding/proxy/config/home.py +188 -0
  10. coding/proxy/config/importer.py +812 -0
  11. coding/proxy/config/loader.py +16 -47
  12. coding/proxy/config/normalize.py +300 -0
  13. coding/proxy/config/resolver.py +412 -0
  14. coding/proxy/config/routing.py +13 -4
  15. coding/proxy/config/schema.py +8 -4
  16. coding/proxy/config/secrets.py +286 -0
  17. coding/proxy/config/server.py +8 -3
  18. coding/proxy/config/service.py +1182 -0
  19. coding/proxy/config/session_policy.py +64 -0
  20. coding/proxy/config/store.py +384 -0
  21. coding/proxy/config/ui_registry.py +700 -0
  22. coding/proxy/routing/executor.py +313 -36
  23. coding/proxy/routing/model_mapper.py +14 -5
  24. coding/proxy/routing/quota_guard.py +31 -7
  25. coding/proxy/routing/router.py +6 -0
  26. coding/proxy/routing/session_policy.py +42 -11
  27. coding/proxy/server/app.py +30 -6
  28. coding/proxy/server/config_routes.py +360 -0
  29. coding/proxy/server/dashboard.py +296 -78
  30. coding/proxy/server/generations.py +762 -0
  31. coding/proxy/server/routes.py +73 -22
  32. coding/proxy/server/security.py +350 -0
  33. coding/proxy/server/static/config/config.css +181 -0
  34. coding/proxy/server/static/config/config.js +1279 -0
  35. coding/proxy/vendors/antigravity.py +10 -0
  36. coding/proxy/vendors/base.py +10 -0
  37. coding/proxy/vendors/native_anthropic.py +4 -0
  38. coding/proxy/vendors/token_manager.py +2 -1
  39. {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.1.dist-info}/METADATA +15 -8
  40. {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.1.dist-info}/RECORD +43 -28
  41. {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.1.dist-info}/WHEEL +1 -1
  42. {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.1.dist-info}/entry_points.txt +0 -0
  43. {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.1.dist-info}/licenses/LICENSE +0 -0
@@ -33,6 +33,14 @@ class RuntimeReauthCoordinator:
33
33
  - 重认证期间 TokenManager 持续抛 TokenAcquireError
34
34
  - Router 触发 failover → 熔断器 OPEN → 请求路由到下一层级
35
35
  - 重认证完成后 TokenManager 获得新凭证 → 熔断器恢复 → 后端可用
36
+
37
+ .. warning::
38
+ ``server/generations.py`` 的 generation 交接逻辑直接读写本类私有属性
39
+ (``_providers`` / ``_states`` / ``_locks`` / ``_last_error`` /
40
+ ``_last_completed`` / ``_token_updaters`` / ``_token_store``),
41
+ 行为由 ``tests/test_generations_app.py`` 锁定。重命名属性、加
42
+ ``__slots__`` 或改动数据结构时必须同步 ``_relay_reauth`` /
43
+ ``_finish_relay`` / ``_forward_tokens``。
36
44
  """
37
45
 
38
46
  def __init__(
@@ -1,4 +1,4 @@
1
- """Token 持久化存储 — ~/.coding-proxy/tokens.json.
1
+ """Token 持久化存储 — $CODING_PROXY_HOME/tokens.json.
2
2
 
3
3
  ``ProviderTokens`` 数据模型已迁移至 :mod:`coding.proxy.model.auth`。
4
4
  本文件保留 ``TokenStoreManager`` 持久化管理器,类型通过 re-export 提供。
@@ -14,19 +14,19 @@ import logging
14
14
  from pathlib import Path
15
15
  from typing import Any
16
16
 
17
+ from ..config.home import default_token_store_path
18
+
17
19
  # noqa: F401
18
20
  from ..model.auth import ProviderTokens
19
21
 
20
22
  logger = logging.getLogger(__name__)
21
23
 
22
- _DEFAULT_STORE_PATH = Path("~/.coding-proxy/tokens.json")
23
-
24
24
 
25
25
  class TokenStoreManager:
26
26
  """管理所有 Provider 的 Token 持久化."""
27
27
 
28
28
  def __init__(self, store_path: Path | None = None) -> None:
29
- self._path = (store_path or _DEFAULT_STORE_PATH).expanduser()
29
+ self._path = (store_path or default_token_store_path()).expanduser()
30
30
  self._data: dict[str, dict[str, Any]] = {}
31
31
 
32
32
  def load(self) -> None:
@@ -1,6 +1,6 @@
1
1
  """CLI 入口 — Typer 命令行工具.
2
2
 
3
- Auth 子命令已正交提取至 :mod:`.auth_commands`.
3
+ Auth / Config 子命令已正交提取至 :mod:`.auth_commands` / :mod:`.config_commands`.
4
4
  """
5
5
 
6
6
  from __future__ import annotations
@@ -17,41 +17,35 @@ if TYPE_CHECKING:
17
17
 
18
18
  from rich.console import Console
19
19
 
20
- from ..config.loader import load_config
21
20
  from ..logging.db import TimePeriod, TokenLogger
22
21
  from ..logging.stats import show_usage
22
+ from .auth_commands import _build_token_store, _offline_config
23
23
  from .auth_commands import app as auth_app
24
24
  from .auth_commands import auto_login_if_needed as _auto_login_if_needed
25
+ from .config_commands import app as config_app
25
26
 
26
- app = typer.Typer(name="coding-proxy", help="Claude Code 多供应商智能代理服务")
27
+ app = typer.Typer(
28
+ name="coding-proxy",
29
+ help="Claude Code 多供应商智能代理服务",
30
+ pretty_exceptions_show_locals=False,
31
+ )
27
32
  console = Console()
33
+ err_console = Console(stderr=True)
28
34
  logger = logging.getLogger(__name__)
29
35
 
30
- # 注册 Auth 子应用
36
+ # 注册 Auth / Config 子应用
31
37
  app.add_typer(auth_app, name="auth")
38
+ app.add_typer(config_app, name="config")
32
39
 
33
40
  # 注册 Session 子应用
34
- session_app = typer.Typer(name="session", help="管理 Session-Vendor 运行时绑定")
41
+ session_app = typer.Typer(
42
+ name="session",
43
+ help="管理 Session-Vendor 运行时绑定",
44
+ pretty_exceptions_show_locals=False,
45
+ )
35
46
  app.add_typer(session_app, name="session")
36
47
 
37
48
 
38
- def _build_token_store(cfg_path: Path | None = None):
39
- """按配置解析 Token Store 路径并完成加载."""
40
- from ..auth.store import TokenStoreManager
41
-
42
- cfg = load_config(cfg_path)
43
- store = TokenStoreManager(
44
- store_path=Path(cfg.auth.token_store_path)
45
- if cfg.auth.token_store_path
46
- else None,
47
- )
48
- store.load()
49
- logger.debug(
50
- "OAuth token store loaded from config path: %s", cfg.auth.token_store_path
51
- )
52
- return cfg, store
53
-
54
-
55
49
  def _resolve_period(
56
50
  *,
57
51
  days: int = 7,
@@ -84,45 +78,155 @@ def start(
84
78
  port: int | None = typer.Option(None, "--port", "-p", help="监听端口"),
85
79
  host: str | None = typer.Option(None, "--host", "-h", help="监听地址"),
86
80
  ) -> None:
87
- """启动代理服务."""
81
+ """启动代理服务.
82
+
83
+ uvicorn 运行 :class:`GenerationManager`:Dashboard 保存配置后进程内热切换,无需重启;
84
+ 存储的配置无效时以 degraded 模式启动(仅 Dashboard 与管理 API 可用)。
85
+ """
88
86
  import uvicorn
89
87
 
88
+ from ..config.importer import (
89
+ ExplicitConfigMissingError,
90
+ LegacyConfigError,
91
+ StaleYamlError,
92
+ boot,
93
+ )
94
+ from ..config.resolver import MODE_LEGACY
95
+ from ..config.secrets import MasterKeyError
96
+ from ..config.store import ConfigStoreError
90
97
  from ..server.app import create_app
98
+ from ..server.generations import GenerationManager
91
99
  from .banner import print_banner
92
100
 
93
101
  cfg_path = _resolve_config_path(config)
94
- cfg = load_config(cfg_path)
102
+ try:
103
+ booted = boot(cfg_path)
104
+ except (
105
+ StaleYamlError,
106
+ ExplicitConfigMissingError,
107
+ LegacyConfigError,
108
+ MasterKeyError,
109
+ ConfigStoreError,
110
+ ) as exc:
111
+ err_console.print(f"[red]{exc}[/red]")
112
+ raise typer.Exit(2) from None
113
+ resolved = booted.resolved
114
+ for notice in booted.notices:
115
+ err_console.print(f"[yellow]{notice}[/yellow]")
116
+ if resolved.mode == MODE_LEGACY:
117
+ err_console.print("[yellow]配置导入失败,本次以只读方式运行旧 YAML[/yellow]")
118
+ cfg = resolved.config
119
+ if cfg is None:
120
+ for error in resolved.errors:
121
+ loc = ".".join(map(str, error["loc"])) or "<root>"
122
+ err_console.print(f"[red]{loc}: {error['msg']}[/red]")
123
+ err_console.print(
124
+ "[red]存储的配置无效,以 degraded 模式启动(代理接口返回 503);"
125
+ "请在 Dashboard → Config 或用 `coding-proxy config` 修复[/red]"
126
+ )
95
127
 
128
+ from ..logging import build_log_config
129
+
130
+ manager = GenerationManager(boot=booted, build=create_app)
131
+ server_cfg, logging_cfg = manager.server, manager.logging
96
132
  if port:
97
- cfg.server.port = port
133
+ server_cfg.port = port
134
+ resolved.sources["server.port"] = "cli"
98
135
  if host:
99
- cfg.server.host = host
100
-
101
- # 自动登录检查
102
- asyncio.run(_auto_login_if_needed(cfg_path))
136
+ server_cfg.host = host
137
+ resolved.sources["server.host"] = "cli"
103
138
 
104
- from ..logging import build_log_config
139
+ # 自动登录检查(配置无效时跳过)
140
+ if cfg is not None:
141
+ asyncio.run(_auto_login_if_needed(cfg_path, cfg=cfg))
105
142
 
106
- fastapi_app = create_app(cfg)
143
+ # 打印启动品牌横幅与带 admin token 的 Dashboard 链接(仅控制台,不进日志)
144
+ print_banner(console, host=server_cfg.host, port=server_cfg.port)
145
+ _print_dashboard_url(server_cfg.host, server_cfg.port, server_cfg.allowed_hosts)
107
146
 
108
- # 打印启动品牌横幅
109
- print_banner(console, host=cfg.server.host, port=cfg.server.port)
110
-
111
- # 解析文件日志路径:未显式配置时使用默认值
112
- _file_path: str | None = cfg.logging.file or ".logs/coding-proxy.log"
147
+ # 解析文件日志路径:未设置时用默认值;显式空串 = 禁用文件日志(透传 build_log_config)
148
+ _file_path: str | None = (
149
+ logging_cfg.file if logging_cfg.file is not None else ".logs/coding-proxy.log"
150
+ )
113
151
  uvicorn.run(
114
- fastapi_app,
115
- host=cfg.server.host,
116
- port=cfg.server.port,
152
+ manager,
153
+ host=server_cfg.host,
154
+ port=server_cfg.port,
117
155
  log_config=build_log_config(
118
- level=cfg.logging.level,
156
+ level=logging_cfg.level,
119
157
  file_path=_file_path,
120
- max_bytes=cfg.logging.max_bytes,
121
- backup_count=cfg.logging.backup_count,
158
+ max_bytes=logging_cfg.max_bytes,
159
+ backup_count=logging_cfg.backup_count,
122
160
  ),
161
+ proxy_headers=False,
123
162
  )
124
163
 
125
164
 
165
+ def _dashboard_host(host: str) -> str:
166
+ """监听地址 → 浏览器可访问的主机(通配地址改用 loopback,IPv6 加方括号)."""
167
+ if host in ("", "0.0.0.0"):
168
+ return "127.0.0.1"
169
+ if host == "::":
170
+ return "[::1]"
171
+ return f"[{host}]" if ":" in host else host
172
+
173
+
174
+ def _dashboard_host_rejected(shown: str, allowed_hosts: list[str]) -> bool:
175
+ """打印的主机会被管理面 Host 校验(403)拒绝.
176
+
177
+ IP 字面量即监听地址,中间件按本机地址放行;主机名须在 loopback ∪ allowed_hosts 中。
178
+ """
179
+ import ipaddress
180
+
181
+ from ..server import security
182
+
183
+ parsed = security.split_host(shown)
184
+ if parsed is None:
185
+ return True
186
+ name = parsed[0]
187
+ try:
188
+ ipaddress.ip_address(name)
189
+ return False
190
+ except ValueError:
191
+ pass
192
+ return name not in security.LOOPBACK_HOSTS | security.normalize_allowed_hosts(
193
+ allowed_hosts
194
+ )
195
+
196
+
197
+ def _print_dashboard_url(
198
+ host: str, port: int, allowed_hosts: list[str] | None = None
199
+ ) -> None:
200
+ """``#admin=`` fragment 不随请求发送,token 不会出现在服务端访问日志."""
201
+ import json
202
+
203
+ from ..config.home import load_or_create_admin_token
204
+ from ..config.store import ConfigStoreError
205
+
206
+ shown = _dashboard_host(host)
207
+ url = f"http://{shown}:{port}/dashboard?tab=config"
208
+ try:
209
+ url += f"#admin={load_or_create_admin_token()}"
210
+ except (OSError, ConfigStoreError) as exc:
211
+ err_console.print(
212
+ f"[yellow]admin token 不可用({type(exc).__name__}),"
213
+ "Config 页需执行 `coding-proxy config token` 后解锁[/yellow]"
214
+ )
215
+ console.print(f"Dashboard: {url}", markup=False, highlight=False, soft_wrap=True)
216
+ allowed = list(allowed_hosts or [])
217
+ if _dashboard_host_rejected(shown, allowed):
218
+ value = json.dumps([*allowed, shown.strip("[]")], ensure_ascii=False)
219
+ err_console.print(
220
+ f"主机 {shown} 不在 server.allowed_hosts 中,Dashboard 与管理 API 会返回 403;"
221
+ f"请执行 coding-proxy config set server.allowed_hosts '{value}' 后重启,"
222
+ f"或经 SSH 隧道访问 http://127.0.0.1:{port}/dashboard",
223
+ style="yellow",
224
+ markup=False,
225
+ highlight=False,
226
+ soft_wrap=True,
227
+ )
228
+
229
+
126
230
  @app.command()
127
231
  def status(
128
232
  port: int = typer.Option(3392, "--port", "-p", help="代理服务端口"),
@@ -177,8 +281,8 @@ def usage(
177
281
  -t 全部历史(按供应商+模型聚合)
178
282
  """
179
283
  period, count = _resolve_period(days=days, week=week, month=month, total=total)
180
- cfg = load_config(Path(db_path) if db_path else None)
181
- token_logger = TokenLogger(cfg.db_path)
284
+ cfg = _offline_config(decrypt=False)
285
+ token_logger = TokenLogger(Path(db_path).expanduser() if db_path else cfg.db_path)
182
286
  # 解析逗号分隔的多 vendor(如 "anthropic,zhipu" → ["anthropic", "zhipu"])
183
287
  vendor_filter: str | list[str] | None = None
184
288
  if vendor:
@@ -275,25 +379,44 @@ def reset(
275
379
  def session_bind(
276
380
  key: str = typer.Option(..., "--key", "-k", help="Session key"),
277
381
  vendor: str = typer.Option(
278
- ..., "--vendor", "-v", help="绑定 vendor(逗号分隔多个)"
382
+ None, "--vendor", "-v", help="绑定 vendor(逗号分隔多个,与 --model 可组合)"
383
+ ),
384
+ model: str = typer.Option(
385
+ None,
386
+ "--model",
387
+ "-m",
388
+ help="绑定模型(须在 config 的 bindable_models 清单内,与 --vendor 可组合)",
279
389
  ),
280
390
  port: int = typer.Option(3392, "--port", "-p", help="代理服务端口"),
281
391
  ) -> None:
282
- """为指定 Session 绑定 vendor 优先级."""
392
+ """为指定 Session 绑定 vendor 优先级与可选的会话级模型覆盖."""
283
393
  import httpx as _httpx
284
394
 
285
- vendors = [v.strip() for v in vendor.split(",") if v.strip()]
395
+ if not vendor and not model:
396
+ console.print("[red]至少提供 --vendor 或 --model 之一[/red]")
397
+ raise typer.Exit(1)
398
+
399
+ payload: dict = {"session_key": key}
400
+ if vendor:
401
+ payload["vendors"] = [v.strip() for v in vendor.split(",") if v.strip()]
402
+ if model:
403
+ payload["model"] = model
286
404
  try:
287
405
  resp = _httpx.put(
288
406
  f"http://127.0.0.1:{port}/api/session-vendor",
289
- json={"session_key": key, "vendors": vendors},
407
+ json=payload,
290
408
  timeout=5,
291
409
  )
292
410
  if resp.status_code == 200:
293
411
  data = resp.json()
412
+ parts = []
413
+ if data.get("model"):
414
+ parts.append(f"model={data['model']}")
415
+ if data.get("vendors"):
416
+ parts.append(" → ".join(data["vendors"]))
294
417
  console.print(
295
418
  f"[green]绑定成功:[/] session [cyan]{key[:16]}…[/cyan] → "
296
- + " → ".join(data.get("vendors", vendors))
419
+ + " ".join(parts)
297
420
  )
298
421
  else:
299
422
  try:
@@ -352,7 +475,11 @@ def session_list(
352
475
  for b in bindings:
353
476
  key = b.get("session_key", "?")
354
477
  vendors = b.get("vendors", [])
355
- console.print(f" [cyan]{key[:24]}…[/cyan] → " + " → ".join(vendors))
478
+ model = b.get("model")
479
+ model_part = f"model={model} " if model else ""
480
+ console.print(
481
+ f" [cyan]{key[:24]}…[/cyan] → {model_part}" + " → ".join(vendors)
482
+ )
356
483
  else:
357
484
  console.print(f"[red]查询失败: {resp.status_code} {resp.text}[/red]")
358
485
  except _httpx.ConnectError:
@@ -6,22 +6,57 @@ import asyncio
6
6
  import inspect
7
7
  import logging
8
8
  from pathlib import Path
9
+ from typing import TYPE_CHECKING
9
10
 
10
11
  import typer
11
12
  from rich.console import Console
12
13
 
14
+ from ..config.importer import StoredConfigInvalidError, load_offline_config
13
15
  from ..config.loader import load_config
16
+ from ..config.secrets import MasterKeyError
17
+ from ..config.store import ConfigStoreError
14
18
 
15
- app = typer.Typer(name="auth", help="管理 OAuth 登录凭证")
19
+ if TYPE_CHECKING:
20
+ from ..config.schema import ProxyConfig
21
+
22
+ app = typer.Typer(
23
+ name="auth", help="管理 OAuth 登录凭证", pretty_exceptions_show_locals=False
24
+ )
16
25
  console = Console()
26
+ err_console = Console(stderr=True)
17
27
  logger = logging.getLogger(__name__)
18
28
 
19
29
 
20
- def _build_token_store(cfg_path: Path | None = None):
21
- """按配置解析 Token Store 路径并完成加载."""
30
+ def _offline_config(*, decrypt: bool) -> ProxyConfig:
31
+ """离线读取配置:已迁移读 config.db,否则只读读取旧 YAML 并提示迁移."""
32
+ try:
33
+ cfg, hint = load_offline_config(decrypt=decrypt)
34
+ except (ConfigStoreError, MasterKeyError, StoredConfigInvalidError) as exc:
35
+ err_console.print(f"[red]{exc}[/red]")
36
+ raise typer.Exit(1) from None
37
+ if hint:
38
+ err_console.print(f"[dim]{hint}[/dim]")
39
+ return cfg
40
+
41
+
42
+ def _build_token_store(
43
+ cfg_path: Path | None = None,
44
+ *,
45
+ cfg: ProxyConfig | None = None,
46
+ decrypt: bool = True,
47
+ ):
48
+ """按配置解析 Token Store 路径并完成加载.
49
+
50
+ ``cfg`` 优先;其次显式 YAML 路径(legacy 只读);否则读取运行时配置。
51
+ """
22
52
  from ..auth.store import TokenStoreManager
23
53
 
24
- cfg = load_config(cfg_path)
54
+ if cfg is None:
55
+ cfg = (
56
+ load_config(cfg_path)
57
+ if cfg_path is not None
58
+ else _offline_config(decrypt=decrypt)
59
+ )
25
60
  store = TokenStoreManager(
26
61
  store_path=Path(cfg.auth.token_store_path)
27
62
  if cfg.auth.token_store_path
@@ -96,7 +131,7 @@ async def _run_auth_login(provider: str | None) -> None:
96
131
  @app.command("status")
97
132
  def auth_status() -> None:
98
133
  """查看已登录的 OAuth 凭证状态."""
99
- _, store = _build_token_store()
134
+ _, store = _build_token_store(decrypt=False)
100
135
 
101
136
  providers = store.list_providers()
102
137
  if not providers:
@@ -140,7 +175,7 @@ def auth_logout(
140
175
  ),
141
176
  ) -> None:
142
177
  """清除已存储的 OAuth 凭证."""
143
- _, store = _build_token_store()
178
+ _, store = _build_token_store(decrypt=False)
144
179
 
145
180
  if provider:
146
181
  store.remove(provider)
@@ -152,7 +187,9 @@ def auth_logout(
152
187
 
153
188
 
154
189
  # ── 自动登录辅助 ─────────────────────────────────────────────
155
- async def auto_login_if_needed(cfg_path: Path | None) -> None:
190
+ async def auto_login_if_needed(
191
+ cfg_path: Path | None = None, *, cfg: ProxyConfig | None = None
192
+ ) -> None:
156
193
  """检查各 Provider 是否缺少凭证,自动触发浏览器登录.
157
194
 
158
195
  仅对已启用、且未在 config 中显式提供凭证的 Tier 做检查。
@@ -163,11 +200,13 @@ async def auto_login_if_needed(cfg_path: Path | None) -> None:
163
200
  1. needs_login() — 快速本地判断(无凭证或已过期且无 refresh_token)
164
201
  2. refresh() — Google access_token 过期且存在 refresh_token 时静默刷新
165
202
  3. validate() — 网络验证已有凭证是否仍有效(仅在有凭证且未刷新时触发)
203
+
204
+ 仍读取 legacy ``cfg.copilot`` / ``cfg.antigravity``(行为不变)。
166
205
  """
167
206
  from ..auth.providers.github import GitHubDeviceFlowProvider
168
207
  from ..auth.providers.google import GoogleOAuthProvider
169
208
 
170
- cfg, store = _build_token_store(cfg_path)
209
+ cfg, store = _build_token_store(cfg_path, cfg=cfg)
171
210
 
172
211
  async def _resolve_needs_login(provider, tokens) -> bool:
173
212
  result = provider.needs_login(tokens)