-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathconfig_manager.py
More file actions
4528 lines (3934 loc) · 194 KB
/
config_manager.py
File metadata and controls
4528 lines (3934 loc) · 194 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 -*-
"""
配置文件管理模块
负责管理配置文件的存储位置和迁移
"""
import sys
import os
import json
import re
import shutil
import threading
import asyncio
import time
import math
import uuid
from datetime import date
from copy import deepcopy
from pathlib import Path
from urllib.parse import urlparse, urlunparse
from config import (
APP_NAME,
CONFIG_FILES,
DEFAULT_CONFIG_DATA,
GEOIP_FORCE_NON_MAINLAND,
RESERVED_FIELD_SCHEMA,
)
from config.prompts.prompts_chara import get_lanlan_prompt, is_default_prompt
from utils.api_config_loader import (
get_core_api_profiles,
get_assist_api_profiles,
get_assist_api_key_fields,
get_livestream_config,
is_livestream_active,
)
from utils.custom_tts_adapter import check_custom_tts_voice_allowed
from utils.file_utils import atomic_write_json
from utils.gptsovits_config import normalize_gsv_api_url
from utils.logger_config import get_module_logger
from utils.native_voice_registry import (
is_free_lanlan_app_route,
is_saveable_native_voice,
)
from utils.persona_presets import PERSONA_OVERRIDE_FIELDS
from utils.steam_state import get_steamworks
# Workshop配置相关常量 - 将在ConfigManager实例化时使用self.workshop_dir
logger = get_module_logger(__name__)
def _as_bool(value, default=False):
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
lowered = value.strip().lower()
if lowered in ('true', '1', 'yes', 'on'):
return True
if lowered in ('false', '0', 'no', 'off', ''):
return False
if value is None:
return default
return bool(value)
def get_reserved(data: dict, *path, default=None, legacy_keys: tuple[str, ...] | None = None):
"""统一读取 `_reserved` 下的嵌套字段,支持旧平铺字段回退。
如果 _reserved 中的嵌套路径存在(即使值为 None),直接返回该值;
仅当路径不存在或 _reserved 本身缺失时,才回退到旧平铺字段。
"""
if not isinstance(data, dict):
return default
reserved = data.get("_reserved")
if isinstance(reserved, dict):
current = reserved
found = True
for key in path:
if not isinstance(current, dict) or key not in current:
found = False
break
current = current[key]
if found:
return current
# COMPAT(v1->v2): 旧平铺字段回退读取,避免历史配置在迁移前读不到值。
if legacy_keys:
for legacy_key in legacy_keys:
if legacy_key in data and data[legacy_key] is not None:
return data[legacy_key]
return default
def set_reserved(data: dict, *path_and_value) -> bool:
"""统一写入 `_reserved` 下的嵌套字段,自动创建中间层。
Returns ``True`` if the stored value was actually changed, ``False``
otherwise (including invalid input).
"""
if not isinstance(data, dict) or len(path_and_value) < 2:
return False
*path, value = path_and_value
if not path:
return False
reserved = data.get("_reserved")
if not isinstance(reserved, dict):
reserved = {}
data["_reserved"] = reserved
current = reserved
for key in path[:-1]:
next_node = current.get(key)
if not isinstance(next_node, dict):
next_node = {}
current[key] = next_node
current = next_node
last_key = path[-1]
if last_key in current and current[last_key] == value:
return False
current[last_key] = value
return True
DEFAULT_YUI_LIVE2D_MODEL_PATH = "yui-origin/yui-origin.model3.json"
def _normalize_live2d_model_path(value) -> str:
model_path = str(value or "").strip().replace("\\", "/").lower()
if model_path == "yui-origin":
return DEFAULT_YUI_LIVE2D_MODEL_PATH
return model_path
def _is_default_yui_character(character_name: str, character_data: dict) -> bool:
if not isinstance(character_data, dict):
return False
name = str(character_name or "").strip().upper()
nickname = str(character_data.get("昵称") or "").strip().upper()
if name != "YUI" and nickname != "YUI":
return False
model_path = get_reserved(
character_data,
"avatar",
"live2d",
"model_path",
default="",
legacy_keys=("live2d",),
)
return _normalize_live2d_model_path(model_path) == DEFAULT_YUI_LIVE2D_MODEL_PATH
# 历史上 free_voices["yui_cn"] 用过、现已被替换的免费 YUI 预设音色 ID。
# 这些值仍残留在存量用户的 characters.json 里,但已不在 free_voices 白名单中,
# 会被 cleanup_invalid_voice_ids 判为 invalid 清空 → 空 voice 落到 free/step
# provider 的 default_voice(qingchunshaonv),导致「一直吃默认 YUI、从没手动
# 选过音色」的免费用户在音色 ID 更替后无声掉档到通用女声。cleanup 在判 invalid
# 前先把这些值平移到现役 yui_cn 即可兜住。将来再更替 YUI 音色时,把被替换掉的
# 旧值追加进这个集合。
_DEPRECATED_FREE_YUI_VOICE_IDS = frozenset({"voice-tone-R6NtLH3Hk0"})
def _get_default_yui_free_voice_id() -> str:
from utils.api_config_loader import get_free_voices
from utils.language_utils import get_global_language_full
free_voices = get_free_voices() or {}
try:
language = str(get_global_language_full() or "").strip().lower().replace("-", "_")
except Exception:
language = ""
language_aliases = {
"zh": "cn",
"zh_cn": "cn",
"zh_hans": "cn",
"zh_tw": "tw",
"zh_hant": "tw",
}
suffix = language_aliases.get(language, language.split("_", 1)[0] if language else "")
keys = []
if suffix:
keys.append(f"yui_{suffix}")
keys.extend(("yui_cn", "cuteGirl"))
for key in keys:
voice_id = str(free_voices.get(key) or "").strip()
if voice_id:
return voice_id
return next((str(voice_id).strip() for voice_id in free_voices.values() if str(voice_id or "").strip()), "")
async def ensure_default_yui_voice_for_free_api(config_manager, core_cfg: dict | None = None) -> bool:
"""Ensure the default YUI card has the free YUI voice when free API is active."""
if not isinstance(core_cfg, dict):
try:
core_cfg = await config_manager.aget_core_config()
except Exception:
core_cfg = {}
if not isinstance(core_cfg, dict):
return False
# 免费预设 YUI 音色只在 core=free 运行时可用,与 assist 无关。
if (core_cfg.get("coreApi") or core_cfg.get("CORE_API_TYPE")) != "free":
return False
characters = await config_manager.aload_characters()
if not isinstance(characters, dict):
return False
current_name = str(characters.get("当前猫娘") or "").strip()
catgirls = characters.get("猫娘")
if not current_name or not isinstance(catgirls, dict):
return False
current_character = catgirls.get(current_name)
if not _is_default_yui_character(current_name, current_character):
return False
current_voice_id = str(get_reserved(
current_character,
"voice_id",
default="",
legacy_keys=("voice_id",),
) or "").strip()
if current_voice_id:
return False
# 海外免费(free + *.lanlan.app):默认音色是品牌 yui(free_intl 的 default_voice),
# 下发字面量 "yui"。国内免费(lanlan.tech)仍按语言绑定 free_voices 里的 yui 音色。
#
# 注意:update_core_config 传进来的 raw core_cfg 里 CORE_URL 还是 lanlan.tech,
# get_core_config() 才会按非大陆改写成 lanlan.app,直接判 URL 会漏判海外。
# 故 URL 命中 lanlan.app 走快路,否则用 _check_non_mainland 兜底判海外。
core_url = str((core_cfg or {}).get("CORE_URL") or "")
overseas = is_free_lanlan_app_route("free", core_url)
if not overseas:
try:
overseas = bool(config_manager._check_non_mainland())
except Exception:
overseas = False
yui_voice_id = "yui" if overseas else _get_default_yui_free_voice_id()
if not yui_voice_id:
return False
changed = set_reserved(current_character, "voice_id", yui_voice_id)
if not changed:
return False
await config_manager.asave_characters(characters)
logger.info("已为 free API 下的默认 YUI 绑定音色: %s", yui_voice_id)
return True
def delete_reserved(data: dict, *path) -> bool:
"""删除 `_reserved` 下的嵌套字段,并尽量清理空的中间层。"""
if not isinstance(data, dict) or not path:
return False
reserved = data.get("_reserved")
if not isinstance(reserved, dict):
return False
current = reserved
parents: list[tuple[dict, str]] = []
for key in path[:-1]:
if not isinstance(current, dict) or key not in current:
return False
parents.append((current, key))
current = current.get(key)
last_key = path[-1]
if not isinstance(current, dict) or last_key not in current:
return False
current.pop(last_key, None)
while parents:
parent, key = parents.pop()
child = parent.get(key)
if isinstance(child, dict) and not child:
parent.pop(key, None)
continue
break
if isinstance(data.get("_reserved"), dict) and not data["_reserved"]:
data.pop("_reserved", None)
return True
def _normalize_persona_override_profile(raw_profile: object) -> dict[str, str]:
if not isinstance(raw_profile, dict):
return {}
profile: dict[str, str] = {}
for field in PERSONA_OVERRIDE_FIELDS:
value = str(raw_profile.get(field) or "").strip()
if value:
profile[field] = value
return profile
def _get_persona_override(character_payload: dict) -> dict | None:
if not isinstance(character_payload, dict):
return None
reserved = character_payload.get("_reserved")
if not isinstance(reserved, dict):
return None
override = reserved.get("persona_override")
if not isinstance(override, dict):
return None
return override
def _build_effective_character_payload(character_payload: dict, entity: str = "neko") -> dict:
if not isinstance(character_payload, dict):
return {}
effective_payload = deepcopy(character_payload)
override = _get_persona_override(character_payload)
if not isinstance(override, dict):
for field, value in _build_ai_context_fields(
character_payload,
existing_fields=set(effective_payload.keys()),
entity=entity,
).items():
effective_payload[field] = value
return effective_payload
profile = _normalize_persona_override_profile(override.get("profile"))
for field, value in profile.items():
effective_payload[field] = value
for field, value in _build_ai_context_fields(
character_payload,
existing_fields=set(effective_payload.keys()),
entity=entity,
).items():
effective_payload[field] = value
return effective_payload
def _append_persona_guidance_to_prompt(prompt_text: str, character_payload: dict) -> str:
override = _get_persona_override(character_payload)
if not isinstance(override, dict):
return prompt_text
guidance = ""
from_preset = False
preset_id = str(override.get("preset_id") or "").strip()
if preset_id:
# 运行时按当前全局语言重新解析,使 persona prompt 与基础 LANLAN prompt
# 一样跟随语言切换;仅当 preset_id 已被代码移除时才退回到落盘字符串。
try:
from utils.persona_presets import get_persona_prompt_guidance
guidance = (get_persona_prompt_guidance(preset_id) or "").strip()
from_preset = bool(guidance)
except Exception:
guidance = ""
if not guidance:
guidance = str(override.get("prompt_guidance") or "").strip()
if not guidance:
return prompt_text
# preset 的 guidance 是一份**完整独立**的人设 prompt,骨架(fictional-character
# 前言 + <Context Awareness> + <WARNING> + <IMPORTANT>)与默认 base 逐字相同。
# 直接 append 会让整套骨架重复一遍(~1500 字),且这段经 lanlan_prompt_map 流向
# 主对话 system prompt、proactive、break reminder、各插件等**所有**消费点。
# 当 base 仍是默认 prompt 时,preset 本身就是完整人设 → 用它替换 base,避免重复;
# 仅当用户写过自定义 system_prompt(非默认)时才退回 append 以保留其自定义内容。
if from_preset and is_default_prompt(prompt_text):
return guidance
return f"{prompt_text}\n\nAdditional role guidance: {guidance}"
_AI_CONTEXT_RENAME_EVENT_FIELD = "__ai_context.profile_rename_events"
def _unique_ai_context_field_name(existing_fields: set[str] | None) -> str:
existing = {str(field) for field in (existing_fields or set())}
if _AI_CONTEXT_RENAME_EVENT_FIELD not in existing:
return _AI_CONTEXT_RENAME_EVENT_FIELD
index = 2
while f"{_AI_CONTEXT_RENAME_EVENT_FIELD}.{index}" in existing:
index += 1
return f"{_AI_CONTEXT_RENAME_EVENT_FIELD}.{index}"
def _join_profile_rename_old_names(lang: str | None, names: list[str]) -> str:
normalized_lang = str(lang or "").strip().lower()
separator = "、" if normalized_lang.startswith(("zh", "ja")) else ", "
return separator.join(names)
def _build_ai_context_fields(
character_payload: dict,
existing_fields: set[str] | None = None,
entity: str = "neko",
) -> dict[str, str]:
"""把隐藏运行时事件展开成只给 prompt/记忆同步使用的合成字段。
entity 区分这份 payload 是猫娘(neko)还是主人(master),决定改名记录的人称:
主人的记录进的是猫娘 persona 的 master section,必须第二人称,不能第一人称。
"""
if not isinstance(character_payload, dict):
return {}
rename_events = get_reserved(
character_payload,
"ai_context",
"rename_events",
default=[],
)
if not isinstance(rename_events, list):
return {}
try:
from utils.language_utils import get_global_language_full
lang = get_global_language_full()
except Exception:
lang = None
from config.prompts.prompts_memory import render_profile_rename_event_context
field_name = _unique_ai_context_field_name(existing_fields)
old_names: list[str] = []
current_name = ""
legacy_lines: list[str] = []
for event in rename_events:
if not isinstance(event, dict):
continue
if str(event.get("type") or "").strip() != "profile_rename":
continue
old_name = str(event.get("old_name") or "").strip()
new_name = str(event.get("new_name") or "").strip()
if old_name and new_name:
if old_name not in old_names:
old_names.append(old_name)
current_name = new_name
else:
text = str(event.get("text") or "").strip()
if not text:
continue
legacy_lines.append(text)
if current_name:
old_names = [name for name in old_names if name != current_name]
lines: list[str] = []
if old_names and current_name:
old_names_text = _join_profile_rename_old_names(lang, old_names)
label, text = render_profile_rename_event_context(lang, old_names_text, current_name, entity=entity)
lines.append(f"{label}: {text}")
lines.extend(legacy_lines)
if not lines:
return {}
return {field_name: "\n".join(lines)}
def _has_generated_persona_selection_prompt(prompt_text: object) -> bool:
if not isinstance(prompt_text, str):
return False
return "<NEKO_PERSONA_SELECTION>" in prompt_text
def strip_generated_persona_selection_prompt(prompt_text: object) -> str | None:
if not isinstance(prompt_text, str):
return None
if not _has_generated_persona_selection_prompt(prompt_text):
return prompt_text
cleaned_prompt = re.sub(
r"\s*<NEKO_PERSONA_SELECTION>.*?</NEKO_PERSONA_SELECTION>\s*",
"\n\n",
prompt_text,
flags=re.DOTALL,
)
cleaned_prompt = re.sub(r"\n{3,}", "\n\n", cleaned_prompt).strip()
return cleaned_prompt
def _resolve_effective_character_prompt(character_payload: dict) -> str:
stored_prompt = get_reserved(
character_payload,
"system_prompt",
default=None,
legacy_keys=("system_prompt",),
)
if stored_prompt is None or is_default_prompt(stored_prompt):
return get_lanlan_prompt()
# 旧版人格功能会把整段模板化人格 prompt 直接写进 system_prompt。
# 不论当前是否仍保留 persona_override,这类历史片段都不应继续直接喂给模型。
if _has_generated_persona_selection_prompt(stored_prompt):
cleaned_prompt = strip_generated_persona_selection_prompt(stored_prompt)
return cleaned_prompt or get_lanlan_prompt()
return stored_prompt
def _legacy_live2d_to_model_path(legacy_live2d: str) -> str:
"""将旧 live2d 目录名转为 model3 文件路径。"""
if not legacy_live2d:
return ""
raw = str(legacy_live2d).strip().replace("\\", "/")
if not raw:
return ""
if raw.endswith(".model3.json"):
return raw
# COMPAT(v1->v2): 历史配置只有目录名(如 mao_pro),迁移时自动补全默认 model3 文件名。
return f"{raw}/{raw}.model3.json"
def _legacy_live2d_name_from_model_path(model_path: str) -> str:
"""将新 model_path 反向还原为旧 live2d 模型名(兼容旧前端字段)。"""
if not model_path:
return ""
raw = str(model_path).strip().replace("\\", "/")
if not raw:
return ""
if raw.endswith(".model3.json"):
parent = raw.rsplit("/", 1)[0] if "/" in raw else ""
if parent:
return parent.rsplit("/", 1)[-1]
filename = raw.rsplit("/", 1)[-1]
name = filename[:-len(".model3.json")]
return name
return raw.rsplit("/", 1)[-1]
def validate_reserved_schema(reserved: dict) -> list[str]:
"""校验 `_reserved` 结构,返回错误列表(空列表表示通过)。"""
errors: list[str] = []
def _walk(value, schema, path: str):
if isinstance(schema, dict):
if not isinstance(value, dict):
errors.append(f"{path} 需要 dict,实际 {type(value).__name__}")
return
for key, sub_schema in schema.items():
if key in value and value[key] is not None:
_walk(value[key], sub_schema, f"{path}.{key}")
return
if isinstance(schema, tuple):
if not isinstance(value, schema):
expected = ",".join(t.__name__ for t in schema)
errors.append(f"{path} 需要类型({expected}),实际 {type(value).__name__}")
return
if not isinstance(value, schema):
errors.append(f"{path} 需要 {schema.__name__},实际 {type(value).__name__}")
if reserved is None:
return errors
_walk(reserved, RESERVED_FIELD_SCHEMA, "_reserved")
return errors
def migrate_catgirl_reserved(catgirl_data: dict) -> bool:
"""迁移单个角色配置到 `_reserved` 结构,返回是否发生变更。"""
if not isinstance(catgirl_data, dict):
return False
changed = False
if not isinstance(catgirl_data.get("_reserved"), dict):
catgirl_data["_reserved"] = {}
changed = True
voice_id = get_reserved(catgirl_data, "voice_id", default="", legacy_keys=("voice_id",))
if voice_id is not None:
changed |= set_reserved(catgirl_data, "voice_id", str(voice_id))
system_prompt = get_reserved(catgirl_data, "system_prompt", default=None, legacy_keys=("system_prompt",))
if system_prompt is not None:
changed |= set_reserved(catgirl_data, "system_prompt", str(system_prompt))
model_type = str(
get_reserved(catgirl_data, "avatar", "model_type", default="", legacy_keys=("model_type",))
).strip().lower()
if model_type not in {"live2d", "vrm", "live3d"}:
has_vrm = catgirl_data.get("vrm") or get_reserved(catgirl_data, "avatar", "vrm", "model_path")
has_mmd = catgirl_data.get("mmd") or get_reserved(catgirl_data, "avatar", "mmd", "model_path")
model_type = "live3d" if (has_vrm or has_mmd) else "live2d"
# 归一化:旧配置中的 'vrm' 统一为 'live3d'
if model_type == "vrm":
model_type = "live3d"
changed |= set_reserved(catgirl_data, "avatar", "model_type", model_type)
asset_source_id = get_reserved(
catgirl_data,
"avatar",
"asset_source_id",
default="",
legacy_keys=("live2d_item_id", "item_id"),
)
asset_source_id = str(asset_source_id).strip() if asset_source_id is not None else ""
changed |= set_reserved(catgirl_data, "avatar", "asset_source_id", asset_source_id)
asset_source = get_reserved(catgirl_data, "avatar", "asset_source", default="")
if not asset_source:
asset_source = "steam_workshop" if asset_source_id else "local"
changed |= set_reserved(catgirl_data, "avatar", "asset_source", str(asset_source))
live2d_model_path = get_reserved(
catgirl_data,
"avatar",
"live2d",
"model_path",
default="",
legacy_keys=("live2d",),
)
if live2d_model_path:
changed |= set_reserved(
catgirl_data,
"avatar",
"live2d",
"model_path",
_legacy_live2d_to_model_path(str(live2d_model_path)),
)
live2d_idle_animation = get_reserved(
catgirl_data,
"avatar",
"live2d",
"idle_animation",
default=None,
legacy_keys=("live2d_idle_animation",),
)
if live2d_idle_animation is not None:
if isinstance(live2d_idle_animation, str):
changed |= set_reserved(catgirl_data, "avatar", "live2d", "idle_animation", live2d_idle_animation if live2d_idle_animation else None)
elif isinstance(live2d_idle_animation, list):
changed |= set_reserved(catgirl_data, "avatar", "live2d", "idle_animation", live2d_idle_animation[0] if live2d_idle_animation else None)
vrm_model_path = get_reserved(
catgirl_data,
"avatar",
"vrm",
"model_path",
default="",
legacy_keys=("vrm",),
)
if vrm_model_path:
changed |= set_reserved(catgirl_data, "avatar", "vrm", "model_path", str(vrm_model_path).strip())
vrm_animation = get_reserved(
catgirl_data,
"avatar",
"vrm",
"animation",
default=None,
legacy_keys=("vrm_animation",),
)
if vrm_animation is not None:
changed |= set_reserved(catgirl_data, "avatar", "vrm", "animation", vrm_animation)
idle_animation = get_reserved(
catgirl_data,
"avatar",
"vrm",
"idle_animation",
default=None,
legacy_keys=("idleAnimation", "idleAnimations"),
)
if idle_animation is not None:
# 向前兼容: 旧版存的是 string, 迁移为 list; 空值保留 []
if isinstance(idle_animation, str):
changed |= set_reserved(catgirl_data, "avatar", "vrm", "idle_animation", [idle_animation] if idle_animation else [])
elif isinstance(idle_animation, list):
changed |= set_reserved(catgirl_data, "avatar", "vrm", "idle_animation", idle_animation)
lighting = get_reserved(
catgirl_data,
"avatar",
"vrm",
"lighting",
default=None,
legacy_keys=("lighting",),
)
if isinstance(lighting, dict):
changed |= set_reserved(catgirl_data, "avatar", "vrm", "lighting", lighting)
# MMD 模型路径迁移
mmd_model_path = get_reserved(
catgirl_data,
"avatar",
"mmd",
"model_path",
default="",
legacy_keys=("mmd",),
)
if mmd_model_path:
changed |= set_reserved(catgirl_data, "avatar", "mmd", "model_path", str(mmd_model_path).strip())
mmd_animation = get_reserved(
catgirl_data,
"avatar",
"mmd",
"animation",
default=None,
legacy_keys=("mmd_animation",),
)
if mmd_animation is not None:
changed |= set_reserved(catgirl_data, "avatar", "mmd", "animation", mmd_animation)
mmd_idle_animation = get_reserved(
catgirl_data,
"avatar",
"mmd",
"idle_animation",
default=None,
legacy_keys=("mmd_idle_animation", "mmd_idle_animations"),
)
if mmd_idle_animation is not None:
# 向前兼容: 旧版存的是 string, 迁移为 list; 空值保留 []
if isinstance(mmd_idle_animation, str):
changed |= set_reserved(catgirl_data, "avatar", "mmd", "idle_animation", [mmd_idle_animation] if mmd_idle_animation else [])
elif isinstance(mmd_idle_animation, list):
changed |= set_reserved(catgirl_data, "avatar", "mmd", "idle_animation", mmd_idle_animation)
live3d_sub_type = str(
get_reserved(
catgirl_data,
"avatar",
"live3d_sub_type",
default="",
legacy_keys=("live3d_sub_type",),
)
or ""
).strip().lower()
if live3d_sub_type not in {"vrm", "mmd"}:
has_mmd_model = bool(get_reserved(catgirl_data, "avatar", "mmd", "model_path", default=""))
has_vrm_model = bool(get_reserved(catgirl_data, "avatar", "vrm", "model_path", default=""))
if model_type == "live3d":
if has_mmd_model:
live3d_sub_type = "mmd"
elif has_vrm_model:
live3d_sub_type = "vrm"
else:
live3d_sub_type = ""
elif has_mmd_model and not has_vrm_model:
live3d_sub_type = "mmd"
elif has_vrm_model and not has_mmd_model:
live3d_sub_type = "vrm"
else:
live3d_sub_type = ""
if live3d_sub_type:
changed |= set_reserved(catgirl_data, "avatar", "live3d_sub_type", live3d_sub_type)
else:
# 非 3D 角色或没有明确活动 3D 子类型时,不要强行写回空字符串,
# 否则会让导出/导入后的角色配置出现无意义的额外字段。
changed |= delete_reserved(catgirl_data, "avatar", "live3d_sub_type")
# COMPAT(v1->v2): 保留字段统一迁入 _reserved 后,移除旧平铺字段,避免再次泄露到可编辑字段。
for legacy_key in (
"voice_id",
"system_prompt",
"model_type",
"live3d_sub_type",
"live2d_item_id",
"item_id",
"live2d",
"live2d_idle_animation",
"vrm",
"vrm_animation",
"idleAnimation",
"idleAnimations",
"lighting",
"vrm_rotation",
"mmd",
"mmd_animation",
"mmd_idle_animation",
"mmd_idle_animations",
):
if legacy_key in catgirl_data:
catgirl_data.pop(legacy_key, None)
changed = True
return changed
def flatten_reserved(catgirl_data: dict) -> dict:
"""将 `_reserved` 展开成旧平铺字段(仅用于兼容旧调用方/前端)。"""
if not isinstance(catgirl_data, dict):
return catgirl_data
result = dict(catgirl_data)
voice_id = get_reserved(result, "voice_id", default="")
if voice_id:
result["voice_id"] = voice_id
system_prompt = get_reserved(result, "system_prompt", default=None)
if system_prompt is not None:
result["system_prompt"] = system_prompt
model_type = get_reserved(result, "avatar", "model_type", default="live2d")
if model_type:
result["model_type"] = model_type
live3d_sub_type = get_reserved(result, "avatar", "live3d_sub_type", default="")
if live3d_sub_type:
result["live3d_sub_type"] = live3d_sub_type
live2d_model_path = get_reserved(result, "avatar", "live2d", "model_path", default="")
if live2d_model_path:
result["live2d"] = _legacy_live2d_name_from_model_path(str(live2d_model_path))
live2d_idle_animation = get_reserved(result, "avatar", "live2d", "idle_animation", default=None)
if live2d_idle_animation is not None:
result["live2d_idle_animation"] = live2d_idle_animation
vrm_model_path = get_reserved(result, "avatar", "vrm", "model_path", default="")
if vrm_model_path:
result["vrm"] = vrm_model_path
asset_source_id = get_reserved(result, "avatar", "asset_source_id", default="")
if asset_source_id:
result["live2d_item_id"] = asset_source_id
vrm_animation = get_reserved(result, "avatar", "vrm", "animation", default=None)
if vrm_animation is not None:
result["vrm_animation"] = vrm_animation
idle_animation = get_reserved(result, "avatar", "vrm", "idle_animation", default=None)
if idle_animation is not None:
# idleAnimation (string): 供 vrm-init / vrm-manager 等运行时消费
# idleAnimations (list): 供 model_manager 多选 UI 消费
if isinstance(idle_animation, str):
result["idleAnimation"] = idle_animation
result["idleAnimations"] = [idle_animation] if idle_animation else []
elif isinstance(idle_animation, list):
result["idleAnimation"] = idle_animation[0] if idle_animation else ""
result["idleAnimations"] = idle_animation
else:
result["idleAnimation"] = ""
result["idleAnimations"] = []
lighting = get_reserved(result, "avatar", "vrm", "lighting", default=None)
if isinstance(lighting, dict):
result["lighting"] = lighting
mmd_model_path = get_reserved(result, "avatar", "mmd", "model_path", default="")
if mmd_model_path:
result["mmd"] = mmd_model_path
mmd_animation = get_reserved(result, "avatar", "mmd", "animation", default=None)
if mmd_animation is not None:
result["mmd_animation"] = mmd_animation
mmd_idle_animation = get_reserved(result, "avatar", "mmd", "idle_animation", default=None)
if mmd_idle_animation is not None:
# mmd_idle_animation (string): 供 mmd-init / app-interpage 等运行时消费
# mmd_idle_animations (list): 供 model_manager 多选 UI 消费
if isinstance(mmd_idle_animation, str):
result["mmd_idle_animation"] = mmd_idle_animation
result["mmd_idle_animations"] = [mmd_idle_animation] if mmd_idle_animation else []
elif isinstance(mmd_idle_animation, list):
result["mmd_idle_animation"] = mmd_idle_animation[0] if mmd_idle_animation else ""
result["mmd_idle_animations"] = mmd_idle_animation
else:
result["mmd_idle_animation"] = ""
result["mmd_idle_animations"] = []
touch_set = get_reserved(result, 'touch_set', default=None)
if touch_set:
result['touch_set'] = touch_set
return result
class ConfigManager:
"""配置文件管理器"""
_agent_quota_lock = threading.Lock()
_selected_root_unavailable_recovery_override_roots: set[str] = set()
_free_agent_daily_limit = 500 # 免费配额并非只在本地实施,本地计算是为了减少无效请求、节约网络带宽。
# 本地每日配额只对真正的免费 Agent 模型计数;模型名与 config/api_providers.json 的 assist free profile 保持一致。
_free_agent_model_name = "free-agent-model"
# 配额耗尽时给前端弹提示的节流:与 _agent_quota_lock 不同的锁,避免在持有配额锁时重入。
# notifier 由 agent_server 在启动时注册(进程级),收到耗尽信号最多每 _quota_notify_interval_s 秒触发一次。
_quota_notify_lock = threading.Lock()
_quota_notify_interval_s = 10.0
_quota_notify_last_monotonic = 0.0
_quota_exceeded_notifier = None
ROOT_STATE_VERSION = 1
CLOUDSAVE_LOCAL_STATE_VERSION = 1
CHARACTER_TOMBSTONES_STATE_VERSION = 1
@property
def selected_root(self):
return self.committed_selected_root
@selected_root.setter
def selected_root(self, value):
self.committed_selected_root = value
def __init__(self, app_name=None):
"""
初始化配置管理器
Args:
app_name: 应用名称,默认使用配置中的 APP_NAME
"""
self.app_name = app_name if app_name is not None else APP_NAME
# 检测是否在子进程中,子进程静默初始化(通过 main_server.py 设置的环境变量)
self._verbose = '_NEKO_MAIN_SERVER_INITIALIZED' not in os.environ
self.docs_dir = self._get_documents_directory()
default_app_docs_dir = self.docs_dir / self.app_name
# CFA (Windows 受控文件夹访问/反勒索防护) 检测:
# 如果原始 Documents 路径可读但不可写,记住它以便从中读取用户数据(模型等)
first_readable_non_writable = getattr(self, '_first_non_writable_readable_candidate', None)
self._cfa_fallback_write_docs_dir = None
if (
sys.platform == "win32"
and first_readable_non_writable is not None
and first_readable_non_writable != self.docs_dir
):
self._readable_docs_dir = first_readable_non_writable
self._cfa_fallback_write_docs_dir = self.docs_dir
print("⚠ WARNING [ConfigManager] 文档目录不可写(可能受Windows安全策略/反勒索防护保护)!", file=sys.stderr)
print(f"⚠ WARNING [ConfigManager] 原始文档路径(只读): {first_readable_non_writable}", file=sys.stderr)
print(f"⚠ WARNING [ConfigManager] 回退写入路径: {self.docs_dir}", file=sys.stderr)
print("⚠ WARNING [ConfigManager] 用户数据将从原始路径读取,写入操作将使用回退路径", file=sys.stderr)
else:
self._readable_docs_dir = None
resolved_app_docs_dir = default_app_docs_dir
resolved_anchor_root = default_app_docs_dir
committed_selected_root = default_app_docs_dir
recovery_committed_root_unavailable = False
default_anchor_root = None
try:
from utils.storage_policy import (
compute_anchor_root,
is_runtime_root_available,
load_storage_policy,
normalize_runtime_root,
paths_equal,
)
env_selected_root = os.environ.get("NEKO_STORAGE_SELECTED_ROOT", "").strip()
env_anchor_root = os.environ.get("NEKO_STORAGE_ANCHOR_ROOT", "").strip()
default_anchor_root = compute_anchor_root(self, current_root=default_app_docs_dir)
resolved_anchor_root = default_anchor_root
policy_anchor_root = normalize_runtime_root(env_anchor_root or default_anchor_root)
policy = load_storage_policy(self, anchor_root=policy_anchor_root)
if env_selected_root:
resolved_app_docs_dir = normalize_runtime_root(env_selected_root)
resolved_anchor_root = normalize_runtime_root(env_anchor_root or default_anchor_root)
committed_selected_root = resolved_app_docs_dir
if isinstance(policy, dict):
first_run_completed = bool(policy.get("first_run_completed"))
selected_root_value = str(policy.get("selected_root") or "").strip()
if selected_root_value:
committed_selected_root = normalize_runtime_root(selected_root_value)
anchor_root_value = str(policy.get("anchor_root") or "").strip()
if anchor_root_value and not env_anchor_root:
resolved_anchor_root = normalize_runtime_root(anchor_root_value)
if (
first_run_completed
and paths_equal(resolved_app_docs_dir, resolved_anchor_root)
and not paths_equal(committed_selected_root, resolved_anchor_root)
and not is_runtime_root_available(committed_selected_root)
):
recovery_committed_root_unavailable = True
else:
if env_anchor_root:
resolved_anchor_root = normalize_runtime_root(env_anchor_root)
if isinstance(policy, dict):
first_run_completed = bool(policy.get("first_run_completed"))
selected_root_value = str(policy.get("selected_root") or "").strip()
if selected_root_value:
committed_selected_root = normalize_runtime_root(selected_root_value)
resolved_app_docs_dir = committed_selected_root
if not env_anchor_root:
resolved_anchor_root = normalize_runtime_root(
str(policy.get("anchor_root") or "").strip() or default_anchor_root
)
if (
first_run_completed
and not paths_equal(committed_selected_root, resolved_anchor_root)
and not is_runtime_root_available(committed_selected_root)
):
resolved_app_docs_dir = resolved_anchor_root
recovery_committed_root_unavailable = True
except Exception as e: