-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin_method.py
More file actions
3176 lines (2755 loc) · 111 KB
/
plugin_method.py
File metadata and controls
3176 lines (2755 loc) · 111 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
"""
插件方法
"""
import asyncio
from collections import Counter
from datetime import datetime, timezone
from typing import Annotated, Any, Dict, List, Optional, Set, Tuple
from nekro_agent.api.schemas import AgentCtx
from nekro_agent.core import logger
from nekro_agent.services.plugin.base import SandboxMethodType
from nekro_agent.services.command.base import CommandPermission
from nekro_agent.services.command.ctl import CmdCtl
from nekro_agent.services.command.schemas import (
Arg,
CommandExecutionContext,
CommandResponse,
)
from nekro_agent.models.db_chat_message import DBChatMessage
from .mem0_output_formatter import (
format_add_output,
format_get_all_output,
format_history_output,
format_history_text,
format_search_output,
normalize_results,
_format_memory_list,
_get_combined_score,
)
from .mem0_utils import get_mem0_client
from .plugin import get_memory_config, plugin
from .utils import MemoryScope, decode_id, get_preset_id, resolve_memory_scope
from .pre_search_utils import build_pre_search_query, convert_db_messages_to_dict
from .dedup_simhash import SimHasher, hamming_distance_hex
from .dedup_similarity import calculate_similarity
from .query_rewrite import should_skip_retrieval
from .extraction_prompts import ENHANCED_MEMORY_PROMPT
from .extraction_parser import parse_extracted_memories
from .memory_engine_router import route_search
_MIGRATION_IN_FLIGHT: Set[Tuple[Optional[str], Optional[str], Optional[str], str]] = (
set()
)
_turn_counter: Dict[str, int] = {} # chat_key → turn count
_REGISTERED_SCOPE_QUERIES: Set[Tuple[Optional[str], Optional[str], Optional[str]]] = (
set()
)
def _memory_identifier(item: Dict[str, Any]) -> Optional[str]:
"""提取统一的记忆ID,便于跨层去重。"""
for key in ("id", "memory_id"):
value = item.get(key)
if value:
return str(value)
return None
def _normalize_importance_value(value: Any, default: int = 5) -> int:
try:
normalized = int(value)
except (TypeError, ValueError):
return default
if 1 <= normalized <= 10:
return normalized
return default
def _normalize_expiration_date(value: Optional[str]) -> Optional[str]:
if value is None:
return None
raw = str(value).strip()
if not raw:
return None
if raw.endswith("Z"):
raw = raw[:-1] + "+00:00"
try:
parsed = datetime.fromisoformat(raw)
except (TypeError, ValueError):
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
normalized = parsed.astimezone(timezone.utc).replace(microsecond=0)
return normalized.isoformat().replace("+00:00", "Z")
def _normalize_memory_metadata(
metadata: Optional[Dict[str, Any]],
*,
expiration_date: Optional[str] = None,
importance: Optional[Any] = None,
) -> Dict[str, Any]:
merged_metadata: Dict[str, Any] = dict(metadata or {})
normalized_expiration = _normalize_expiration_date(expiration_date)
if normalized_expiration:
merged_metadata["expiration_date"] = normalized_expiration
elif "expiration_date" in merged_metadata:
existing_expiration = _normalize_expiration_date(
str(merged_metadata.get("expiration_date") or "")
)
if existing_expiration:
merged_metadata["expiration_date"] = existing_expiration
else:
merged_metadata.pop("expiration_date", None)
importance_source = (
importance if importance is not None else merged_metadata.get("importance")
)
merged_metadata["importance"] = _normalize_importance_value(
importance_source, default=5
)
return merged_metadata
def _register_scope_query(
*,
user_id: Optional[str] = None,
agent_id: Optional[str] = None,
run_id: Optional[str] = None,
) -> None:
if user_id is None and agent_id is None and run_id is None:
return
_REGISTERED_SCOPE_QUERIES.add((user_id, agent_id, run_id))
def _register_layer_scope(layer_ids: Optional[Dict[str, Any]]) -> None:
if not layer_ids:
return
_register_scope_query(
user_id=layer_ids.get("user_id"),
agent_id=layer_ids.get("agent_id"),
run_id=layer_ids.get("run_id"),
)
def _register_scope_context(scope: MemoryScope, plugin_config: Any) -> None:
for layer_name in ("conversation", "persona", "global", "guild"):
layer_ids = _resolve_layer_ids(scope, layer_name, plugin_config)
_register_layer_scope(layer_ids)
def _collect_registered_scope_kwargs() -> List[Dict[str, Any]]:
return [
{
key: value
for key, value in (
("user_id", user_id),
("agent_id", agent_id),
("run_id", run_id),
)
if value is not None
}
for user_id, agent_id, run_id in _REGISTERED_SCOPE_QUERIES
]
async def _scan_records_from_registered_scopes(client: Any) -> List[Dict[str, Any]]:
scope_kwargs_list = _collect_registered_scope_kwargs()
if not scope_kwargs_list:
return []
records: List[Dict[str, Any]] = []
seen_ids: Set[str] = set()
for kwargs in scope_kwargs_list:
try:
raw = await asyncio.to_thread(client.get_all, **kwargs)
except Exception as exc:
logger.warning(f"[Memory] 作用域扫描失败 kwargs={kwargs}: {exc}")
continue
for item in normalize_results(raw):
memory_id = _memory_identifier(item)
if memory_id and memory_id in seen_ids:
continue
if memory_id:
seen_ids.add(memory_id)
records.append(item)
return records
def _resolve_cleanup_interval_seconds(plugin_config: Any) -> int:
raw_interval = getattr(plugin_config, "AUTO_CLEANUP_INTERVAL_SECONDS", 600)
try:
interval = int(raw_interval)
except (TypeError, ValueError):
interval = 600
return max(30, interval)
def _fire_and_forget(coro) -> None:
"""将协程提交到后台执行,不阻塞当前调用。错误仅记录日志。"""
async def _wrapper():
try:
await coro
except Exception as exc:
logger.error(f"[Memory] 后台写操作失败: {exc}")
try:
loop = asyncio.get_running_loop()
loop.create_task(_wrapper())
except RuntimeError:
logger.error("[Memory] 无法提交后台任务:没有运行中的事件循环")
def _build_layer_order(
scope,
layers: Optional[List[str]],
preferred: Optional[str],
session_enabled: bool,
agent_enabled: bool,
bind_persona_to_user: bool,
prefer_long_term: bool = False,
guild_enabled: bool = False,
) -> List[str]:
if layers:
normalized_layers: List[str] = []
for layer in layers:
layer_info = scope.layer_ids(
layer,
enable_agent_layer=agent_enabled,
bind_persona_to_user=bind_persona_to_user,
enable_guild_layer=guild_enabled,
)
if not layer_info:
continue
canonical_name = layer_info.get("layer", layer)
if canonical_name not in normalized_layers:
normalized_layers.append(canonical_name)
if normalized_layers:
return normalized_layers
default_order = scope.default_layer_order(
enable_session_layer=session_enabled,
enable_agent_layer=agent_enabled,
prefer_long_term=prefer_long_term,
enable_guild_layer=guild_enabled,
)
if preferred:
normalized_preferred = preferred.strip()
normalized_lower = normalized_preferred.lower()
for layer_name in default_order:
if layer_name.lower() == normalized_lower:
return [layer_name]
logger.warning(
"Invalid preferred memory layer '%s' provided; falling back to default layer order %s",
preferred,
default_order,
)
return default_order
def _resolve_layer_ids(
scope: MemoryScope, layer: str, config: Any
) -> Optional[Dict[str, Any]]:
return scope.layer_ids(
layer,
enable_agent_layer=config.ENABLE_AGENT_SCOPE,
bind_persona_to_user=config.PERSONA_BIND_USER,
enable_guild_layer=getattr(config, "ENABLE_GUILD_SCOPE", False),
)
def _resolve_read_layer_ids(
scope: MemoryScope, layer: str, config: Any
) -> Optional[Dict[str, Any]]:
resolved = _resolve_layer_ids(scope, layer, config)
if resolved:
return resolved
normalized = (layer or "").strip().lower()
persona_aliases = {"persona", "preset", "agent"}
if (
normalized in persona_aliases
and getattr(config, "PERSONA_BIND_USER", False)
and getattr(config, "ENABLE_AGENT_SCOPE", True)
and scope.agent_id
and not scope.user_id
):
fallback = scope.layer_ids(
"persona",
enable_agent_layer=config.ENABLE_AGENT_SCOPE,
bind_persona_to_user=False,
enable_guild_layer=getattr(config, "ENABLE_GUILD_SCOPE", False),
)
if fallback:
logger.info(
"[Memory] persona 读取回退:当前上下文无 user_id,使用仅 agent_id 兼容读取"
)
return fallback
return None
def _annotate_results(
raw_results: Any, layer: str, seen_ids: Set[str]
) -> List[Dict[str, Any]]:
annotated: List[Dict[str, Any]] = []
for item in normalize_results(raw_results):
record = dict(item)
record["layer"] = layer
memory_id = _memory_identifier(record)
if memory_id and memory_id in seen_ids:
continue
if memory_id:
seen_ids.add(memory_id)
annotated.append(record)
return annotated
def _normalize_cli_value(value: Optional[str]) -> Optional[str]:
if value is None:
return None
value = str(value).strip()
return value or None
def _normalize_bool_value(value: Any) -> bool:
if isinstance(value, bool):
return value
if value is None:
return False
normalized = str(value).strip().lower()
return normalized in {"1", "true", "yes", "y", "on"}
def _extract_memory_text(item: Dict[str, Any]) -> str:
return str(item.get("memory") or item.get("data") or item.get("content") or "")
def _split_tokens(tokens: List[str]) -> Tuple[List[str], Dict[str, str]]:
positional: List[str] = []
kv: Dict[str, str] = {}
for token in tokens:
if "=" in token:
key, val = token.split("=", 1)
kv[key.strip().lower()] = val.strip()
else:
if token:
positional.append(token)
return positional, kv
def _parse_layers(layer_value: Optional[str]) -> Optional[List[str]]:
if not layer_value:
return None
normalized = layer_value.strip().lower()
if normalized in ("*", "all", "any", "默认", "全部"):
return None
parts = [
part.strip() for part in layer_value.replace(",", " ").split() if part.strip()
]
return parts or None
def _parse_tags(tag_value: Optional[str]) -> Optional[List[str]]:
if not tag_value:
return None
if isinstance(tag_value, str):
parts = [p.strip() for p in tag_value.replace(",", " ").split() if p.strip()]
return parts or None
return None
def _parse_metadata(options: Dict[str, str]) -> Dict[str, Any]:
metadata: Dict[str, Any] = {}
tag = options.get("tag") or options.get("type")
if tag:
metadata["TYPE"] = tag
expiration_date = (
options.get("expiration_date")
or options.get("expires")
or options.get("expire")
or options.get("expires_at")
or options.get("expiry")
)
expiration_date = _normalize_cli_value(expiration_date)
if expiration_date:
metadata["expiration_date"] = expiration_date
importance_raw = (
options.get("importance") or options.get("imp") or options.get("priority")
)
if importance_raw is not None:
metadata["importance"] = _normalize_importance_value(importance_raw, default=5)
for key, val in options.items():
if key.startswith("meta.") or key.startswith("meta_"):
meta_key = key.split(".", 1)[1] if "." in key else key.split("_", 1)[1]
if meta_key:
metadata[meta_key] = val
return _normalize_memory_metadata(metadata)
def _build_scope_from_context(
context: CommandExecutionContext, options: Dict[str, str]
) -> MemoryScope:
def _safe_getattr(obj: Any, name: str) -> Optional[str]:
try:
return _normalize_cli_value(getattr(obj, name, None))
except Exception:
return None
user_id = _normalize_cli_value(
options.get("user") or options.get("u") or _safe_getattr(context, "user_id")
)
# 如果 user_id 是纯数字(旧 OneBot 格式),添加 "private_" 前缀以匹配 db_user.unique_id
if user_id and user_id.isdigit():
user_id = f"private_{user_id}"
agent_id = _normalize_cli_value(
options.get("agent")
or options.get("persona")
or options.get("preset")
or _safe_getattr(context, "agent_id")
or _safe_getattr(context, "bot_id")
or _safe_getattr(context, "adapter_key")
)
run_source = _normalize_cli_value(
options.get("run")
or options.get("session")
or options.get("chat")
or _safe_getattr(context, "chat_key")
or _safe_getattr(context, "session_id")
)
resolved_scope = resolve_memory_scope(
context,
user_id=user_id,
agent_id=agent_id,
run_id=run_source,
)
logger.debug(
f"[Memory] 构建作用域 - user_id={resolved_scope.user_id}, "
f"agent_id={resolved_scope.agent_id}, run_id={resolved_scope.run_id}, "
f"run_source={run_source}, context.user_id={_safe_getattr(context, 'user_id')}, "
f"context.chat_key={_safe_getattr(context, 'chat_key')}, "
f"context.session_id={_safe_getattr(context, 'session_id')}, "
f"context.adapter_key={_safe_getattr(context, 'adapter_key')}"
)
return resolved_scope
def _build_legacy_value_candidates(layer: str, value: Optional[str]) -> List[str]:
"""构造旧作用域兼容候选值(用于读取回退)。"""
normalized = _normalize_cli_value(value)
if not normalized:
return []
candidates: List[str] = [normalized]
if layer == "global":
if normalized.startswith("private_") and normalized[8:].isdigit():
candidates.append(normalized[8:])
elif normalized.isdigit():
candidates.append(f"private_{normalized}")
if layer == "persona":
if normalized.startswith("preset:"):
raw = normalized.split(":", 1)[1]
if raw:
candidates.append(raw)
else:
candidates.append(f"preset:{normalized}")
if layer == "conversation":
try:
decoded = decode_id(normalized)
if decoded:
candidates.append(decoded)
candidates.append(get_preset_id(decoded))
except Exception:
# 不是有效 base64 时直接忽略
pass
deduped: List[str] = []
for item in candidates:
if item and item not in deduped:
deduped.append(item)
return deduped
def _build_legacy_layer_variants(layer_ids: Dict[str, Any]) -> List[Dict[str, Any]]:
"""基于当前层级ID构造兼容读取候选层级。"""
layer = layer_ids.get("layer")
if layer not in {"global", "persona", "conversation"}:
return []
key_by_layer = {
"global": "user_id",
"persona": "agent_id",
"conversation": "run_id",
}
key = key_by_layer[layer]
current_value = layer_ids.get(key)
candidates = _build_legacy_value_candidates(layer, current_value)
variants: List[Dict[str, Any]] = []
for value in candidates:
variant = {
"layer": layer,
"user_id": None,
"agent_id": None,
"run_id": None,
}
variant[key] = value
variants.append(variant)
unique_variants: List[Dict[str, Any]] = []
seen: Set[Tuple[Optional[str], Optional[str], Optional[str]]] = set()
for variant in variants:
fingerprint = (
variant.get("user_id"),
variant.get("agent_id"),
variant.get("run_id"),
)
if fingerprint in seen:
continue
seen.add(fingerprint)
unique_variants.append(variant)
return unique_variants
def _layer_query_kwargs(
layer_ids: Dict[str, Any], plugin_config: Any
) -> Dict[str, Any]:
_ = plugin_config
query_kwargs: Dict[str, Any] = {}
for key in ("user_id", "agent_id", "run_id"):
value = layer_ids.get(key)
if value is not None:
query_kwargs[key] = value
return query_kwargs
async def _migrate_records_to_target_layer(
client: Any,
raw_results: Any,
target_layer_ids: Dict[str, Any],
plugin_config: Any,
) -> None:
"""将兼容读取命中的旧作用域记忆复制到当前目标作用域。"""
_ = plugin_config
target_layer = target_layer_ids.get("layer")
migrated = 0
seen: Set[str] = set()
for item in normalize_results(raw_results):
memory_id = _memory_identifier(item) or ""
if memory_id and memory_id in seen:
continue
if memory_id:
seen.add(memory_id)
memory_text = item.get("memory") or item.get("text") or item.get("content")
if not memory_text:
continue
metadata = dict(item.get("metadata") or {})
metadata.setdefault("_migrated_from_legacy_scope", True)
if memory_id:
metadata.setdefault("_source_memory_id", memory_id)
_add_kw: Dict[str, Any] = {"metadata": metadata, "infer": False}
if target_layer_ids.get("user_id") is not None:
_add_kw["user_id"] = target_layer_ids["user_id"]
if target_layer_ids.get("agent_id") is not None:
_add_kw["agent_id"] = target_layer_ids["agent_id"]
if target_layer_ids.get("run_id") is not None:
_add_kw["run_id"] = target_layer_ids["run_id"]
await asyncio.to_thread(client.add, memory_text, **_add_kw)
migrated += 1
if migrated:
logger.info(f"[Memory] 自动迁移完成:已复制 {migrated} 条到 {target_layer} 层")
def _schedule_migration_once(
*,
client: Any,
legacy_records: List[Dict[str, Any]],
target_layer_ids: Dict[str, Any],
plugin_config: Any,
) -> None:
migration_key = (
target_layer_ids.get("user_id"),
target_layer_ids.get("agent_id"),
target_layer_ids.get("run_id"),
str(target_layer_ids.get("layer") or ""),
)
if migration_key in _MIGRATION_IN_FLIGHT:
return
_MIGRATION_IN_FLIGHT.add(migration_key)
async def _runner() -> None:
try:
await _migrate_records_to_target_layer(
client=client,
raw_results=legacy_records,
target_layer_ids=target_layer_ids,
plugin_config=plugin_config,
)
except Exception as exc:
logger.error(f"[Memory] 自动迁移失败: {exc}")
finally:
_MIGRATION_IN_FLIGHT.discard(migration_key)
try:
loop = asyncio.get_running_loop()
loop.create_task(_runner())
except RuntimeError:
logger.error("[Memory] 无法提交自动迁移任务:没有运行中的事件循环")
async def _read_with_legacy_fallback(
*,
client: Any,
layer_ids: Dict[str, Any],
plugin_config: Any,
op: str,
query: Optional[str] = None,
limit: Optional[int] = None,
) -> Tuple[List[Dict[str, Any]], bool]:
"""读取指定层级,并在启用时回退读取旧作用域格式。"""
if op not in {"search", "get_all"}:
raise ValueError(f"unsupported op: {op}")
def _id_fingerprint(
ids: Dict[str, Any],
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
return (ids.get("user_id"), ids.get("agent_id"), ids.get("run_id"))
primary_kwargs = _layer_query_kwargs(layer_ids, plugin_config)
if op == "search":
if not query:
return [], False
primary_raw = await route_search(
query=query,
limit=limit or 5,
**primary_kwargs,
)
else:
primary_raw = await asyncio.to_thread(client.get_all, **primary_kwargs)
merged = normalize_results(primary_raw)
has_primary = bool(merged)
primary_count = len(merged)
seen_ids: Set[str] = set()
for item in merged:
memory_id = _memory_identifier(item)
if memory_id:
seen_ids.add(memory_id)
legacy_hit = False
legacy_variants_hit = 0
legacy_records_merged = 0
if not getattr(plugin_config, "LEGACY_SCOPE_FALLBACK_ENABLED", True):
return merged, legacy_hit
target_fingerprint = _id_fingerprint(layer_ids)
allow_auto_migrate = getattr(plugin_config, "AUTO_MIGRATE_ON_READ", False)
if allow_auto_migrate and op == "search" and (not has_primary):
# search 的空结果不代表目标层无数据(可能只是查询词未命中),避免误迁移。
existence_probe = await asyncio.to_thread(client.get_all, **primary_kwargs)
has_primary = bool(normalize_results(existence_probe))
for variant in _build_legacy_layer_variants(layer_ids):
if _id_fingerprint(variant) == target_fingerprint:
continue
legacy_kwargs = _layer_query_kwargs(variant, plugin_config)
if op == "search":
legacy_raw = await route_search(
query=query,
limit=limit or 5,
**legacy_kwargs,
)
else:
legacy_raw = await asyncio.to_thread(client.get_all, **legacy_kwargs)
legacy_records = normalize_results(legacy_raw)
if not legacy_records:
continue
legacy_hit = True
legacy_variants_hit += 1
for record in legacy_records:
memory_id = _memory_identifier(record)
if memory_id and memory_id in seen_ids:
continue
if memory_id:
seen_ids.add(memory_id)
merged.append(record)
legacy_records_merged += 1
# 自动迁移采用保守策略:仅当新作用域当前为空时,才把旧作用域结果复制到新作用域
if allow_auto_migrate and (not has_primary) and legacy_records:
logger.info(
f"[Memory] 触发自动迁移排队:layer={layer_ids.get('layer')}, "
f"legacy_records={len(legacy_records)}"
)
_schedule_migration_once(
client=client,
legacy_records=legacy_records,
target_layer_ids=layer_ids,
plugin_config=plugin_config,
)
if legacy_hit:
logger.debug(
f"[Memory] 兼容读取统计:layer={layer_ids.get('layer')}, "
f"primary={primary_count}, legacy_variants_hit={legacy_variants_hit}, "
f"legacy_merged={legacy_records_merged}, total={len(merged)}"
)
return merged, legacy_hit
def _format_command_error(message: str) -> str:
return f"❌ {message}"
def _build_mem_root_help_text() -> str:
lines = [
"📚 mem 命令帮助",
"",
"基础用法:",
"- mem.list [layer=conversation|persona|global] [tags=TAG1,TAG2]",
"- mem.search <query> [layer=xxx] [limit=5]",
"- mem.add <文本> [layer=xxx] [tag=TYPE] [expires=ISO8601]",
"- mem.delete <memory_id>",
"- mem.edit <memory_id> <new_text>",
"- mem.history <memory_id>",
"",
"可视化与管理:",
"- mem.visual [layer=xxx] [tags=TAG1,TAG2] [limit=60]",
"- mem.panel [layer=xxx] [tags=TAG1,TAG2] [limit=80] [ops=true|false]",
"",
"维护操作(高风险):",
"- mem.cleanup",
"- mem.clear [layer=conversation|persona|global]",
"",
"作用域参数(可选):",
"- user=xxx agent=xxx run=xxx",
"",
"提示:mem 命令组仅管理员可调用。",
]
return "\n".join(lines)
def _parse_time_value(value: Any) -> Optional[datetime]:
if isinstance(value, datetime):
parsed = value
elif isinstance(value, str):
raw = value.strip()
if not raw:
return None
if raw.endswith("Z"):
raw = raw[:-1] + "+00:00"
try:
parsed = datetime.fromisoformat(raw)
except (TypeError, ValueError):
return None
else:
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
def _extract_item_time(item: Dict[str, Any]) -> Optional[datetime]:
raw_metadata = item.get("metadata")
metadata: Dict[str, Any] = raw_metadata if isinstance(raw_metadata, dict) else {}
candidates = [
item.get("updated_at"),
item.get("created_at"),
item.get("event_at"),
metadata.get("updated_at"),
metadata.get("created_at"),
metadata.get("event_at"),
]
for value in candidates:
parsed = _parse_time_value(value)
if parsed is not None:
return parsed
return None
def _render_distribution(counter: Counter, title: str, max_items: int = 8) -> List[str]:
if not counter:
return [f"{title}: (无数据)"]
top_items = counter.most_common(max_items)
max_count = top_items[0][1] if top_items else 1
width = 18
lines = [title]
for name, count in top_items:
bar_len = max(1, round((count / max_count) * width)) if count > 0 else 0
bar = "█" * bar_len
lines.append(f"- {name}: {bar} {count}")
return lines
def _summarize_memory_visual(
merged_results: List[Dict[str, Any]], *, limit: int
) -> str:
if not merged_results:
return "(无结果)"
rows_with_time: List[Tuple[Optional[datetime], Dict[str, Any]]] = [
(_extract_item_time(item), item) for item in merged_results
]
rows_with_time.sort(
key=lambda row: row[0] or datetime(1970, 1, 1, tzinfo=timezone.utc),
reverse=True,
)
selected_rows = rows_with_time[:limit]
selected = [item for _, item in selected_rows]
layer_counter: Counter = Counter()
tag_counter: Counter = Counter()
importance_counter: Counter = Counter()
timeline_lines: List[str] = []
relation_lines: List[str] = []
id_to_text: Dict[str, str] = {}
for _, item in selected_rows:
memory_id = str(item.get("id") or item.get("memory_id") or "")
memory_text = _extract_memory_text(item).replace("\n", " ").strip()
if memory_id:
id_to_text[memory_id] = memory_text[:22]
for dt_value, item in selected_rows:
layer = str(item.get("layer") or item.get("scope_level") or "unknown")
layer_counter[layer] += 1
raw_metadata = item.get("metadata")
metadata: Dict[str, Any] = (
raw_metadata if isinstance(raw_metadata, dict) else {}
)
tag = metadata.get("TYPE")
if isinstance(tag, str) and tag.strip():
tag_counter[tag.strip()] += 1
elif isinstance(tag, list):
for tag_item in tag:
if isinstance(tag_item, str) and tag_item.strip():
tag_counter[tag_item.strip()] += 1
else:
tag_counter["(未标注)"] += 1
importance = _normalize_importance_value(metadata.get("importance"), default=5)
importance_counter[f"P{importance}"] += 1
if len(timeline_lines) < 12:
memory_id = str(item.get("id") or item.get("memory_id") or "未知ID")
text = _extract_memory_text(item).replace("\n", " ").strip()[:40]
dt_text = dt_value.strftime("%m-%d %H:%M") if dt_value else "--"
timeline_lines.append(f"- {dt_text} [{layer}] {memory_id}: {text}")
if len(relation_lines) < 10:
source_id = str(item.get("id") or item.get("memory_id") or "")
if not source_id:
continue
related_ids = (
metadata.get("related_memory_ids") or metadata.get("links") or []
)
if isinstance(related_ids, str):
related_ids = [related_ids]
if isinstance(related_ids, list):
for rid in related_ids:
if not isinstance(rid, str) or not rid.strip():
continue
target_id = rid.strip()
source_text = id_to_text.get(source_id, "")
target_text = id_to_text.get(target_id, "")
relation_lines.append(
f"- {source_id}({source_text}) -> {target_id}({target_text})"
)
if len(relation_lines) >= 10:
break
lines: List[str] = []
lines.append(f"📊 记忆可视化总览(样本 {len(selected)}/{len(merged_results)})")
lines.extend(_render_distribution(layer_counter, "\n🧱 层级分布"))
lines.extend(_render_distribution(tag_counter, "\n🏷️ 类型分布"))
lines.extend(_render_distribution(importance_counter, "\n⭐ 重要性分布"))
lines.append("\n🕒 最近时间线")
lines.extend(timeline_lines or ["- (无时间数据)"])
lines.append("\n🕸️ 关系视图")
lines.extend(
relation_lines
or [
"- (未检测到 related_memory_ids/links 关系,可先通过 metadata 写入关系字段)"
]
)
return "\n".join(lines)
def _summarize_memory_management(
merged_results: List[Dict[str, Any]], *, limit: int, include_ops: bool
) -> str:
if not merged_results:
return "📋 记忆管理面板\n(无结果)"
rows_with_time: List[Tuple[Optional[datetime], Dict[str, Any]]] = [
(_extract_item_time(item), item) for item in merged_results
]
rows_with_time.sort(
key=lambda row: row[0] or datetime(1970, 1, 1, tzinfo=timezone.utc),
reverse=True,
)
selected_rows = rows_with_time[:limit]
selected = [item for _, item in selected_rows]
layer_counter: Counter = Counter()
type_counter: Counter = Counter()
importance_counter: Counter = Counter()
now = datetime.now(timezone.utc)
expiring_7d = 0
expired = 0
no_expire = 0
for _, item in selected_rows:
layer = str(item.get("layer") or item.get("scope_level") or "unknown")
layer_counter[layer] += 1
raw_metadata = item.get("metadata")
metadata: Dict[str, Any] = (
raw_metadata if isinstance(raw_metadata, dict) else {}
)
tag = metadata.get("TYPE")
if isinstance(tag, str) and tag.strip():
type_counter[tag.strip()] += 1
elif isinstance(tag, list):
for tag_item in tag:
if isinstance(tag_item, str) and tag_item.strip():
type_counter[tag_item.strip()] += 1
else:
type_counter["(未标注)"] += 1
importance = _normalize_importance_value(metadata.get("importance"), default=5)
importance_counter[f"P{importance}"] += 1
expiration_dt = _parse_expiration_datetime(metadata.get("expiration_date"))
if expiration_dt is None:
no_expire += 1
elif expiration_dt < now:
expired += 1
elif (expiration_dt - now).total_seconds() <= 7 * 24 * 3600:
expiring_7d += 1
ranked = list(selected)
ranked.sort(
key=lambda item: _get_combined_score(item, importance_weight=0.45), reverse=True
)
top_rows = ranked[:8]
lines: List[str] = []
lines.append(f"📋 记忆管理面板(样本 {len(selected)}/{len(merged_results)})")
lines.extend(_render_distribution(layer_counter, "\n🧱 层级分布"))
lines.extend(_render_distribution(type_counter, "\n🏷️ 类型分布"))
lines.extend(_render_distribution(importance_counter, "\n⭐ 重要性分布"))
lines.append("\n⏳ 过期健康度(基于采样)")
lines.append(f"- 7天内即将过期: {expiring_7d}")
lines.append(f"- 已过期(待清理): {expired}")
lines.append(f"- 无过期时间: {no_expire}")
lines.append("\n🧭 建议优先维护(按综合分排序)")
if top_rows:
for item in top_rows:
memory_id = str(item.get("id") or item.get("memory_id") or "未知ID")
raw_metadata = item.get("metadata")
top_metadata: Dict[str, Any] = (
raw_metadata if isinstance(raw_metadata, dict) else {}
)
layer = str(item.get("layer") or item.get("scope_level") or "unknown")
tag = top_metadata.get("TYPE")
importance = _normalize_importance_value(
top_metadata.get("importance"), default=5
)
expires = top_metadata.get("expiration_date") or "-"
text = _extract_memory_text(item).replace("\n", " ").strip()[:42]
if isinstance(tag, str):
tag_label = tag if tag.strip() else "(未标注)"
elif isinstance(tag, list):
safe_tags = [str(t).strip() for t in tag if str(t).strip()]
tag_label = ",".join(safe_tags[:2]) if safe_tags else "(未标注)"
else:
tag_label = "(未标注)"
lines.append(