lingshu-skill 5.24.0 → 5.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +1 -1
  3. package/SKILL-lite.md +1 -1
  4. package/SKILL-tiny.md +1 -1
  5. package/SKILL.md +2 -1
  6. package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +12 -0
  7. package/package.json +1 -1
  8. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +14 -13
  9. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +44 -0
  10. package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
  11. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
  12. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +2 -1
  14. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +43 -0
  15. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +74 -0
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +167 -0
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +221 -219
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +10 -3
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +470 -460
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +14 -0
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +29 -1
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +12 -0
  23. package/scripts/check_version.py +16 -0
  24. package/scripts/cli.py +43 -0
  25. package/scripts/core.py +74 -0
  26. package/scripts/coverage_report.py +167 -0
  27. package/scripts/mem_dialogue.py +221 -219
  28. package/scripts/memory.py +10 -3
  29. package/scripts/panels.py +470 -460
  30. package/scripts/release.py +14 -0
  31. package/scripts/safety.py +29 -1
  32. package/scripts/safety_net.py +12 -0
@@ -21,222 +21,224 @@ def _mem():
21
21
  return memory
22
22
 
23
23
 
24
- _DIALOGUE_EXTS = (".jsonl", ".md", ".txt")
25
- _DIALOGUE_MAX_DEPTH = 2
26
- _DIALOGUE_READ_CAP = 8 * 1024 * 1024 # 单次最多读 8MB;大文件按完整行分批推进偏移
27
-
28
-
29
- def _dialogue_offsets_path() -> Path:
30
- return core.HOME / "dialogue_offsets.json"
31
-
32
-
33
- def _dialogue_load_offsets() -> dict:
34
- p = _dialogue_offsets_path()
35
- if not p.exists():
36
- return {}
37
- try:
38
- d = json.loads(p.read_text(encoding="utf-8-sig"))
39
- return d if isinstance(d, dict) else {}
40
- except Exception:
41
- return {}
42
-
43
-
44
- def _dialogue_decode(blob: bytes, source: str) -> str:
45
- """BOM → UTF-8 严格解码 → GB18030 回退;实际编码留日志,不乱码静默入库。"""
46
- if not blob:
47
- return ""
48
- encoding = "utf-8"
49
- if blob.startswith(b"\xef\xbb\xbf"):
50
- encoding = "utf-8-sig"
51
- elif blob.startswith((b"\xff\xfe", b"\xfe\xff")):
52
- encoding = "utf-16"
53
- else:
54
- try:
55
- return blob.decode("utf-8")
56
- except UnicodeDecodeError:
57
- encoding = "gb18030"
58
- try:
59
- text = blob.decode(encoding)
60
- except UnicodeDecodeError:
61
- text = blob.decode(encoding, errors="replace")
62
- core.log_event("dialogue", f"对话摄取解码({source}):{encoding}", level="info")
63
- return text
64
-
65
-
66
- def _dialogue_turns_from_text(text: str, ext: str) -> list:
67
- """把导出片段解析成 [(role, text)];role ∈ user / ai / other。"""
68
- turns = []
69
- for ln in text.splitlines():
70
- s = ln.strip()
71
- if not s:
72
- continue
73
- if ext == ".jsonl":
74
- try:
75
- d = json.loads(s)
76
- except Exception:
77
- continue
78
- if isinstance(d, str):
79
- turns.append(("other", d))
80
- continue
81
- if not isinstance(d, dict):
82
- continue
83
- txt = d.get("content") or d.get("text") or d.get("message") or ""
84
- if isinstance(txt, list): # OpenAI 风格 content parts
85
- txt = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in txt)
86
- txt = str(txt).strip()
87
- if not txt:
88
- continue
89
- raw_role = str(d.get("role") or d.get("sender") or d.get("from") or "").lower()
90
- if raw_role in ("user", "human", "me", "我", "用户"):
91
- role = "user"
92
- elif raw_role in ("assistant", "ai", "bot", "model", "灵枢", "助手"):
93
- role = "ai"
94
- else:
95
- role = "other"
96
- turns.append((role, txt))
97
- else:
98
- m = re.match(r"^\s*(user|human|assistant|ai|bot|model|我|用户|助手|灵枢)\s*[::]\s*(.+)$",
99
- s, re.I)
100
- if m:
101
- who = m.group(1).lower()
102
- role = "user" if who in ("user", "human", "我", "用户") else "ai"
103
- turns.append((role, m.group(2).strip()))
104
- else:
105
- turns.append(("other", s))
106
- return turns
107
-
108
-
109
- def _dialogue_chunks(turns: list, max_chars: int = 700) -> list:
110
- """相邻轮次拼成块(用户/我 前缀);块满就切,一块 = 一条 episode 记忆。"""
111
- chunks, buf, size = [], [], 0
112
- for role, text in turns:
113
- if len(text) < 2:
114
- continue
115
- prefix = "用户: " if role == "user" else ("我: " if role == "ai" else "")
116
- piece = prefix + text
117
- if buf and size + len(piece) > max_chars:
118
- chunks.append("\n".join(buf))
119
- buf, size = [], 0
120
- buf.append(piece)
121
- size += len(piece) + 1
122
- if buf:
123
- chunks.append("\n".join(buf))
124
- return [c for c in chunks if len(c) >= 8]
125
-
126
-
127
- def _dialogue_files(sources: list, max_files: int) -> list:
128
- """收集候选文件(最多 max_files 个,按 mtime 新→旧)。"""
129
- found = []
130
- for src in sources:
131
- root = Path(str(src)).expanduser()
132
- if not root.is_dir():
133
- continue
134
- base_depth = len(root.parts)
135
- for f in root.rglob("*"):
136
- try:
137
- if len(f.parts) - base_depth > _DIALOGUE_MAX_DEPTH:
138
- continue
139
- if f.is_file() and f.suffix.lower() in _DIALOGUE_EXTS:
140
- found.append(f)
141
- except OSError:
142
- continue
143
- found.sort(key=lambda f: -(f.stat().st_mtime if f.exists() else 0))
144
- return found[:max_files]
145
-
146
-
147
- def ingest_dialogues(paths=None, limit: int | None = None, dry_run: bool = False) -> dict:
148
- """增量摄取其他会话的对话导出 → episode 记忆。
149
-
150
- 参数:
151
- paths 额外/替代的源目录(缺省用 config.dialogue_sources)
152
- limit 本次最多处理多少个文件(缺省 config.dialogue_ingest_max_files)
153
- dry_run 只统计不写库(不推进偏移、不写记忆)
154
- 返回:{enabled, files, scanned, imported, skipped, chars, dry_run}
155
- """
156
- cfg = load_config()
157
- if not cfg.get("dialogue_ingest"):
158
- return {"ok": True, "enabled": False, "files": 0, "scanned": 0,
159
- "imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
160
- "reason": "未开启:config dialogue_ingest=false"}
161
- sources = [str(x) for x in (paths or cfg.get("dialogue_sources") or []) if str(x).strip()]
162
- if not sources:
163
- return {"ok": True, "enabled": True, "files": 0, "scanned": 0,
164
- "imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
165
- "reason": "没有配置 dialogue_sources 目录"}
166
- max_files = max(1, min(int(limit or cfg.get("dialogue_ingest_max_files") or 50), 500))
167
- max_chars = max(200, min(int(cfg.get("dialogue_ingest_max_chars") or 700), 2000))
168
- imported, skipped, chars, touched = 0, 0, 0, 0
169
- # offsets 既记读取位置,也记已导入块哈希:去重不再全量扫记忆库;
170
- # 整个读偏移→写记忆→存偏移过程持同一把锁,避免两个进程重复导入。
171
- with core._locked(_dialogue_offsets_path()):
172
- files = _dialogue_files(sources, max_files)
173
- offsets = _dialogue_load_offsets()
174
- known = {h for entry in offsets.values() if isinstance(entry, dict)
175
- for h in (entry.get("chunk_hashes") or [])}
176
- for f in files:
177
- key = str(f.resolve())
178
- try:
179
- st = f.stat()
180
- except OSError:
181
- continue
182
- entry = offsets.get(key) or {}
183
- # 用 offset==size 判断"已读干净":尾部半行没读完时不跳过,
184
- # 下次等它补上换行再继续(否则会永久漏掉最后一条)。
185
- if entry.get("offset") == st.st_size and entry.get("mtime") == st.st_mtime:
186
- continue # 没变过:完全不读
187
- start = int(entry.get("offset") or 0)
188
- if st.st_size < start:
189
- start = 0 # 文件被截断/重写:从头再来(块哈希去重兜底)
190
- remaining = max(0, st.st_size - start)
191
- try:
192
- with open(f, "rb") as fh:
193
- fh.seek(start)
194
- blob = fh.read(min(_DIALOGUE_READ_CAP, remaining))
195
- except OSError:
196
- continue
197
- if remaining > _DIALOGUE_READ_CAP:
198
- core.log_event("dialogue", f"对话摄取分段读取({f.name}):"
199
- f"偏移 {start},本次 {len(blob)} 字节,剩余下次继续",
200
- level="info")
201
- # 偏移永远落在完整行边界:尾部半行(正在写/无换行结尾)留到下次,
202
- # 否则续读时会把一条完整的新记录误当成"残片"丢掉。
203
- if blob and not blob.endswith(b"\n"):
204
- cut = blob.rfind(b"\n")
205
- if cut < 0:
206
- continue
207
- blob = blob[:cut + 1]
208
- text = _dialogue_decode(blob, f.name)
209
- turns = _dialogue_turns_from_text(text, f.suffix.lower())
210
- file_hashes = list(entry.get("chunk_hashes") or [])
211
- for chunk in _dialogue_chunks(turns, max_chars):
212
- digest = hashlib.sha256(chunk.strip().encode("utf-8")).hexdigest()
213
- if digest in known:
214
- skipped += 1
215
- continue
216
- if not dry_run:
217
- try:
218
- _mem().remember(chunk, kind="episode", importance=0.45,
219
- tags=["对话摄取", f.stem], source="dialogue",
220
- channel=f"dialogue:{f.stem}")
221
- except Exception as exc:
222
- core.log_event("dialogue", f"对话摄取写入失败({f.name}):{exc}", level="warn")
223
- continue
224
- known.add(digest)
225
- file_hashes.append(digest)
226
- imported += 1
227
- chars += len(chunk)
228
- if not dry_run:
229
- # offset 只推进到最后一个完整行末尾;尾部半行等下次补全
230
- offsets[key] = {"offset": start + len(blob), "size": st.st_size,
231
- "mtime": st.st_mtime, "ts": now_ts(),
232
- "chunk_hashes": file_hashes}
233
- touched += 1
234
- if not dry_run and touched:
235
- try:
236
- core.atomic_json(_dialogue_offsets_path(), offsets)
237
- except Exception as exc:
238
- core.log_event("dialogue", f"对话摄取偏移保存失败:{exc}", level="warn")
239
- return {"ok": True, "enabled": True, "files": len(files), "scanned": len(files),
240
- "imported": imported, "skipped": skipped, "chars": chars,
241
- "dry_run": dry_run, "sources": sources}
242
-
24
+ _DIALOGUE_EXTS = (".jsonl", ".md", ".txt")
25
+ _DIALOGUE_MAX_DEPTH = 2
26
+ _DIALOGUE_READ_CAP = 8 * 1024 * 1024 # 单次最多读 8MB;大文件按完整行分批推进偏移
27
+
28
+
29
+ def _dialogue_offsets_path() -> Path:
30
+ return core.HOME / "dialogue_offsets.json"
31
+
32
+
33
+ def _dialogue_load_offsets() -> dict:
34
+ p = _dialogue_offsets_path()
35
+ if not p.exists():
36
+ return {}
37
+ try:
38
+ d = json.loads(p.read_text(encoding="utf-8-sig"))
39
+ return d if isinstance(d, dict) else {}
40
+ except Exception:
41
+ return {}
42
+
43
+
44
+ def _dialogue_decode(blob: bytes, source: str) -> str:
45
+ """BOM → UTF-8 严格解码 → GB18030 回退;实际编码留日志,不乱码静默入库。"""
46
+ if not blob:
47
+ return ""
48
+ encoding = "utf-8"
49
+ if blob.startswith(b"\xef\xbb\xbf"):
50
+ encoding = "utf-8-sig"
51
+ elif blob.startswith((b"\xff\xfe", b"\xfe\xff")):
52
+ encoding = "utf-16"
53
+ else:
54
+ try:
55
+ return blob.decode("utf-8")
56
+ except UnicodeDecodeError:
57
+ encoding = "gb18030"
58
+ try:
59
+ text = blob.decode(encoding)
60
+ except UnicodeDecodeError:
61
+ text = blob.decode(encoding, errors="replace")
62
+ core.log_event("dialogue", f"对话摄取解码({source}):{encoding}", level="info")
63
+ return text
64
+
65
+
66
+ def _dialogue_turns_from_text(text: str, ext: str) -> list:
67
+ """把导出片段解析成 [(role, text)];role ∈ user / ai / other。"""
68
+ turns = []
69
+ for ln in text.splitlines():
70
+ s = ln.strip()
71
+ if not s:
72
+ continue
73
+ if ext == ".jsonl":
74
+ try:
75
+ d = json.loads(s)
76
+ except Exception:
77
+ continue
78
+ if isinstance(d, str):
79
+ turns.append(("other", d))
80
+ continue
81
+ if not isinstance(d, dict):
82
+ continue
83
+ txt = d.get("content") or d.get("text") or d.get("message") or ""
84
+ if isinstance(txt, list): # OpenAI 风格 content parts
85
+ txt = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in txt)
86
+ txt = str(txt).strip()
87
+ if not txt:
88
+ continue
89
+ raw_role = str(d.get("role") or d.get("sender") or d.get("from") or "").lower()
90
+ if raw_role in ("user", "human", "me", "我", "用户"):
91
+ role = "user"
92
+ elif raw_role in ("assistant", "ai", "bot", "model", "灵枢", "助手"):
93
+ role = "ai"
94
+ else:
95
+ role = "other"
96
+ turns.append((role, txt))
97
+ else:
98
+ m = re.match(r"^\s*(user|human|assistant|ai|bot|model|我|用户|助手|灵枢)\s*[::]\s*(.+)$",
99
+ s, re.I)
100
+ if m:
101
+ who = m.group(1).lower()
102
+ role = "user" if who in ("user", "human", "我", "用户") else "ai"
103
+ turns.append((role, m.group(2).strip()))
104
+ else:
105
+ turns.append(("other", s))
106
+ return turns
107
+
108
+
109
+ def _dialogue_chunks(turns: list, max_chars: int = 700) -> list:
110
+ """相邻轮次拼成块(用户/我 前缀);块满就切,一块 = 一条 episode 记忆。"""
111
+ chunks, buf, size = [], [], 0
112
+ for role, text in turns:
113
+ if len(text) < 2:
114
+ continue
115
+ prefix = "用户: " if role == "user" else ("我: " if role == "ai" else "")
116
+ piece = prefix + text
117
+ if buf and size + len(piece) > max_chars:
118
+ chunks.append("\n".join(buf))
119
+ buf, size = [], 0
120
+ buf.append(piece)
121
+ size += len(piece) + 1
122
+ if buf:
123
+ chunks.append("\n".join(buf))
124
+ return [c for c in chunks if len(c) >= 8]
125
+
126
+
127
+ def _dialogue_files(sources: list, max_files: int) -> list:
128
+ """收集候选文件(最多 max_files 个,按 mtime 新→旧)。"""
129
+ found = []
130
+ for src in sources:
131
+ root = Path(str(src)).expanduser()
132
+ if not root.is_dir():
133
+ continue
134
+ base_depth = len(root.parts)
135
+ for f in root.rglob("*"):
136
+ try:
137
+ if len(f.parts) - base_depth > _DIALOGUE_MAX_DEPTH:
138
+ continue
139
+ if f.is_file() and f.suffix.lower() in _DIALOGUE_EXTS:
140
+ found.append(f)
141
+ except OSError:
142
+ continue
143
+ found.sort(key=lambda f: -(f.stat().st_mtime if f.exists() else 0))
144
+ return found[:max_files]
145
+
146
+
147
+ def ingest_dialogues(paths=None, limit: int | None = None, dry_run: bool = False) -> dict:
148
+ """增量摄取其他会话的对话导出 → episode 记忆。
149
+
150
+ 参数:
151
+ paths 额外/替代的源目录(缺省用 config.dialogue_sources)
152
+ limit 本次最多处理多少个文件(缺省 config.dialogue_ingest_max_files)
153
+ dry_run 只统计不写库(不推进偏移、不写记忆)
154
+ 返回:{enabled, files, scanned, imported, skipped, chars, dry_run}
155
+ """
156
+ cfg = load_config()
157
+ if not cfg.get("dialogue_ingest"):
158
+ return {"ok": True, "enabled": False, "files": 0, "scanned": 0,
159
+ "imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
160
+ "reason": "未开启:config dialogue_ingest=false"}
161
+ sources = [str(x) for x in (paths or cfg.get("dialogue_sources") or []) if str(x).strip()]
162
+ if not sources:
163
+ return {"ok": True, "enabled": True, "files": 0, "scanned": 0,
164
+ "imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
165
+ "reason": "没有配置 dialogue_sources 目录"}
166
+ max_files = max(1, min(int(limit or cfg.get("dialogue_ingest_max_files") or 50), 500))
167
+ max_chars = max(200, min(int(cfg.get("dialogue_ingest_max_chars") or 700), 2000))
168
+ imported, skipped, chars, touched = 0, 0, 0, 0
169
+ # offsets 既记读取位置,也记已导入块哈希:去重不再全量扫记忆库;
170
+ # 整个读偏移→写记忆→存偏移过程持同一把锁,避免两个进程重复导入。
171
+ with core._locked(_dialogue_offsets_path()):
172
+ files = _dialogue_files(sources, max_files)
173
+ offsets = _dialogue_load_offsets()
174
+ known = {h for entry in offsets.values() if isinstance(entry, dict)
175
+ for h in (entry.get("chunk_hashes") or [])}
176
+ for f in files:
177
+ key = str(f.resolve())
178
+ try:
179
+ st = f.stat()
180
+ except OSError:
181
+ continue
182
+ entry = offsets.get(key) or {}
183
+ # 用 offset==size 判断"已读干净":尾部半行没读完时不跳过,
184
+ # 下次等它补上换行再继续(否则会永久漏掉最后一条)。
185
+ if entry.get("offset") == st.st_size and entry.get("mtime") == st.st_mtime:
186
+ continue # 没变过:完全不读
187
+ start = int(entry.get("offset") or 0)
188
+ if st.st_size < start:
189
+ start = 0 # 文件被截断/重写:从头再来(块哈希去重兜底)
190
+ remaining = max(0, st.st_size - start)
191
+ try:
192
+ with open(f, "rb") as fh:
193
+ fh.seek(start)
194
+ blob = fh.read(min(_DIALOGUE_READ_CAP, remaining))
195
+ except OSError:
196
+ continue
197
+ if remaining > _DIALOGUE_READ_CAP:
198
+ core.log_event("dialogue", f"对话摄取分段读取({f.name}):"
199
+ f"偏移 {start},本次 {len(blob)} 字节,剩余下次继续",
200
+ level="info")
201
+ # 偏移永远落在完整行边界:尾部半行(正在写/无换行结尾)留到下次,
202
+ # 否则续读时会把一条完整的新记录误当成"残片"丢掉。
203
+ if blob and not blob.endswith(b"\n"):
204
+ cut = blob.rfind(b"\n")
205
+ if cut < 0:
206
+ continue
207
+ blob = blob[:cut + 1]
208
+ text = _dialogue_decode(blob, f.name)
209
+ turns = _dialogue_turns_from_text(text, f.suffix.lower())
210
+ file_hashes = list(entry.get("chunk_hashes") or [])
211
+ for chunk in _dialogue_chunks(turns, max_chars):
212
+ digest = hashlib.sha256(chunk.strip().encode("utf-8")).hexdigest()
213
+ if digest in known:
214
+ skipped += 1
215
+ continue
216
+ if not dry_run:
217
+ try:
218
+ _mem().remember(chunk, kind="episode", importance=0.45,
219
+ tags=["对话摄取", f.stem], source="dialogue",
220
+ channel=f"dialogue:{f.stem}")
221
+ except Exception as exc:
222
+ core.log_event("dialogue", f"对话摄取写入失败({f.name}):{exc}", level="warn")
223
+ # 这条吞掉等于"对话没进记忆"——用户以为记下了,其实没有
224
+ core.swallow("dialogue.ingest", exc, where="mem_dialogue")
225
+ continue
226
+ known.add(digest)
227
+ file_hashes.append(digest)
228
+ imported += 1
229
+ chars += len(chunk)
230
+ if not dry_run:
231
+ # offset 只推进到最后一个完整行末尾;尾部半行等下次补全
232
+ offsets[key] = {"offset": start + len(blob), "size": st.st_size,
233
+ "mtime": st.st_mtime, "ts": now_ts(),
234
+ "chunk_hashes": file_hashes}
235
+ touched += 1
236
+ if not dry_run and touched:
237
+ try:
238
+ core.atomic_json(_dialogue_offsets_path(), offsets)
239
+ except Exception as exc:
240
+ core.log_event("dialogue", f"对话摄取偏移保存失败:{exc}", level="warn")
241
+ return {"ok": True, "enabled": True, "files": len(files), "scanned": len(files),
242
+ "imported": imported, "skipped": skipped, "chars": chars,
243
+ "dry_run": dry_run, "sources": sources}
244
+
@@ -2733,9 +2733,16 @@ def purge(memory_id: str, confirm_token: str) -> dict:
2733
2733
  """
2734
2734
  if READONLY:
2735
2735
  raise PermissionError("记忆库当前只读,无法物理删除。")
2736
- if not confirm_token or confirm_token != memory_id[:8]:
2737
- raise ValueError(
2738
- f"物理删除需显式确认:--confirm {memory_id[:8]}(传入的确认码不匹配)")
2736
+ # 统一走 safety 的确认原语(原先这里自己写了一段比对,文案与 safety 那套不一致,
2737
+ # 也让"破坏性确认"散落在两个模块里)。
2738
+ try:
2739
+ import safety as _safety
2740
+ _safety.require_token("物理删除记忆", confirm_token, memory_id[:8],
2741
+ hint=f"--confirm {memory_id[:8]}")
2742
+ except ImportError: # safety 未部署时退回原判据,别把删除功能整体搞挂
2743
+ if not confirm_token or confirm_token != memory_id[:8]:
2744
+ raise ValueError(
2745
+ f"物理删除需显式确认:--confirm {memory_id[:8]}(传入的确认码不匹配)")
2739
2746
  cutoff = now_ts() - _PURGE_COOLDOWN_DAYS * DAY
2740
2747
  with _locked(HOME / "hippocampus.jsonl"):
2741
2748
  records = load_all()