lingshu-skill 5.64.0 → 5.66.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 (31) hide show
  1. package/CHANGELOG.md +25 -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 +1 -1
  6. package/manifest.json +26 -26
  7. package/package.json +1 -1
  8. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +15 -15
  9. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +25 -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 +1 -1
  14. package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +17 -3
  15. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +282 -259
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +215 -209
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_exchange.py +217 -171
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +219 -195
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +190 -181
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +11 -3
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +148 -123
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +131 -124
  23. package/scripts/checkpoint.py +17 -3
  24. package/scripts/mem_dialogue.py +282 -259
  25. package/scripts/mem_embed.py +215 -209
  26. package/scripts/mem_exchange.py +217 -171
  27. package/scripts/retriever.py +219 -195
  28. package/scripts/rss_ingest.py +190 -181
  29. package/scripts/session_rag.py +11 -3
  30. package/scripts/session_summary.py +148 -123
  31. package/scripts/web_research.py +131 -124
@@ -1,181 +1,190 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """RSS/Atom 摄入(§4 P2-1,窄口径版)。
4
-
5
- 范围(按待办建议收窄):**本地 RSS/Atom 文件** 或 **显式 URL 列表**,默认不自动跑。
6
- 不内置定时抓取、不做订阅管理界面——想自动化就把 `rss ingest --url-list` 挂到你自己的计划任务里。
7
-
8
- 设计约束:
9
- · 零依赖:`xml.etree` + `urllib`,够用;
10
- · 幂等:按条目的 link(没有则 title+published)做 sha1 存 `rss_seen.json`,重复摄入不重复记;
11
- · 可逆/可审计:每条记成 `kind=episode` 的记忆,带 `rss` 标签与来源链接;
12
- · 宽容:坏 XML、坏日期、断网都只跳过该条/该源,不抛。
13
-
14
- 用法:
15
- python scripts/brain.py rss ingest --file feed.xml
16
- python scripts/brain.py rss ingest --url-list urls.txt --limit 20
17
- python scripts/brain.py rss ingest --file feed.xml --dry-run
18
- """
19
- from __future__ import annotations
20
-
21
- import hashlib
22
- import json
23
- import re
24
- import time
25
- import urllib.request
26
- import xml.etree.ElementTree as ET
27
- from pathlib import Path
28
-
29
- import core
30
-
31
- SEEN = "rss_seen.json"
32
- MAX_KEEP_SEEN = 5000 # 只记最近这么多条 link 哈希,防无限增长
33
- DEFAULT_LIMIT = 20
34
-
35
-
36
- def _seen_path() -> Path:
37
- return Path(core.HOME) / SEEN
38
-
39
-
40
- def load_seen() -> list:
41
- try:
42
- p = _seen_path()
43
- if not p.is_file():
44
- return []
45
- d = json.loads(p.read_text(encoding="utf-8", errors="replace") or "[]")
46
- return d if isinstance(d, list) else []
47
- except Exception:
48
- return []
49
-
50
-
51
- def save_seen(items: list) -> None:
52
- try:
53
- if getattr(core, "READONLY", False):
54
- return
55
- with core._locked(core.HOME / SEEN):
56
- core.atomic_json(_seen_path(), items[-MAX_KEEP_SEEN:])
57
- except Exception:
58
- pass
59
-
60
-
61
- def _text(el) -> str:
62
- if el is None:
63
- return ""
64
- return re.sub(r"\s+", " ", "".join(el.itertext())).strip()
65
-
66
-
67
- def parse_feed(raw: bytes) -> list:
68
- """解析 RSS 2.0 / Atom。返回 [{title, link, summary, published}]。"""
69
- out = []
70
- try:
71
- root = ET.fromstring(raw)
72
- except Exception:
73
- return out
74
- # Atom: {http://www.w3.org/2005/Atom}entry
75
- ns_atom = "{http://www.w3.org/2005/Atom}"
76
- entries = root.findall(f".//{ns_atom}entry")
77
- if entries:
78
- for e in entries:
79
- link = ""
80
- for ln in e.findall(f"{ns_atom}link"):
81
- if ln.get("rel") in (None, "alternate") and ln.get("href"):
82
- link = ln.get("href")
83
- break
84
- # ⚠ 不能写 `e.find(summary) or e.find(content)`:ElementTree 里**空元素布尔值为 False**,
85
- # 一个没有子节点的 <summary> 会让 or 落到 content 上(实测 Atom 摘要因此变空)。
86
- _sum = e.find(f"{ns_atom}summary")
87
- if _sum is None:
88
- _sum = e.find(f"{ns_atom}content")
89
- _pub = e.find(f"{ns_atom}published")
90
- if _pub is None:
91
- _pub = e.find(f"{ns_atom}updated")
92
- out.append({
93
- "title": _text(e.find(f"{ns_atom}title")),
94
- "link": link,
95
- "summary": _text(_sum),
96
- "published": _text(_pub),
97
- })
98
- return out
99
- # RSS 2.0: channel/item
100
- for it in root.findall(".//item"):
101
- out.append({
102
- "title": _text(it.find("title")),
103
- "link": _text(it.find("link")),
104
- "summary": _text(it.find("description")),
105
- "published": _text(it.find("pubDate")),
106
- })
107
- return out
108
-
109
-
110
- def _key(it: dict) -> str:
111
- basis = (it.get("link") or "").strip() or (it.get("title", "") + "|" + it.get("published", ""))
112
- return hashlib.sha1(basis.encode("utf-8", "replace")).hexdigest()[:16]
113
-
114
-
115
- def _fetch(url: str, timeout: float = 15.0) -> bytes | None:
116
- try:
117
- req = urllib.request.Request(url, headers={"User-Agent": "lingshu-rss/1.0"})
118
- with urllib.request.urlopen(req, timeout=timeout) as r:
119
- return r.read()
120
- except Exception:
121
- return None
122
-
123
-
124
- def ingest(files=None, urls=None, limit: int = DEFAULT_LIMIT, dry_run: bool = False) -> dict:
125
- """从本地文件 / 显式 URL 摄入条目。返回 {sources, parsed, new, ingested, errors}。"""
126
- import memory # 延迟导入:只有真要写记忆时才需要
127
-
128
- files = list(files or [])
129
- urls = list(urls or [])
130
- seen = load_seen()
131
- seen_set = set(seen)
132
- stats = {"sources": 0, "parsed": 0, "new": 0, "ingested": 0, "errors": []}
133
-
134
- raws: list = []
135
- for f in files:
136
- try:
137
- raws.append(Path(f).read_bytes())
138
- stats["sources"] += 1
139
- except Exception as e: # noqa: BLE001
140
- stats["errors"].append(f"{f}: {e}")
141
- for u in urls:
142
- b = _fetch(u)
143
- if b is None:
144
- stats["errors"].append(f"{u}: 拉取失败")
145
- continue
146
- raws.append(b)
147
- stats["sources"] += 1
148
-
149
- for raw in raws:
150
- items = parse_feed(raw)
151
- stats["parsed"] += len(items)
152
- for it in items:
153
- if stats["new"] >= max(1, int(limit)):
154
- break
155
- k = _key(it)
156
- if k in seen_set:
157
- continue
158
- stats["new"] += 1
159
- if dry_run:
160
- continue
161
- title = (it.get("title") or "(无标题)")[:80]
162
- summary = (it.get("summary") or "")[:400]
163
- text = f"[RSS] {title}" + (f" —— {summary}" if summary else "")
164
- try:
165
- memory.remember(text, kind="episode", importance=0.4,
166
- tags=["rss"], source=(it.get("link") or "rss")[:200])
167
- stats["ingested"] += 1
168
- seen.append(k)
169
- except Exception as e: # noqa: BLE001
170
- stats["errors"].append(f"{title}: {e}")
171
- if not dry_run and seen:
172
- save_seen(seen)
173
- return stats
174
-
175
-
176
- def render(stats: dict) -> list[str]:
177
- lines = [f"来源 {stats['sources']} 个 · 解析 {stats['parsed']} 条 · "
178
- f"新条目 {stats['new']} · 已写入记忆 {stats['ingested']}"]
179
- for e in (stats.get("errors") or [])[:5]:
180
- lines.append(f" ⚠ {e}")
181
- return lines
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """RSS/Atom 摄入(§4 P2-1,窄口径版)。
4
+
5
+ 范围(按待办建议收窄):**本地 RSS/Atom 文件** 或 **显式 URL 列表**,默认不自动跑。
6
+ 不内置定时抓取、不做订阅管理界面——想自动化就把 `rss ingest --url-list` 挂到你自己的计划任务里。
7
+
8
+ 设计约束:
9
+ · 零依赖:`xml.etree` + `urllib`,够用;
10
+ · 幂等:按条目的 link(没有则 title+published)做 sha1 存 `rss_seen.json`,重复摄入不重复记;
11
+ · 可逆/可审计:每条记成 `kind=episode` 的记忆,带 `rss` 标签与来源链接;
12
+ · 宽容:坏 XML、坏日期、断网都只跳过该条/该源,不抛。
13
+
14
+ 用法:
15
+ python scripts/brain.py rss ingest --file feed.xml
16
+ python scripts/brain.py rss ingest --url-list urls.txt --limit 20
17
+ python scripts/brain.py rss ingest --file feed.xml --dry-run
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import re
24
+ import time
25
+ import urllib.request
26
+ import xml.etree.ElementTree as ET
27
+ from pathlib import Path
28
+
29
+ import core
30
+
31
+ SEEN = "rss_seen.json"
32
+ MAX_KEEP_SEEN = 5000 # 只记最近这么多条 link 哈希,防无限增长
33
+ DEFAULT_LIMIT = 20
34
+
35
+
36
+ def _seen_path() -> Path:
37
+ return Path(core.HOME) / SEEN
38
+
39
+
40
+ def load_seen() -> list:
41
+ try:
42
+ p = _seen_path()
43
+ if not p.is_file():
44
+ return []
45
+ d = json.loads(p.read_text(encoding="utf-8", errors="replace") or "[]")
46
+ return d if isinstance(d, list) else []
47
+ except Exception:
48
+ return []
49
+
50
+
51
+ def save_seen(items: list) -> bool:
52
+ """LS-045(v5.66):save_seen 失败返回 False,让调用方知道 seen 持久化失败!"""
53
+ try:
54
+ if getattr(core, "READONLY", False):
55
+ return True # 只读跳过不算失败
56
+ with core._locked(core.HOME / SEEN):
57
+ core.atomic_json(_seen_path(), items[-MAX_KEEP_SEEN:])
58
+ return True
59
+ except Exception as exc:
60
+ import core as _core
61
+ _core.log_event("rss", f"seen 持久化失败:{exc}(下轮可能重复摄入)", level="error")
62
+ return False
63
+
64
+
65
+ def _text(el) -> str:
66
+ if el is None:
67
+ return ""
68
+ return re.sub(r"\s+", " ", "".join(el.itertext())).strip()
69
+
70
+
71
+ def parse_feed(raw: bytes) -> list:
72
+ """解析 RSS 2.0 / Atom。返回 [{title, link, summary, published}]。"""
73
+ out = []
74
+ try:
75
+ root = ET.fromstring(raw)
76
+ except Exception:
77
+ return out
78
+ # Atom: {http://www.w3.org/2005/Atom}entry
79
+ ns_atom = "{http://www.w3.org/2005/Atom}"
80
+ entries = root.findall(f".//{ns_atom}entry")
81
+ if entries:
82
+ for e in entries:
83
+ link = ""
84
+ for ln in e.findall(f"{ns_atom}link"):
85
+ if ln.get("rel") in (None, "alternate") and ln.get("href"):
86
+ link = ln.get("href")
87
+ break
88
+ # ⚠ 不能写 `e.find(summary) or e.find(content)`:ElementTree 里**空元素布尔值为 False**,
89
+ # 一个没有子节点的 <summary> 会让 or 落到 content 上(实测 Atom 摘要因此变空)。
90
+ _sum = e.find(f"{ns_atom}summary")
91
+ if _sum is None:
92
+ _sum = e.find(f"{ns_atom}content")
93
+ _pub = e.find(f"{ns_atom}published")
94
+ if _pub is None:
95
+ _pub = e.find(f"{ns_atom}updated")
96
+ out.append({
97
+ "title": _text(e.find(f"{ns_atom}title")),
98
+ "link": link,
99
+ "summary": _text(_sum),
100
+ "published": _text(_pub),
101
+ })
102
+ return out
103
+ # RSS 2.0: channel/item
104
+ for it in root.findall(".//item"):
105
+ out.append({
106
+ "title": _text(it.find("title")),
107
+ "link": _text(it.find("link")),
108
+ "summary": _text(it.find("description")),
109
+ "published": _text(it.find("pubDate")),
110
+ })
111
+ return out
112
+
113
+
114
+ def _key(it: dict) -> str:
115
+ basis = (it.get("link") or "").strip() or (it.get("title", "") + "|" + it.get("published", ""))
116
+ return hashlib.sha1(basis.encode("utf-8", "replace")).hexdigest()[:16]
117
+
118
+
119
+ def _fetch(url: str, timeout: float = 15.0) -> bytes | None:
120
+ try:
121
+ req = urllib.request.Request(url, headers={"User-Agent": "lingshu-rss/1.0"})
122
+ with urllib.request.urlopen(req, timeout=timeout) as r:
123
+ return r.read()
124
+ except Exception:
125
+ return None
126
+
127
+
128
+ def ingest(files=None, urls=None, limit: int = DEFAULT_LIMIT, dry_run: bool = False) -> dict:
129
+ """从本地文件 / 显式 URL 摄入条目。返回 {sources, parsed, new, ingested, errors}。"""
130
+ import memory # 延迟导入:只有真要写记忆时才需要
131
+
132
+ files = list(files or [])
133
+ urls = list(urls or [])
134
+ seen = load_seen()
135
+ seen_set = set(seen)
136
+ stats = {"sources": 0, "parsed": 0, "new": 0, "ingested": 0, "errors": []}
137
+
138
+ raws: list = []
139
+ for f in files:
140
+ try:
141
+ raws.append(Path(f).read_bytes())
142
+ stats["sources"] += 1
143
+ except Exception as e: # noqa: BLE001
144
+ stats["errors"].append(f"{f}: {e}")
145
+ for u in urls:
146
+ b = _fetch(u)
147
+ if b is None:
148
+ stats["errors"].append(f"{u}: 拉取失败")
149
+ continue
150
+ raws.append(b)
151
+ stats["sources"] += 1
152
+
153
+ # LS-044/053(v5.66):同批 link 去重 + 按成功摄入数计算 limit
154
+ batch_seen = set() # 本批已处理的 key(跨文件去重)
155
+ for raw in raws:
156
+ items = parse_feed(raw)
157
+ stats["parsed"] += len(items)
158
+ for it in items:
159
+ if stats["ingested"] >= max(1, int(limit)):
160
+ break # LS-053: 按成功摄入数计算 limit(首条失败不阻止后续健康条目)
161
+ k = _key(it)
162
+ if k in seen_set or k in batch_seen:
163
+ continue # LS-044: 同批同 link 只写一条
164
+ stats["new"] += 1
165
+ if dry_run:
166
+ continue
167
+ title = (it.get("title") or "(无标题)")[:80]
168
+ summary = (it.get("summary") or "")[:400]
169
+ text = f"[RSS] {title}" + (f" —— {summary}" if summary else "")
170
+ try:
171
+ memory.remember(text, kind="episode", importance=0.4,
172
+ tags=["rss"], source=(it.get("link") or "rss")[:200])
173
+ stats["ingested"] += 1
174
+ seen.append(k)
175
+ batch_seen.add(k)
176
+ except Exception as e: # noqa: BLE001
177
+ stats["errors"].append(f"{title}: {e}")
178
+ if not dry_run and seen:
179
+ save_ok = save_seen(seen)
180
+ if not save_ok:
181
+ stats["errors"].append("seen 持久化失败(下轮可能重复摄入)")
182
+ return stats
183
+
184
+
185
+ def render(stats: dict) -> list[str]:
186
+ lines = [f"来源 {stats['sources']} 个 · 解析 {stats['parsed']} 条 · "
187
+ f"新条目 {stats['new']} · 已写入记忆 {stats['ingested']}"]
188
+ for e in (stats.get("errors") or [])[:5]:
189
+ lines.append(f" ⚠ {e}")
190
+ return lines
@@ -66,8 +66,15 @@ def init_db(path=None) -> dict:
66
66
  return {"ok": True, "path": str(path or db_path()), "messages": rows}
67
67
 
68
68
 
69
- def _msg_id(session: str, role: str, ts: float, text: str) -> str:
70
- raw = f"{session}|{role}|{ts}|{text}".encode("utf-8")
69
+ def _msg_id(session: str, role: str, ts: float, text: str,
70
+ platform: str = "", workspace: str = "") -> str:
71
+ """LS-034(v5.65):将会话作用域纳入消息主键!
72
+
73
+ 旧主键只含 session|role|ts|text,同一消息在不同 platform/workspace 下
74
+ 会因哈希一致被 IntegrityError 误判为"重复"而跳过(数据丢失)。
75
+ 现将 platform 和 workspace 一并纳入主键,验证相同消息可分别存在于两个作用域。
76
+ """
77
+ raw = f"{session}|{platform}|{workspace}|{role}|{ts}|{text}".encode("utf-8")
71
78
  return "sr_" + hashlib.sha256(raw).hexdigest()[:24]
72
79
 
73
80
 
@@ -89,7 +96,8 @@ def ingest_messages(rows, *, session: str = "default", platform: str = "",
89
96
  continue
90
97
  role = str(r.get("role") or "other").lower()
91
98
  ts = float(r.get("ts") or r.get("created") or 0)
92
- mid = _msg_id(session, role, ts, text)
99
+ # LS-034(v5.65):主键纳入 platform 和 workspace 作用域
100
+ mid = _msg_id(session, role, ts, text, platform=platform, workspace=workspace)
93
101
  try:
94
102
  conn.execute(
95
103
  "INSERT INTO messages(id, session, platform, workspace, role, ts, text)"