Repository navigation
Expand file tree
/
Copy pathui_registry.py
More file actions
756 lines (716 loc) · 20.8 KB
/
Copy pathui_registry.py
File metadata and controls
756 lines (716 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
"""Config 页字段元数据(单一事实源:label / widget / 适用 vendor / 中文说明).
路径中 ``*`` 匹配任意 vendor 类型或列表元素。类型、默认值取自 Pydantic schema;
覆盖门测试保证每个非 legacy 叶子字段要么在 :data:`REGISTRY`,要么在 :data:`HIDDEN`。
"""
from __future__ import annotations
import types
from dataclasses import asdict, dataclass
from typing import Any, Union, get_args, get_origin
from pydantic import BaseModel
from .loader import _LEGACY_FLAT_KEYS
from .routing import VendorConfig
from .schema import ProxyConfig
WIDGETS = frozenset(
{
"text",
"number",
"bool",
"enum",
"secret",
"list",
"map",
"optional_group",
"list_section",
}
)
_NATIVE_ANTHROPIC = ["zhipu", "minimax", "kimi", "doubao", "xiaomi", "alibaba"]
_VENDOR_TYPES = list(get_args(VendorConfig.model_fields["vendor"].annotation))
@dataclass(frozen=True)
class FieldSpec:
path: str
label: str
widget: str
description: str
unit: str | None = None
enum: list[str] | None = None
min: float | None = None
max: float | None = None
vendors: list[str] | None = None
group: str | None = None
readonly: bool = False
unset_hint: str | None = None
def _f(path: str, label: str, widget: str, description: str, **kw: Any) -> FieldSpec:
return FieldSpec(path, label, widget, description, **kw)
def _vendor_qg(prefix: str, group: str, window_desc: str) -> list[FieldSpec]:
return [
_f(
f"{prefix}.enabled",
"Enabled",
"bool",
f"是否启用{window_desc}配额守卫",
group=group,
),
_f(
f"{prefix}.token_budget",
"Token Budget",
"number",
"滑动窗口内的 token 预算;0 表示仅按探测结果判定",
unit="tokens",
min=0,
group=group,
),
_f(
f"{prefix}.window_hours",
"Window",
"number",
"滑动窗口长度",
unit="h",
min=0,
group=group,
),
_f(
f"{prefix}.threshold_percent",
"Threshold %",
"number",
"用量达到预算该比例时暂停调度该 vendor",
unit="%",
min=0,
max=100,
group=group,
),
_f(
f"{prefix}.probe_interval_seconds",
"Probe Interval",
"number",
"超限后探测恢复的间隔",
unit="s",
min=0,
group=group,
),
]
REGISTRY: list[FieldSpec] = [
# ── Server / Logging / Database / Auth(bootstrap,只读,经 CLI 修改) ──
_f(
"server.host",
"Host",
"text",
"监听地址;修改需经 CLI 并重启",
group="Server",
readonly=True,
),
_f(
"server.port",
"Port",
"number",
"监听端口;修改需经 CLI 并重启",
min=1,
max=65535,
group="Server",
readonly=True,
),
_f(
"server.allowed_hosts",
"Allowed Hosts",
"list",
"Dashboard 与管理 API 额外允许的 Host(主机名或 IP,IPv6 可不加方括号;loopback 与本机直连 IP 恒允许);修改需经 CLI 并重启",
group="Server",
readonly=True,
),
_f(
"logging.level",
"Level",
"enum",
"控制台日志级别",
enum=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
group="Logging",
readonly=True,
),
_f(
"logging.file",
"Log File",
"text",
"文件日志路径;未设置时为 .logs/coding-proxy.log,空串禁用",
group="Logging",
readonly=True,
),
_f(
"logging.max_bytes",
"Max Bytes",
"number",
"单个日志文件上限,超过后轮转",
unit="B",
min=0,
group="Logging",
readonly=True,
),
_f(
"logging.backup_count",
"Backups",
"number",
"保留的压缩备份文件数",
min=0,
group="Logging",
readonly=True,
),
_f(
"database.path",
"Usage DB",
"text",
"Token 用量数据库路径,默认 $CODING_PROXY_HOME/usage.db",
group="Database",
readonly=True,
),
_f(
"database.compat_state_path",
"Compat DB",
"text",
"兼容层会话状态数据库路径,默认 $CODING_PROXY_HOME/compat.db",
group="Database",
readonly=True,
),
_f(
"database.compat_state_ttl_seconds",
"Compat TTL",
"number",
"兼容层会话状态保留时长",
unit="s",
min=0,
group="Database",
readonly=True,
),
_f(
"auth.google_client_id",
"Google Client",
"text",
"Google OAuth Client ID(Antigravity 登录用)",
group="Auth",
readonly=True,
),
_f(
"auth.google_client_secret",
"Google Secret",
"secret",
"Google OAuth Client Secret,仅用于 CLI 登录流程(auth login、start 自动登录);未设置时使用内置公开凭据",
group="Auth",
unset_hint="使用内置默认",
),
_f(
"auth.token_store_path",
"Token Store",
"text",
"OAuth token 存储文件,默认 $CODING_PROXY_HOME/tokens.json",
group="Auth",
readonly=True,
),
# ── Vendors ──
_f(
"vendors.*.enabled",
"Enabled",
"bool",
"是否启用该 vendor;禁用后不参与路由",
group="General",
),
_f(
"vendors.*.base_url",
"Base URL",
"text",
"上游 API 地址;修改后已存密钥会被清空,需重新设置",
group="General",
),
_f(
"vendors.*.timeout_ms",
"Timeout",
"number",
"单次请求超时",
unit="ms",
min=0,
group="General",
),
_f(
"vendors.*.github_token",
"GitHub Token",
"secret",
"GitHub token;留空时使用 `coding-proxy auth login` 获取的 OAuth 凭证",
vendors=["copilot"],
group="Credentials",
unset_hint="使用 OAuth 登录凭证",
),
_f(
"vendors.*.account_type",
"Account Type",
"enum",
"Copilot 账户类型,决定默认 API 地址",
enum=["individual", "business", "enterprise"],
vendors=["copilot"],
group="General",
),
_f(
"vendors.*.token_url",
"Token URL",
"text",
"Copilot token 交换端点;修改后已存密钥会被清空",
vendors=["copilot"],
group="General",
),
_f(
"vendors.*.models_cache_ttl_seconds",
"Models TTL",
"number",
"模型列表缓存时长",
unit="s",
min=0,
vendors=["copilot"],
group="General",
),
_f(
"vendors.*.client_id",
"Client ID",
"secret",
"Antigravity 使用的 Google OAuth2 Client ID;留空且凭证来自 OAuth 登录时使用内置公开 Client ID",
vendors=["antigravity"],
group="Credentials",
unset_hint="经 OAuth 登录时使用内置公开凭据",
),
_f(
"vendors.*.client_secret",
"Client Secret",
"secret",
"Antigravity 使用的 Google OAuth2 Client Secret;留空且凭证来自 OAuth 登录时使用内置公开 Client Secret",
vendors=["antigravity"],
group="Credentials",
unset_hint="经 OAuth 登录时使用内置公开凭据",
),
_f(
"vendors.*.refresh_token",
"Refresh Token",
"secret",
"Google OAuth2 refresh token;留空时使用 OAuth 登录凭证",
vendors=["antigravity"],
group="Credentials",
unset_hint="使用 OAuth 登录凭证",
),
_f(
"vendors.*.model_endpoint",
"Endpoint",
"text",
"Antigravity 模型端点路径",
vendors=["antigravity"],
group="General",
),
_f(
"vendors.*.api_key",
"API Key",
"secret",
"Anthropic 兼容端点的 API Key",
vendors=list(_NATIVE_ANTHROPIC),
group="Credentials",
unset_hint="请求会因缺少 API Key 直接失败",
),
_f(
"vendors.*.circuit_breaker",
"Breaker",
"optional_group",
"熔断器;关闭时不熔断,是否兜底由 tiers 中的位置决定",
group="Circuit Breaker",
),
_f(
"vendors.*.circuit_breaker.failure_threshold",
"Fail Threshold",
"number",
"连续失败多少次后熔断",
min=1,
group="Circuit Breaker",
),
_f(
"vendors.*.circuit_breaker.recovery_timeout_seconds",
"Recovery",
"number",
"熔断后首次尝试恢复的等待时间",
unit="s",
min=0,
group="Circuit Breaker",
),
_f(
"vendors.*.circuit_breaker.success_threshold",
"Success Thr.",
"number",
"半开状态下连续成功多少次后恢复",
min=1,
group="Circuit Breaker",
),
_f(
"vendors.*.circuit_breaker.max_recovery_seconds",
"Max Recovery",
"number",
"恢复等待时间指数退避的上限",
unit="s",
min=0,
group="Circuit Breaker",
),
*_vendor_qg("vendors.*.quota_guard", "Quota Guard", ""),
*_vendor_qg("vendors.*.weekly_quota_guard", "Weekly Quota", "周"),
_f(
"vendors.*.concurrency",
"Concurrency",
"optional_group",
"每模型并发限制;未设置时使用内置默认(每模型 3 个)",
vendors=["zhipu"],
group="Concurrency",
),
_f(
"vendors.*.concurrency.default",
"Default Limit",
"number",
"未单独配置的模型的并发上限",
min=1,
max=20,
vendors=["zhipu"],
group="Concurrency",
),
_f(
"vendors.*.concurrency.models",
"Per-Model",
"map",
"按映射后模型名单独设置并发上限",
vendors=["zhipu"],
group="Concurrency",
),
# ── Tiers ──
_f(
"tiers",
"Tier Order",
"list",
"降级链路优先级;未设置时按 vendors 列表顺序",
enum=list(_VENDOR_TYPES),
),
# ── Failover ──
_f("failover.status_codes", "Status Codes", "list", "触发故障转移的 HTTP 状态码"),
_f("failover.error_types", "Error Types", "list", "触发故障转移的上游错误类型"),
_f(
"failover.error_message_patterns",
"Msg Patterns",
"list",
"错误消息包含任一关键字时触发故障转移",
),
# ── Model Mapping ──
_f(
"model_mapping",
"Mappings",
"list_section",
"模型名映射规则,按顺序匹配,首个命中生效",
),
_f(
"model_mapping.*.pattern",
"Pattern",
"text",
"匹配的请求模型名(正则或精确匹配)",
),
_f("model_mapping.*.target", "Target", "text", "映射后的上游模型名"),
_f("model_mapping.*.is_regex", "Regex", "bool", "pattern 是否按正则匹配"),
_f(
"model_mapping.*.vendors",
"Vendor Scope",
"list",
"仅对这些 vendor 生效;为空时对全部生效",
enum=list(_VENDOR_TYPES),
),
# ── Pricing ──
_f(
"pricing",
"Pricing",
"list_section",
"模型单价(每百万 token),用于用量成本统计;修改会重算历史成本",
),
_f("pricing.*.vendor", "Vendor", "text", "供应商名,对应用量表的供应商列"),
_f("pricing.*.model", "Model", "text", "实际服务模型名"),
_f(
"pricing.*.input_cost_per_mtok",
"Input",
"number",
"输入 token 单价($ 或 ¥)",
unit="/Mtok",
min=0,
),
_f(
"pricing.*.output_cost_per_mtok",
"Output",
"number",
"输出 token 单价($ 或 ¥)",
unit="/Mtok",
min=0,
),
_f(
"pricing.*.cache_write_cost_per_mtok",
"Cache Write",
"number",
"缓存写入 token 单价($ 或 ¥)",
unit="/Mtok",
min=0,
),
_f(
"pricing.*.cache_read_cost_per_mtok",
"Cache Read",
"number",
"缓存读取 token 单价($ 或 ¥)",
unit="/Mtok",
min=0,
),
_f(
"pricing.*.online",
"Online",
"bool",
"下线(false)后不进 Model Bind 下拉、不可新绑定;已绑会话保留,成本照常计价",
),
]
for _provider in ("openai", "gemini", "anthropic"):
REGISTRY += [
_f(
f"native_api.{_provider}.enabled",
"Enabled",
"bool",
"是否暴露该 provider 的原生透传端点(默认启用)",
group=_provider,
),
_f(
f"native_api.{_provider}.base_url",
"Base URL",
"text",
"上游域名前缀(不含 /v1);可被 NATIVE_*_BASE_URL 环境变量覆盖",
group=_provider,
),
_f(
f"native_api.{_provider}.timeout_ms",
"Timeout",
"number",
"单次请求超时",
unit="ms",
min=1000,
group=_provider,
),
_f(
f"native_api.{_provider}.connect_timeout_ms",
"Conn. Timeout",
"number",
"连接建立超时",
unit="ms",
min=500,
group=_provider,
),
_f(
f"native_api.{_provider}.inject_include_usage",
"Include Usage",
"bool",
"(仅 openai 生效)为 chat 流式请求注入 stream_options.include_usage,"
"让上游回发 usage chunk(默认关)",
group=_provider,
),
]
REGISTRY += [
_f(
"antigravity_gateway.enabled",
"Enabled",
"bool",
"是否暴露 /api/antigravity/** 透传端点(默认启用)",
group="antigravity",
),
_f(
"antigravity_gateway.base_url",
"Base URL",
"text",
"Antigravity 后端(Cloud Code v1internal);域名随版本漂移过,"
"可被 ANTIGRAVITY_GATEWAY_BASE_URL 覆盖",
group="antigravity",
),
_f(
"antigravity_gateway.timeout_ms",
"Timeout",
"number",
"单次请求超时",
unit="ms",
min=1000,
group="antigravity",
),
_f(
"antigravity_gateway.connect_timeout_ms",
"Conn. Timeout",
"number",
"连接建立超时",
unit="ms",
min=500,
group="antigravity",
),
]
REGISTRY += [
# ── Session Policies ──
_f(
"session_policies.policies",
"Policies",
"list_section",
"Session 路由策略,按顺序求值,首个命中生效",
),
_f("session_policies.policies.*.name", "Name", "text", "策略名称,用于日志与排障"),
_f(
"session_policies.policies.*.match.session_keys",
"Session Keys",
"list",
"精确匹配的 session key",
),
_f(
"session_policies.policies.*.tiers",
"Tiers",
"list",
"命中后使用的 vendor 优先级",
enum=list(_VENDOR_TYPES),
),
_f(
"session_policies.policies.*.model",
"Model",
"text",
"会话级模型覆盖:非空时该 Session 的请求统一改写为此模型",
),
_f(
"session_policies.bindable_models",
"Model List",
"list_section",
"可绑定模型的显式定制层;下拉选项为其与内置 vendor 目录的合成结果",
),
_f(
"session_policies.bindable_models.*.label",
"Label",
"text",
"UI 显示名,清单内唯一",
),
_f(
"session_policies.bindable_models.*.model",
"Model",
"text",
"覆盖目标模型名,清单内唯一",
),
_f(
"session_policies.bindable_models.*.tiers",
"Tiers",
"list",
"绑定后优先承接的 vendor;留空继承内置目录归属值,故障时按订阅顺序回退",
enum=list(_VENDOR_TYPES),
),
_f(
"session_policies.bindable_models.*.exclude",
"Exclude",
"bool",
"剔除同名内置目录条目(下拉收缩开关)",
),
_f(
"session_policies.title_vendor_bindings",
"Title Bindings",
"list_section",
"Session 标题前缀到 vendor 的自动绑定,首个命中生效",
),
_f(
"session_policies.title_vendor_bindings.*.prefix",
"Prefix",
"text",
"标题前缀(大小写敏感,不能为空)",
),
_f(
"session_policies.title_vendor_bindings.*.vendor",
"Vendor",
"text",
"命中后绑定的 vendor",
),
_f(
"session_policies.title_exempt_prefixes",
"Title Exempt",
"list",
"以这些前缀开头的候选标题不写入 Session 标题",
),
]
# 不渲染的字段(前缀匹配):legacy 顶层字段、传输层重试、预留字段
HIDDEN: frozenset[str] = frozenset(
{
*_LEGACY_FLAT_KEYS,
"vendors.*.vendor",
"vendors.*.retry",
"auth.github_client_id",
"session_policies.policies.*.quota",
"session_policies.policies.*.match.client_category",
}
)
# ── schema 遍历 ────────────────────────────────────────────────
def _unwrap_optional(annotation: Any) -> tuple[Any, bool]:
origin = get_origin(annotation)
if origin in (Union, types.UnionType):
args = [a for a in get_args(annotation) if a is not type(None)]
if len(args) == 1:
return args[0], True
return annotation, False
def _is_model(annotation: Any) -> bool:
return isinstance(annotation, type) and issubclass(annotation, BaseModel)
def _list_item_model(annotation: Any) -> type[BaseModel] | None:
if get_origin(annotation) is list:
args = get_args(annotation)
if args and _is_model(args[0]):
return args[0]
return None
def walk_schema(
model: type[BaseModel] = ProxyConfig, prefix: str = ""
) -> tuple[set[str], set[str]]:
"""遍历 schema → ``(required, all_paths)``.
``required``:叶子字段、可选分组(``Model | None``)与列表 section;
``all_paths``:在此基础上再加普通嵌套分组,供 registry 路径存在性校验。
"""
required: set[str] = set()
all_paths: set[str] = set()
for name, info in model.model_fields.items():
if model is ProxyConfig and name in _LEGACY_FLAT_KEYS:
continue
path = f"{prefix}{name}"
if model is ProxyConfig and name == "vendors":
sub_req, sub_all = walk_schema(VendorConfig, "vendors.*.")
required |= sub_req
all_paths |= sub_all | {"vendors"}
continue
annotation, optional = _unwrap_optional(info.annotation)
item_model = _list_item_model(annotation)
if _is_model(annotation):
sub_req, sub_all = walk_schema(annotation, f"{path}.")
required |= sub_req
all_paths |= sub_all | {path}
if optional:
required.add(path)
elif item_model is not None:
sub_req, sub_all = walk_schema(item_model, f"{path}.*.")
required |= sub_req | {path}
all_paths |= sub_all | {path}
else:
required.add(path)
all_paths.add(path)
return required, all_paths
def is_hidden(path: str) -> bool:
return any(path == h or path.startswith(f"{h}.") for h in HIDDEN)
def match_path(pattern: str, path: str) -> bool:
"""``*`` 匹配单段的路径匹配."""
p_parts, parts = pattern.split("."), path.split(".")
return len(p_parts) == len(parts) and all(
p == "*" or p == q for p, q in zip(p_parts, parts, strict=True)
)
def find_spec(path: str) -> FieldSpec | None:
for spec in REGISTRY:
if match_path(spec.path, path):
return spec
return None
def registry_payload() -> dict:
return {
"fields": [asdict(spec) for spec in REGISTRY],
"hidden": sorted(HIDDEN),
}
__all__ = [
"FieldSpec",
"REGISTRY",
"HIDDEN",
"WIDGETS",
"walk_schema",
"is_hidden",
"match_path",
"find_spec",
"registry_payload",
]