Repository navigation
Expand file tree
/
Copy pathwb_codearts.py
More file actions
3284 lines (2927 loc) · 128 KB
/
Copy pathwb_codearts.py
File metadata and controls
3284 lines (2927 loc) · 128 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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""华为云 CodeArts(盘古助手/码道)原生客户端与账号池。
这是单进程版本:wb-hub 直接完成 OAuth 登录、token 续期、账号轮转、模型发现、
聊天 SSE 与签到,不再依赖独立的 codearts2api 服务。
协议来源:codearts2api 的 Go 实现与 `docs/reverse-engineering.md`。关键点:
- 聊天:`POST https://snap-access.cn-north-4.myhuaweicloud.com/api/v2/chat/completions`
`x-auth-token` + 华为云 AK/SK `SDK-HMAC-SHA256` 签名;`stream=true`。
- 登录:华为云 CodeArts OAuth2(PKCE + DPoP)→ `sts.cn-north-4/v1/oauth2/tokens`
换 STS 临时 AK/SK + security_token;refresh_token 与 client_id、DPoP 公钥绑定。
- 模型:agent-center / builtin / 限时福利三路合并,福利模型聊天时加
`maas_type: benefit`。
- 签到:`/v1/ops/delivery|claim|confirm`,`Agent-Type: PromptCenter`。
依赖:Python 3.9+ 标准库;密码学原语在 `wb_codearts_crypto.py`。
"""
import io
import json
import os
import secrets
import socket
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import wb_settings
import wb_time
import wb_codearts_crypto as crypto
# ---------------------------------------------------------------------------
# 常量
# ---------------------------------------------------------------------------
SNAP_HOST = os.environ.get("WB_CODEARTS_SNAP_HOST") or \
"https://snap-access.cn-north-4.myhuaweicloud.com"
SNAP_MANAGER = os.environ.get("WB_CODEARTS_SNAP_MANAGER") or \
SNAP_HOST + "/snap-manager"
PORTAL_HOST = os.environ.get("WB_CODEARTS_PORTAL_HOST") or \
"https://codearts.huaweicloud.com/portal"
STS_HOST = os.environ.get("WB_CODEARTS_STS_HOST") or \
"https://sts.cn-north-4.myhuaweicloud.com"
BENEFIT_HOST = os.environ.get("WB_CODEARTS_BENEFIT_HOST") or \
"https://opengw.developer.huaweicloud.com"
CLIENT_ID = "codearts-agent"
PLUGIN_NAME = "snap_AIIDE"
PLUGIN_VERSION = "5.2.0"
REDIRECT_PATH = "/oauth/callback"
EP_CHAT = "/api/v2/chat/completions"
EP_OAUTH_TOKENS = "/v1/oauth2/tokens"
EP_LOGIN_TICKET = "/v1/login/ticket"
EP_MODEL_BUILTIN = "/v1/model/builtin"
EP_AGENT_LIST = "/v1/agent-center/agents/useragents"
EP_AGENT_DETAIL = "/v1/agent-center/agents/detail"
EP_BENEFIT_CONFIG = "/api/v1/gateway/config"
EP_BENEFIT_CLAIM = "/api/v1/benefit/claim"
EP_CREDIT_DELIVERY = "/v1/ops/delivery"
EP_CREDIT_CLAIM = "/v1/ops/claim"
EP_CREDIT_CONFIRM = "/v1/ops/confirm"
EP_PACKAGE_INFO = "/v1/statistics/plugin"
#: 积分活动里「签到」的判据。控制台上的「每日签到赢100积分」是一条
#: `USER_LOGIN` / `triggerEvent=user.login` 的 MANUAL_CLAIM 活动,
#: 但 campaignId 每换季都会变(2026-10 是 34),所以按类型挑,不按 id 硬编码。
#: 1 / 4 是历史 id(4 是「新用户注册送 4000 积分」),留着兼容老账号。
CHECKIN_CAMPAIGN_IDS = (1, 4)
CHECKIN_CAMPAIGN_TYPES = ("USER_LOGIN",)
HEADER_MAAS_TYPE = "maas_type"
MAAS_BENEFIT = "benefit"
#: 冷启动种子:首次发现前也能列出/路由福利模型。
SEED_BENEFIT_MODELS = (
"deepseek-v4-flash-0731", "deepseek-v4-pro-0813", "glm-5.3-flash",
)
SEED_KNOWN_MODELS = (
"GLM-5.2", "GLM-5.2-ArkTS-SPARK", "GLM-5.1", "GLM-4.7",
"OpenPangu-2.0-Pro", "OpenPangu-2.0-Flash",
"Qwen3-VL-235B", "Qwen3.5-397B-A17B-VL", "Qwen3.6-27B-VL",
)
SEED_MODELS = tuple(SEED_KNOWN_MODELS) + tuple(SEED_BENEFIT_MODELS)
#: 模型目录缓存 1 小时;失败时保留上一轮。
CATALOG_TTL = 3600.0
#: 单个账号的模型发现最短间隔(避免每次 /v1/models 都打三路上游)。
CATALOG_MIN_INTERVAL = 60.0
#: 错误阈值与冷却。
ERR_THRESHOLD = 3
ERR_COOLDOWN = 600.0
SOFT_COOLDOWN = 60.0
#: 积分耗尽不是瞬时错误:账号需要等用户补积分或活动到账,60 秒后重试
#: 只会把同一个 400 再打一遍。给它一个更长的可恢复冷却,仍会自然解冻。
CREDIT_COOLDOWN = 600.0
#: 并发名额满时的最长等待(秒)。单账号并发上限默认 1,而客户端常常在同一
#: 瞬间发出第二个请求(DSH 的自动标题请求就与首轮请求同时到达)。旧实现只
#: 等约 100ms 就回「没有可用的 CodeArts 账号」,把一次几百毫秒的正常排队
#: 说成了账号缺失,客户端把它当成配置错误、不会重试。这里改为在名额释放
#: 前排队等待,等不到再回可重试的 429。10s 足够覆盖标题请求那 1~2s 的
#: 占用;真被长请求占着时,继续等 20s 也未必能等到,不如早点回 429 让
#: 客户端按退避重试。
BUSY_WAIT_SECONDS = 10.0
#: token 提前刷新窗口。
REFRESH_SKEW = 1800.0
#: OAuth 会话 TTL。
OAUTH_TTL = 600.0
#: 错误体读取上限。
ERROR_BODY_MAX = 256 * 1024
DEFAULTS = {
"enabled": False,
"timeout_seconds": 30.0,
"stream_timeout_seconds": 600.0,
"models_ttl_seconds": 300.0,
"max_concurrent": 1,
"busy_wait_seconds": BUSY_WAIT_SECONDS,
"benefit_auto_claim": True,
"credits_auto_claim": False,
}
#: Verified with the upstream validation error: reasoning_effort must be one of
#: none/low/medium/high/xhigh/max. `minimal` is accepted but not in that list;
#: `auto` is rejected.
REASONING_EFFORTS = {
"deepseek-v4.1-flash": ["none", "low", "medium", "high", "xhigh", "max"],
"deepseek-v4.1-flash-1017": ["none", "low", "medium", "high",
"xhigh", "max"],
# Verified from the upstream validation message for the GLM backend.
"glm-5.2": ["none", "minimal", "low", "medium", "high", "xhigh", "max"],
"glm-5.2-sft-harmony": ["none", "minimal", "low", "medium", "high",
"xhigh", "max"],
"glm-5.3": ["none", "minimal", "low", "medium", "high", "xhigh", "max"],
# Always-thinking model: upstream explicitly says only low/high/max.
"glm-5.3-flash": ["low", "high", "max"],
}
#: The upstream rejects an output-token request above the model's advertised
#: limit with "The request param is invalid" instead of clamping it. When the
#: catalogue has no limit (discovery failed), 65536 is the conservative cap
#: verified for the CodeArts chat models.
DEFAULT_MAX_OUTPUT_TOKENS = 65536
def _requested_effort(payload):
"""Resolve the client's reasoning level under every common spelling."""
if not isinstance(payload, dict):
return ""
effort = payload.get("reasoning_effort")
if effort is None:
effort = payload.get("reasoningEffort")
if effort is not None:
return str(effort).strip().lower()
thinking = payload.get("thinking")
if isinstance(thinking, dict):
kind = str(thinking.get("type") or "").strip().lower()
if kind == "disabled":
return "none"
if kind == "enabled":
return "high"
if "enable_thinking" in payload:
return "high" if payload.get("enable_thinking") else "none"
return ""
_LOCK = threading.RLock()
# ---------------------------------------------------------------------------
# 异常
# ---------------------------------------------------------------------------
class CodeArtsError(Exception):
def __init__(self, message, status=None, code=None):
super(CodeArtsError, self).__init__(message)
self.status = status
self.code = code
class CodeArtsUnavailable(CodeArtsError):
pass
class CodeArtsBusy(CodeArtsUnavailable):
"""池里还有健康账号,只是并发名额暂时被别的请求占满。
与「一个账号都没有」必须分开:前者等一会儿就好,后者要用户去账号页
添加账号。客户端对两者的处理也不同(重试 vs 报配置错误)。
"""
pass
class CodeArtsAuthError(CodeArtsError):
pass
class CodeArtsBadRequest(CodeArtsError):
pass
class CodeArtsNotFound(CodeArtsError):
pass
class CodeArtsConflict(CodeArtsError):
pass
class CodeArtsUpstreamError(CodeArtsError):
"""上游 HTTP 200 但 SSE 内嵌业务错误(排队/TPM/模型未注册等)。"""
# ---------------------------------------------------------------------------
# 配置
# ---------------------------------------------------------------------------
def _positive_float(value, default, low, high):
try:
out = float(value)
except (TypeError, ValueError):
return float(default)
return min(max(out, float(low)), float(high))
def _positive_int(value, default, low, high):
try:
out = int(value)
except (TypeError, ValueError):
return int(default)
return min(max(out, int(low)), int(high))
def load_config(accounts_dir):
"""读取并收敛 CodeArts 配置;非法值回落默认,不阻塞网关启动。"""
raw = wb_settings.load(accounts_dir).get("codearts")
if not isinstance(raw, dict):
raw = {}
return {
"enabled": raw.get("enabled") is True,
"timeout_seconds": _positive_float(
raw.get("timeout_seconds"), DEFAULTS["timeout_seconds"], 1.0, 600.0),
"stream_timeout_seconds": _positive_float(
raw.get("stream_timeout_seconds"),
DEFAULTS["stream_timeout_seconds"], 1.0, 3600.0),
"models_ttl_seconds": _positive_float(
raw.get("models_ttl_seconds"), DEFAULTS["models_ttl_seconds"],
60.0, 86400.0),
"max_concurrent": _positive_int(
raw.get("max_concurrent"), DEFAULTS["max_concurrent"], 1, 20),
"busy_wait_seconds": _positive_float(
raw.get("busy_wait_seconds"), DEFAULTS["busy_wait_seconds"],
0.0, 120.0),
"benefit_auto_claim": raw.get("benefit_auto_claim", True) is not False,
"credits_auto_claim": raw.get("credits_auto_claim", False) is True,
"accounts_dir": accounts_dir,
}
def save_config(accounts_dir, patch):
"""保存配置;返回完整配置。非法值抛 ValueError。
整段读-改-写必须在 `_LOCK` 内完成。只靠 `wb_settings.save()` 内部那把锁
是不够的——它只保护「写」这一步,`load_config()` 读到的旧值到
`wb_settings.save()` 落盘之间有一个窗口。面板连续点两次保存、或者两个
浏览器同时保存时,后一次会用「读到旧值 + 自己那一项」覆盖掉前一次刚写
进去的另一项,且双方都拿到 200,没有任何报错。
锁序:这里持有 `_LOCK` 时会调用 `wb_settings.load/save`,它们各自持
`wb_settings._lock`。反向(`wb_settings` 持锁时调 `wb_codearts`)不存在,
见 `wb_settings.set_codearts_config()` —— 它只做转发,不持锁。所以
`_LOCK -> wb_settings._lock` 是唯一的获取顺序,不会死锁。
"""
if not isinstance(patch, dict):
raise ValueError("codearts settings must be an object")
with _LOCK:
current = load_config(accounts_dir)
merged = dict(current)
for key in DEFAULTS:
if key in patch:
merged[key] = patch[key]
merged["enabled"] = merged.get("enabled") is True
merged["timeout_seconds"] = _positive_float(
merged.get("timeout_seconds"), DEFAULTS["timeout_seconds"], 1.0, 600.0)
merged["stream_timeout_seconds"] = _positive_float(
merged.get("stream_timeout_seconds"),
DEFAULTS["stream_timeout_seconds"], 1.0, 3600.0)
merged["models_ttl_seconds"] = _positive_float(
merged.get("models_ttl_seconds"), DEFAULTS["models_ttl_seconds"],
60.0, 86400.0)
merged["max_concurrent"] = _positive_int(
merged.get("max_concurrent"), DEFAULTS["max_concurrent"], 1, 20)
merged["busy_wait_seconds"] = _positive_float(
merged.get("busy_wait_seconds"), DEFAULTS["busy_wait_seconds"],
0.0, 120.0)
merged["benefit_auto_claim"] = merged.get("benefit_auto_claim", True) is not False
merged["credits_auto_claim"] = merged.get("credits_auto_claim", False) is True
# 重新读 settings:`load_config` 只返回收敛后的 codearts 段,写回去要
# 保留其它段(api_keys / realm / 媒体配置…),所以必须拿整份再合并。
data = wb_settings.load(accounts_dir)
data["codearts"] = {k: merged[k] for k in DEFAULTS}
wb_settings.save(accounts_dir, data)
return load_config(accounts_dir)
def configured(accounts_dir):
return load_config(accounts_dir)["enabled"]
def masked_config(accounts_dir):
cfg = load_config(accounts_dir)
pool = pool_for(accounts_dir)
out = {k: v for k, v in cfg.items() if k != "accounts_dir"}
out["configured"] = bool(cfg["enabled"])
out["accounts"] = len(pool.accounts) if pool else 0
out["healthy"] = pool.stats()["healthy"] if pool else 0
return out
# ---------------------------------------------------------------------------
# 账号文件与状态
# ---------------------------------------------------------------------------
def accounts_path(accounts_dir):
return os.path.join(accounts_dir, "codearts")
def _auth_filename(uid):
safe = str(uid or "").replace(os.sep, "_").replace("/", "_")
return "codearts-%s.json" % (safe or "unknown")
def _atomic_write(path, payload):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(payload, fh, ensure_ascii=False, indent=2)
os.replace(tmp, path)
def load_auths(accounts_dir):
"""读取 accounts/codearts/codearts-*.json。"""
folder = accounts_path(accounts_dir)
out = []
try:
names = sorted(os.listdir(folder))
except OSError:
return out
for name in names:
if not name.startswith("codearts-") or not name.endswith(".json"):
continue
path = os.path.join(folder, name)
try:
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
except Exception:
continue
if not isinstance(data, dict):
continue
if not data.get("cloud_dragon_token") or not data.get("user_id"):
continue
data["_path"] = path
out.append(data)
return out
def save_auth(accounts_dir, auth):
path = auth.get("_path") or os.path.join(
accounts_path(accounts_dir), _auth_filename(auth.get("user_id")))
auth = dict(auth)
auth.pop("_path", None)
_atomic_write(path, auth)
auth["_path"] = path
return auth
def delete_auth(accounts_dir, uid):
path = os.path.join(accounts_path(accounts_dir), _auth_filename(uid))
try:
os.remove(path)
return True
except FileNotFoundError:
return False
def _parse_expiration(value):
text = str(value or "").strip()
if not text:
return 0.0
text = text.replace("Z", "+00:00")
try:
import datetime
return datetime.datetime.fromisoformat(text).timestamp()
except Exception:
return 0.0
def _fmt_duration(seconds):
seconds = int(max(0, seconds))
hours, rest = divmod(seconds, 3600)
minutes, _ = divmod(rest, 60)
if hours:
return "%dh%dm" % (hours, minutes)
return "%dm" % minutes
# ---------------------------------------------------------------------------
# 账号
# ---------------------------------------------------------------------------
class CodeArtsAccount(object):
"""一个华为云 CodeArts 账号;也是 wb-hub 回程处理器需要的账号表面。"""
uid = ""
realm = "codearts"
product = "codearts"
proxy = None
chat_path = EP_CHAT
def __init__(self, auth, pool):
self.auth = dict(auth)
self.pool = pool
self.uid = str(auth.get("user_id") or "")
self.name = self.uid
self.nickname = str(auth.get("user_name") or self.uid)
# proxy_slot is the persisted binding; proxy is the runtime URL that
# CodeArtsPool.apply_proxy_slots() derives from the current settings.
self.proxy_slot = str(auth.get("proxySlot") or "").strip()
self.proxy = ""
self.disabled = False
self.disabled_reason = ""
# 面板手动停用是独立于上游健康状态的操作员意图。token 刷新、
# OAuth 重新登录和 note_error 都不能隐式把它清掉;只有 enable() 可以。
self.manual_disabled = False
self.cool_until = 0.0
self.err_count = 0
self.last_error = ""
self.active_concurrent = 0
self.max_concurrent = pool.config.get("max_concurrent", 1)
self.last_used = 0.0
self.models = []
self.model_benefit = {}
self.models_fetched_at = 0.0
self.checkin = None
self.note = ""
self.tasks_enabled = True
self.info = None
self.info_fetched_at = 0.0
self._lock = threading.RLock()
self._refresh_lock = threading.Lock()
self._models_lock = threading.Lock()
self._info_lock = threading.Lock()
# Credit accounting samples the account's cumulative "used" counter
# before and after a request. Serialize only those two short lookups,
# never the chat stream itself. `_credit_settled_used` is the account
# wide high-water mark: overlapping requests may observe the same
# cumulative value, but only the first settlement may claim that delta.
# `_credit_explicit_pending` keeps a credit value returned directly by
# an upstream response from being counted again in the next delta.
self._credit_sample_lock = threading.RLock()
self._credit_settled_used = None
self._credit_explicit_pending = 0.0
def chat_base_url(self):
return SNAP_HOST
def model_disabled(self, mid):
return False
def is_cli_identity(self):
return False
# ---- 凭证 ----
def credential(self):
return {
"access_key_id": self.auth.get("access_key_id") or "",
"secret_access_key": self.auth.get("secret_access_key") or "",
"security_token": self.auth.get("cloud_dragon_token") or "",
}
def expires_at(self):
return _parse_expiration(self.auth.get("expiration"))
def token_remaining(self):
exp = self.expires_at()
if not exp:
return 0
return max(0, exp - time.time())
def expired(self):
exp = self.expires_at()
return bool(exp and exp <= time.time())
def expiring_soon(self, skew=REFRESH_SKEW):
exp = self.expires_at()
return bool(exp and exp - time.time() <= skew)
def update_auth(self, token):
creds = token.get("credentials") or {}
self.auth.update({
"user_id": token.get("user_id") or self.uid,
"user_name": token.get("user_name") or self.nickname,
"domain_id": token.get("domain_id") or self.auth.get("domain_id") or "",
"cloud_dragon_token": creds.get("security_token") or "",
"access_key_id": creds.get("access_key_id") or "",
"secret_access_key": creds.get("secret_access_key") or "",
"expiration": creds.get("expiration") or "",
"refresh_token": token.get("refresh_token") or self.auth.get("refresh_token") or "",
"updated_at": int(time.time()),
})
self.auth = save_auth(self.pool.accounts_dir, self.auth)
if not self.manual_disabled:
self.disabled = False
self.disabled_reason = ""
self.last_error = ""
# ---- 状态快照 ----
def view(self):
now = time.time()
cooling = (not self.disabled) and now < self.cool_until
reason = self.disabled_reason or self.last_error
info = self.info or {}
credit_total = ((info.get("credits") or {}).get("total") or {})
credits = None
if credit_total:
credits = {
"remain": float(credit_total.get("remain") or 0),
"amount": float(credit_total.get("amount") or 0),
"used": float(credit_total.get("used") or 0),
"expiring": float(credit_total.get("expiring") or 0),
"unit": "credit",
"package": info.get("package_name") or "",
"end_date": info.get("end_date") or "",
}
return {
"name": self.name,
"uid": self.uid,
"nickname": self.nickname,
"user_name": self.nickname,
"default_model": "",
"credits": credits,
"package": info.get("package_name") or "",
"checkin": self.checkin,
"disabled": self.disabled,
"cooling": cooling,
"until": (wb_time.strftime("%Y-%m-%dT%H:%M:%S", wb_time.localtime(self.cool_until))
if cooling else ""),
"err_count": self.err_count,
"reason": reason,
"last_error": self.last_error,
"active_concurrent": self.active_concurrent,
"max_concurrent": self.max_concurrent,
"token_remaining": _fmt_duration(self.token_remaining()),
"expires_at": (wb_time.strftime("%Y-%m-%dT%H:%M:%S",
wb_time.localtime(self.expires_at()))
if self.expires_at() else ""),
"models": len(self.models),
"proxy_slot": self.proxy_slot,
"proxy": self.proxy,
"note": self.note,
"tasks_enabled": bool(self.tasks_enabled),
}
def healthy(self, now=None):
"""能否被选中。
故意不检查 token 是否过期:过期账号仍要被选中,交给 `_ensure_token`
刷新;把过期号直接过滤掉会让整池过期时一个号都选不到、也无法续期。
"""
now = now or time.time()
return (not self.disabled) and now >= self.cool_until
def checked_in_today(self, now=None):
"""Whether this account already completed a successful check-in today.
A failed attempt (``ok`` false) does not count, so a later slot can
retry after an earlier failure. The timestamp is local time, matching
the scheduler's clock.
"""
entry = self.checkin if isinstance(self.checkin, dict) else {}
if not entry.get("ok"):
return False
text = str(entry.get("checked_at") or "")
if len(text) < 10:
return False
today = wb_time.day_key(time.time() if now is None else now)
return text[:10] == today
def has_model(self, model):
mid = str(model or "").lower()
if not mid:
return True
if not self.models:
return True # 目录还没发现,先给它一次机会
return any(str(m.get("id") or "").lower() == mid for m in self.models)
def is_benefit(self, model):
return bool(self.model_benefit.get(str(model or "").lower()))
# ---------------------------------------------------------------------------
# 账号池
# ---------------------------------------------------------------------------
class CodeArtsPool(object):
def __init__(self, accounts_dir, config):
self.accounts_dir = accounts_dir
self.folder = accounts_path(accounts_dir)
self.state_file = os.path.join(self.folder, "state.json")
self.config = dict(config)
self.accounts = []
self._lock = threading.RLock()
# 并发名额归还时唤醒等待中的请求。用独立的 Condition(不挂在
# `_lock` 上)避免 `release()` 在持有账号锁时再去抢池锁。
self._release_cond = threading.Condition()
self.load()
# ---- 持久化 ----
def load(self):
auths = load_auths(self.accounts_dir)
state = self._load_state()
accounts = []
for auth in auths:
acct = CodeArtsAccount(auth, self)
entry = state.get(acct.uid) or {}
acct.err_count = int(entry.get("err_count") or 0)
acct.cool_until = float(entry.get("cool_until") or 0)
acct.disabled = bool(entry.get("disabled"))
acct.disabled_reason = str(entry.get("reason") or "")
acct.last_error = str(entry.get("last_error") or "")
if "manual_disabled" in entry:
acct.manual_disabled = entry.get("manual_disabled") is True
else:
# 兼容旧 state.json:早期没有 manual_disabled,只能从原因推断。
# 认证失败写的是上游错误正文,不会命中下面这些面板文案。
reason = (acct.disabled_reason + " " + acct.last_error).lower()
acct.manual_disabled = bool(acct.disabled) and any(
marker in reason for marker in
("manual", "手动", "停用", "disabled by operator"))
acct.note = str(entry.get("note") or "")[:200]
acct.tasks_enabled = bool(entry.get("tasks_enabled", True))
if isinstance(entry.get("checkin"), dict):
acct.checkin = entry["checkin"]
accounts.append(acct)
with self._lock:
self.accounts = accounts
self.apply_proxy_slots()
def _load_state(self):
try:
with open(self.state_file, encoding="utf-8") as fh:
raw = json.load(fh)
except Exception:
return {}
if isinstance(raw, dict) and isinstance(raw.get("accounts"), list):
raw = raw["accounts"]
out = {}
if isinstance(raw, list):
for item in raw:
if isinstance(item, dict) and item.get("name"):
out[str(item["name"])] = item
return out
def save_state(self):
items = []
with self._lock:
accounts = list(self.accounts)
for acct in accounts:
items.append({
"name": acct.uid,
"err_count": acct.err_count,
"cool_until": acct.cool_until,
"disabled": acct.disabled,
"manual_disabled": bool(acct.manual_disabled),
"reason": acct.disabled_reason,
"last_error": acct.last_error,
"checkin": acct.checkin,
"note": acct.note,
"tasks_enabled": bool(acct.tasks_enabled),
})
try:
_atomic_write(self.state_file, items)
except Exception:
pass
# ---- 查询 ----
def get(self, uid):
with self._lock:
for acct in self.accounts:
if acct.uid == uid or acct.name == uid:
return acct
return None
def list(self):
with self._lock:
accounts = list(self.accounts)
return [acct.view() for acct in sorted(accounts, key=lambda a: a.uid)]
def apply_proxy_slots(self, slots=None):
"""Re-resolve every account's runtime `proxy` from its bound slot.
Mirrors wb_accounts.AccountPool.apply_proxy_slots(): `proxySlot` is the
persisted source of truth and `proxy` is derived here, so every outbound
CodeArts call site can just use `acct.proxy`. A disabled or missing slot
falls back to direct, while the binding stays on disk for re-enabling.
"""
if slots is None:
slots = wb_settings.proxy_slots(self.accounts_dir)
by_id = {entry["id"]: entry for entry in slots if entry.get("enabled")}
with self._lock:
for acct in self.accounts:
slot = by_id.get(acct.proxy_slot)
acct.proxy = slot["url"] if slot else ""
def stats(self):
now = time.time()
total = healthy = disabled = cooling = 0
with self._lock:
accounts = list(self.accounts)
for acct in accounts:
total += 1
if acct.disabled:
disabled += 1
elif now < acct.cool_until:
cooling += 1
else:
healthy += 1
return {"total": total, "healthy": healthy, "disabled": disabled,
"cooling": cooling}
# ---- 增删启停 ----
def add(self, auth):
acct = CodeArtsAccount(auth, self)
with self._lock:
for index, existing in enumerate(self.accounts):
if existing.uid == acct.uid:
# Re-login returns a fresh auth document without the
# panel-side binding. Keep the slot the operator chose.
if not acct.proxy_slot and existing.proxy_slot:
acct.proxy_slot = existing.proxy_slot
if acct.proxy_slot:
acct.auth["proxySlot"] = acct.proxy_slot
# _save_login() wrote the fresh token document before the
# pool saw it; persist the preserved binding here too.
acct.auth = save_auth(self.accounts_dir, acct.auth)
existing.auth = acct.auth
existing.proxy_slot = acct.proxy_slot
existing.nickname = acct.nickname
if not existing.manual_disabled:
existing.disabled = False
existing.disabled_reason = ""
existing.last_error = ""
existing.err_count = 0
existing.cool_until = 0
existing.models_fetched_at = 0
self.accounts[index] = existing
self.save_state()
self.apply_proxy_slots()
return existing
self.accounts.append(acct)
self.save_state()
self.apply_proxy_slots()
return acct
def remove(self, uid):
acct = self.get(uid)
if acct is None:
return False
with self._lock:
self.accounts = [a for a in self.accounts if a.uid != uid]
delete_auth(self.accounts_dir, uid)
self.save_state()
return True
def enable(self, uid):
acct = self.get(uid)
if acct is None:
return False
acct.disabled = False
acct.disabled_reason = ""
acct.manual_disabled = False
acct.last_error = ""
acct.err_count = 0
acct.cool_until = 0
self.save_state()
return True
def disable(self, uid, reason="manual disable"):
acct = self.get(uid)
if acct is None:
return False
acct.disabled = True
acct.disabled_reason = reason
acct.manual_disabled = True
acct.last_error = reason
self.save_state()
return True
def clear_cooldown(self, uid):
acct = self.get(uid)
if acct is None:
return False
acct.cool_until = 0
acct.err_count = 0
self.save_state()
return True
def set_note(self, uid, note):
acct = self.get(uid)
if acct is None:
return False
acct.note = str(note or "").strip()[:200]
self.save_state()
return True
def set_tasks_enabled(self, uid, enabled):
acct = self.get(uid)
if acct is None:
return False
acct.tasks_enabled = bool(enabled)
self.save_state()
return True
# ---- 调度 ----
def pick(self, model="", session_key=None, exclude=None, allowed_accounts=None):
"""按「能服务该模型 + 健康 + 并发未满」选一个账号。"""
exclude = set(exclude or ())
now = time.time()
with self._lock:
accounts = list(self.accounts)
# 会话粘性:同一段对话优先回到上次的账号。
if session_key:
uid = self._affinity.get(session_key)
if uid and uid not in exclude and (allowed_accounts is None or uid in allowed_accounts):
acct = self.get(uid)
if acct and acct.healthy(now) and acct.has_model(model) \
and acct.active_concurrent < acct.max_concurrent:
return acct
candidates = [a for a in accounts
if a.uid not in exclude and (allowed_accounts is None or a.uid in allowed_accounts) and a.healthy(now)
and a.active_concurrent < a.max_concurrent]
capable = [a for a in candidates if a.has_model(model)]
pool = capable or candidates
if not pool:
return None
pool.sort(key=lambda a: (a.active_concurrent, a.last_used or 0))
return pool[0]
_affinity = {}
def bind_session(self, session_key, uid):
if not session_key or not uid:
return
self._affinity[session_key] = uid
if len(self._affinity) > 4096:
# 简单上限:丢掉最早插入的一批。
for key in list(self._affinity)[:1024]:
self._affinity.pop(key, None)
def acquire(self, acct):
with acct._lock:
if acct.active_concurrent >= acct.max_concurrent:
return False
acct.active_concurrent += 1
acct.last_used = time.time()
return True
def release(self, acct):
released = False
with acct._lock:
if acct.active_concurrent > 0:
acct.active_concurrent -= 1
released = True
if released:
# 在账号锁外唤醒排队者:被唤醒的线程会立刻 `pick()`,那里要
# 遍历账号;持着 acct._lock 通知只会把唤醒拖到锁外,没有意义。
with self._release_cond:
self._release_cond.notify_all()
def wait_for_slot(self, timeout):
"""等任一在飞请求归还名额;返回 True 表示被唤醒。
只当提示用:调用方醒来后必须重新 `pick()`,因为名额可能被另一个
等待者先抢走(也可能在进入 wait 前就已经归还)。
"""
with self._release_cond:
return self._release_cond.wait(max(0.0, float(timeout)))
def busy_accounts(self, exclude=None, allowed_accounts=None):
"""健康、允许使用、但并发名额已满的账号。
用来区分「账号池是空的/全在冷却」和「账号都在忙」:只有后者值得
排队等待。不看 `has_model()`,与 `pick()` 的兜底选号口径保持一致。
"""
exclude = set(exclude or ())
now = time.time()
with self._lock:
accounts = list(self.accounts)
return [acct for acct in accounts
if acct.uid not in exclude
and (allowed_accounts is None or acct.uid in allowed_accounts)
and acct.healthy(now)
and acct.active_concurrent >= acct.max_concurrent]
def note_success(self, acct):
if acct.err_count or acct.cool_until or acct.last_error:
acct.err_count = 0
acct.cool_until = 0
acct.last_error = ""
self.save_state()
def note_error(self, acct, message, soft=False, terminal=False,
cooldown=None):
acct.last_error = str(message or "")[:200]
if terminal:
acct.disabled = True
acct.disabled_reason = acct.last_error
elif soft:
delay = SOFT_COOLDOWN if cooldown is None else max(0.0, float(cooldown))
acct.cool_until = time.time() + delay
else:
acct.err_count += 1
if acct.err_count >= ERR_THRESHOLD:
acct.cool_until = time.time() + ERR_COOLDOWN
acct.err_count = 0
self.save_state()
_POOLS = {}
_POOLS_LOCK = threading.Lock()
def pool_for(accounts_dir, trigger_auto=True):
"""按 accounts_dir 取单例池;配置变化时刷新池配置。"""
key = os.path.abspath(str(accounts_dir or "."))
cfg = load_config(accounts_dir)
with _POOLS_LOCK:
pool = _POOLS.get(key)
if pool is None:
pool = CodeArtsPool(accounts_dir, cfg)
_POOLS[key] = pool
else:
pool.config = cfg
for acct in pool.accounts:
acct.max_concurrent = cfg.get("max_concurrent", 1)
# 锁外触发:自动签到只做判断/记账,真正的领积分在后台线程里跑。
if trigger_auto:
_maybe_auto_checkin(pool)
return pool
def invalidate_pool(accounts_dir=None):
with _POOLS_LOCK:
if accounts_dir is None:
_POOLS.clear()
else:
_POOLS.pop(os.path.abspath(str(accounts_dir)), None)
# ---------------------------------------------------------------------------
# HTTP
# ---------------------------------------------------------------------------
_OPENER_CACHE = {}
_OPENER_LOCK = threading.Lock()
_DIRECT_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def _opener(proxy=""):
"""Build (and cache) an opener pinned to one proxy slot.
Empty/blank means direct, and direct deliberately ignores the process
environment proxies: a CodeArts account that is not bound to a slot must
keep the pre-slot behaviour (no accidental HTTP_PROXY). One opener per
proxy URL keeps each account's traffic on its own exit IP.
"""
proxy = str(proxy or "").strip()
if not proxy:
return _DIRECT_OPENER
with _OPENER_LOCK:
opener = _OPENER_CACHE.get(proxy)
if opener is None:
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({"http": proxy, "https": proxy})
)
_OPENER_CACHE[proxy] = opener
return opener
def _error_text(raw):
try:
parsed = json.loads(raw.decode("utf-8", "replace"))
except Exception:
return raw.decode("utf-8", "replace")[:500]
if isinstance(parsed, dict):
for key in ("error_msg", "message", "error_description", "error"):
value = parsed.get(key)
if isinstance(value, str) and value: