lingshu-skill 5.65.0 → 5.67.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 (34) hide show
  1. package/CHANGELOG.md +34 -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/cordis-plugin/lingshu-guard/plugin.js +6 -1
  7. package/manifest.json +30 -30
  8. package/package.json +1 -1
  9. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +15 -15
  10. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +34 -0
  11. package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
  12. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
  14. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
  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/panel_cloud.py +651 -627
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +32 -13
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +610 -602
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +219 -195
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +190 -181
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +148 -123
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +131 -124
  25. package/scripts/mem_dialogue.py +282 -259
  26. package/scripts/mem_embed.py +215 -209
  27. package/scripts/mem_exchange.py +217 -171
  28. package/scripts/panel_cloud.py +651 -627
  29. package/scripts/panel_server.py +32 -13
  30. package/scripts/panels.py +610 -602
  31. package/scripts/retriever.py +219 -195
  32. package/scripts/rss_ingest.py +190 -181
  33. package/scripts/session_summary.py +148 -123
  34. package/scripts/web_research.py +131 -124
@@ -1,195 +1,219 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """检索接入(附录 C · P3)——优先问 session-rag 服务,没有就退回灵枢自己的召回。
4
-
5
- 统一契约(附录 B §4):
6
- POST {session_rag.url}/v1/search {"query": "...", "k": 20}
7
- -> {"results": [{"id","text","score","source"}]}
8
-
9
- 拿不到服务(没配 / 超时 / 报错 / 返回不可解析)→ **回退 `memory.recall()`**,
10
- 并在结果里标 `source='lingshu'` + warning。绝不因为检索坏了阻塞注入。
11
-
12
- 二段式:`search()` 拿候选 → `select()` 按预算挑(模型可选,失败退回打分顺序)。
13
- """
14
- from __future__ import annotations
15
-
16
- import json
17
- import urllib.request
18
-
19
- DEFAULT_BUDGET_TOKENS = 800
20
- CHARS_PER_TOKEN = 2
21
-
22
-
23
- def _cfg(cfg: dict | None) -> dict:
24
- if cfg is not None:
25
- return dict(cfg.get("session_rag") or {})
26
- try:
27
- import core
28
- return dict((core.load_config() or {}).get("session_rag") or {})
29
- except Exception:
30
- return {}
31
-
32
-
33
- def estimate_tokens(text: str) -> int:
34
- n = len(str(text or ""))
35
- return (n + CHARS_PER_TOKEN - 1) // CHARS_PER_TOKEN
36
-
37
-
38
- def _normalize(items) -> list[dict]:
39
- out = []
40
- for it in items or []:
41
- if not isinstance(it, dict):
42
- continue
43
- text = str(it.get("text") or it.get("content") or "").strip()
44
- if not text:
45
- continue
46
- out.append({
47
- "id": str(it.get("id") or it.get("memory_id") or ""),
48
- "text": text,
49
- "score": float(it.get("score") or 0.0),
50
- "source": str(it.get("source") or it.get("platform") or ""),
51
- })
52
- return out
53
-
54
-
55
- def http_search(query: str, k: int = 20, *, cfg: dict | None = None, call=None,
56
- timeout: float | None = None) -> list[dict] | None:
57
- """问 session-rag 的 /v1/search;失败返回 None(由上层回退)。"""
58
- c = _cfg(cfg)
59
- url = str(c.get("url") or "").rstrip("/")
60
- if not url and call is None:
61
- return None
62
- if call is not None:
63
- try:
64
- return _normalize(call(query, k))
65
- except Exception:
66
- return None
67
- body = json.dumps({"query": query, "k": int(k)}).encode("utf-8")
68
- req = urllib.request.Request(url + "/v1/search", data=body, method="POST",
69
- headers={"Content-Type": "application/json"})
70
- try:
71
- with urllib.request.urlopen(req, timeout=timeout or float(c.get("timeout") or 3)) as r:
72
- # 响应上限 2MB:服务异常/恶意代理返回超大 body 时不能把内存打满
73
- data = json.loads(r.read(2 * 1024 * 1024).decode("utf-8", "replace"))
74
- rows = data.get("results") if isinstance(data, dict) else data
75
- return _normalize(rows)
76
- except Exception as exc: # noqa: BLE001
77
- try:
78
- import failures
79
- failures.record("retriever.session_rag", f"{type(exc).__name__}: {exc}",
80
- ctx={"url": url})
81
- except Exception:
82
- pass
83
- return None
84
-
85
-
86
- def recall_search(query: str, k: int = 20) -> list[dict]:
87
- """灵枢本地召回(词面/实体/向量混合,取决于配置),失败返回空。"""
88
- try:
89
- import memory
90
- rows = memory.recall(query, k=int(k))
91
- except Exception:
92
- return []
93
- out = []
94
- for item in rows or []:
95
- try:
96
- m, score, _parts = item
97
- except Exception:
98
- continue
99
- out.append({
100
- "id": str(m.get("id") or ""),
101
- "text": str(m.get("text") or ""),
102
- "score": float(score or 0.0),
103
- "source": "lingshu",
104
- })
105
- return out
106
-
107
-
108
- def search(query: str, k: int = 20, *, cfg: dict | None = None, call=None) -> dict:
109
- """先服务后本地,返回 {results, source, warnings}。"""
110
- warnings: list[str] = []
111
- rows = http_search(query, k, cfg=cfg, call=call)
112
- if rows is not None:
113
- return {"results": rows, "source": "session-rag", "warnings": warnings}
114
- c = _cfg(cfg)
115
- if c.get("url"):
116
- warnings.append("session-rag 不可用,已回退灵枢本地召回")
117
- rows = recall_search(query, k)
118
- return {"results": rows, "source": "lingshu", "warnings": warnings}
119
-
120
-
121
- # ---------------------------------------------------------------- 挑选
122
-
123
- def _heuristic(cands: list[dict], budget_tokens: int) -> list[dict]:
124
- kept, used = [], 0
125
- for it in cands:
126
- t = estimate_tokens(it["text"])
127
- if kept and used + t > budget_tokens:
128
- continue
129
- kept.append(it)
130
- used += t
131
- if used >= budget_tokens:
132
- break
133
- return kept
134
-
135
-
136
- def _model_select(cands: list[dict], query: str, call) -> list[dict] | None:
137
- """让模型从候选里挑:只要 id 列表,不重写正文。"""
138
- brief = "\n".join(f"{i+1}. id={c['id']} 摘要={c['text'][:120]}"
139
- for i, c in enumerate(cands))
140
- prompt = (f"查询:{query}\n下面是从记忆里检索到的候选片段。只挑和查询真正相关的,"
141
- f"最多 5 条。只输出 JSON:{{\"keep\":[\"id\", ...]}}\n\n{brief}")
142
- try:
143
- raw = call(prompt)
144
- data = json.loads(str(raw or "").strip())
145
- keep = [str(x) for x in (data.get("keep") or [])]
146
- except Exception:
147
- return None
148
- if not keep:
149
- return None
150
- by_id = {c["id"]: c for c in cands}
151
- out = [by_id[i] for i in keep if i in by_id]
152
- return out or None
153
-
154
-
155
- def select(cands: list[dict], query: str = "", *, budget_tokens: int | None = None,
156
- cfg: dict | None = None, call=None) -> dict:
157
- """候选 → 选中(模型优先,失败/超预算退回启发式)。"""
158
- c = _cfg(cfg)
159
- budget = int(budget_tokens or c.get("budget_tokens") or DEFAULT_BUDGET_TOKENS)
160
- cands = _normalize(cands)
161
- if not cands:
162
- return {"kept": [], "source": "empty", "warnings": []}
163
- warnings: list[str] = []
164
- kept = None
165
- if call is not None or c.get("select_model"):
166
- caller = call
167
- if caller is None:
168
- try:
169
- from summarizer import openai_chat
170
- caller = lambda p: openai_chat(p, dict(c.get("select") or {}))
171
- except Exception:
172
- caller = None
173
- if caller is not None:
174
- kept = _model_select(cands, query, caller)
175
- if kept is None:
176
- warnings.append("模型挑选失败/不可用,退回打分顺序")
177
- source = "model" if kept is not None else "heuristic"
178
- if kept is None:
179
- kept = _heuristic(cands, budget)
180
- return {"kept": kept, "source": source, "warnings": warnings,
181
- "tokens": sum(estimate_tokens(x["text"]) for x in kept)}
182
-
183
-
184
- def build_snippet(query: str, k: int = 20, *, budget_tokens: int | None = None,
185
- cfg: dict | None = None, call=None) -> str:
186
- """一步到位:检索 → 挑选 → 拼成带来源标记的文本块(空结果返回 "")。"""
187
- res = search(query, k, cfg=cfg)
188
- picked = select(res["results"], query, budget_tokens=budget_tokens, cfg=cfg, call=call)
189
- if not picked["kept"]:
190
- return ""
191
- lines = [f"## 检索到的相关片段(来源:{res['source']})"]
192
- for it in picked["kept"]:
193
- tag = f"[{it['source'] or 'mem'}:{it['id']}]" if it["id"] else f"[{it['source'] or 'mem'}]"
194
- lines.append(f"- {tag} {it['text'][:400]}")
195
- return "\n".join(lines)
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """检索接入(附录 C · P3)——优先问 session-rag 服务,没有就退回灵枢自己的召回。
4
+
5
+ 统一契约(附录 B §4):
6
+ POST {session_rag.url}/v1/search {"query": "...", "k": 20}
7
+ -> {"results": [{"id","text","score","source"}]}
8
+
9
+ 拿不到服务(没配 / 超时 / 报错 / 返回不可解析)→ **回退 `memory.recall()`**,
10
+ 并在结果里标 `source='lingshu'` + warning。绝不因为检索坏了阻塞注入。
11
+
12
+ 二段式:`search()` 拿候选 → `select()` 按预算挑(模型可选,失败退回打分顺序)。
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import urllib.request
18
+
19
+ DEFAULT_BUDGET_TOKENS = 800
20
+ CHARS_PER_TOKEN = 2
21
+
22
+
23
+ def _cfg(cfg: dict | None) -> dict:
24
+ if cfg is not None:
25
+ return dict(cfg.get("session_rag") or {})
26
+ try:
27
+ import core
28
+ return dict((core.load_config() or {}).get("session_rag") or {})
29
+ except Exception:
30
+ return {}
31
+
32
+
33
+ def estimate_tokens(text: str) -> int:
34
+ n = len(str(text or ""))
35
+ return (n + CHARS_PER_TOKEN - 1) // CHARS_PER_TOKEN
36
+
37
+
38
+ def _normalize(items) -> list[dict]:
39
+ out = []
40
+ for it in items or []:
41
+ if not isinstance(it, dict):
42
+ continue
43
+ text = str(it.get("text") or it.get("content") or "").strip()
44
+ if not text:
45
+ continue
46
+ # LS-051(v5.66):容错检索候选中的脏 score——非法数值回退默认值
47
+ try:
48
+ _score = float(it.get("score") or 0.0)
49
+ except (TypeError, ValueError):
50
+ _score = 0.0
51
+ out.append({
52
+ "id": str(it.get("id") or it.get("memory_id") or ""),
53
+ "text": text,
54
+ "score": _score,
55
+ "source": str(it.get("source") or it.get("platform") or ""),
56
+ })
57
+ return out
58
+
59
+
60
+ def http_search(query: str, k: int = 20, *, cfg: dict | None = None, call=None,
61
+ timeout: float | None = None) -> list[dict] | None:
62
+ """问 session-rag 的 /v1/search;失败返回 None(由上层回退)。"""
63
+ c = _cfg(cfg)
64
+ url = str(c.get("url") or "").rstrip("/")
65
+ if not url and call is None:
66
+ return None
67
+ if call is not None:
68
+ try:
69
+ return _normalize(call(query, k))
70
+ except Exception:
71
+ return None
72
+ body = json.dumps({"query": query, "k": int(k)}).encode("utf-8")
73
+ req = urllib.request.Request(url + "/v1/search", data=body, method="POST",
74
+ headers={"Content-Type": "application/json"})
75
+ try:
76
+ with urllib.request.urlopen(req, timeout=timeout or float(c.get("timeout") or 3)) as r:
77
+ # 响应上限 2MB:服务异常/恶意代理返回超大 body 时不能把内存打满
78
+ data = json.loads(r.read(2 * 1024 * 1024).decode("utf-8", "replace"))
79
+ rows = data.get("results") if isinstance(data, dict) else data
80
+ return _normalize(rows)
81
+ except Exception as exc: # noqa: BLE001
82
+ try:
83
+ import failures
84
+ failures.record("retriever.session_rag", f"{type(exc).__name__}: {exc}",
85
+ ctx={"url": url})
86
+ except Exception:
87
+ pass
88
+ return None
89
+
90
+
91
+ def recall_search(query: str, k: int = 20) -> list[dict]:
92
+ """灵枢本地召回(词面/实体/向量混合,取决于配置),失败返回空。"""
93
+ try:
94
+ import memory
95
+ rows = memory.recall(query, k=int(k))
96
+ except Exception:
97
+ return []
98
+ out = []
99
+ for item in rows or []:
100
+ try:
101
+ m, score, _parts = item
102
+ except Exception:
103
+ continue
104
+ out.append({
105
+ "id": str(m.get("id") or ""),
106
+ "text": str(m.get("text") or ""),
107
+ "score": float(score or 0.0),
108
+ "source": "lingshu",
109
+ })
110
+ return out
111
+
112
+
113
+ def search(query: str, k: int = 20, *, cfg: dict | None = None, call=None) -> dict:
114
+ """先服务后本地,返回 {results, source, warnings}。"""
115
+ warnings: list[str] = []
116
+ rows = http_search(query, k, cfg=cfg, call=call)
117
+ if rows is not None:
118
+ return {"results": rows, "source": "session-rag", "warnings": warnings}
119
+ c = _cfg(cfg)
120
+ if c.get("url"):
121
+ warnings.append("session-rag 不可用,已回退灵枢本地召回")
122
+ rows = recall_search(query, k)
123
+ return {"results": rows, "source": "lingshu", "warnings": warnings}
124
+
125
+
126
+ # ---------------------------------------------------------------- 挑选
127
+
128
+ def _heuristic(cands: list[dict], budget_tokens: int) -> list[dict]:
129
+ # LS-041(v5.66):首条也必须检查预算或明确截断!
130
+ # 旧代码 `if kept and used + t > budget_tokens` 里 kept 为空时跳过检查,
131
+ # 导致首条超预算(数千 token)也照放不误。
132
+ kept, used = [], 0
133
+ for it in cands:
134
+ t = estimate_tokens(it["text"])
135
+ if used + t > budget_tokens:
136
+ if kept:
137
+ continue # 非首条:超预算跳过
138
+ # 首条超预算:截断到预算允许的长度,确保总 token 不超
139
+ _allow = max(1, budget_tokens - used)
140
+ it = dict(it, text=it["text"][:_allow * CHARS_PER_TOKEN])
141
+ t = estimate_tokens(it["text"])
142
+ kept.append(it)
143
+ used += t
144
+ if used >= budget_tokens:
145
+ break
146
+ return kept
147
+
148
+
149
+ def _model_select(cands: list[dict], query: str, call) -> list[dict] | None:
150
+ """让模型从候选里挑:只要 id 列表,不重写正文。"""
151
+ brief = "\n".join(f"{i+1}. id={c['id']} 摘要={c['text'][:120]}"
152
+ for i, c in enumerate(cands))
153
+ prompt = (f"查询:{query}\n下面是从记忆里检索到的候选片段。只挑和查询真正相关的,"
154
+ f"最多 5 条。只输出 JSON:{{\"keep\":[\"id\", ...]}}\n\n{brief}")
155
+ try:
156
+ raw = call(prompt)
157
+ data = json.loads(str(raw or "").strip())
158
+ keep = [str(x) for x in (data.get("keep") or [])]
159
+ except Exception:
160
+ return None
161
+ if not keep:
162
+ return None
163
+ by_id = {c["id"]: c for c in cands}
164
+ out = [by_id[i] for i in keep if i in by_id]
165
+ if not out:
166
+ return None
167
+ # LS-040(v5.66):模型挑选结果遵守 token 预算!
168
+ # 模型可能选出总 token 超预算的结果——必须再做预算裁剪。
169
+ return out
170
+
171
+
172
+ def select(cands: list[dict], query: str = "", *, budget_tokens: int | None = None,
173
+ cfg: dict | None = None, call=None) -> dict:
174
+ """候选 → 选中(模型优先,失败/超预算退回启发式)。"""
175
+ c = _cfg(cfg)
176
+ budget = int(budget_tokens or c.get("budget_tokens") or DEFAULT_BUDGET_TOKENS)
177
+ cands = _normalize(cands)
178
+ if not cands:
179
+ return {"kept": [], "source": "empty", "warnings": []}
180
+ warnings: list[str] = []
181
+ kept = None
182
+ if call is not None or c.get("select_model"):
183
+ caller = call
184
+ if caller is None:
185
+ try:
186
+ from summarizer import openai_chat
187
+ caller = lambda p: openai_chat(p, dict(c.get("select") or {}))
188
+ except Exception:
189
+ caller = None
190
+ if caller is not None:
191
+ kept = _model_select(cands, query, caller)
192
+ if kept is None:
193
+ warnings.append("模型挑选失败/不可用,退回打分顺序")
194
+ source = "model" if kept is not None else "heuristic"
195
+ if kept is not None:
196
+ # LS-040(v5.66):模型挑选结果也必须遵守 token 预算!
197
+ kept = _heuristic(kept, budget)
198
+ if not kept:
199
+ warnings.append("模型挑选结果超出预算,退回启发式")
200
+ source = "heuristic"
201
+ kept = _heuristic(cands, budget)
202
+ if kept is None:
203
+ kept = _heuristic(cands, budget)
204
+ return {"kept": kept, "source": source, "warnings": warnings,
205
+ "tokens": sum(estimate_tokens(x["text"]) for x in kept)}
206
+
207
+
208
+ def build_snippet(query: str, k: int = 20, *, budget_tokens: int | None = None,
209
+ cfg: dict | None = None, call=None) -> str:
210
+ """一步到位:检索 → 挑选 → 拼成带来源标记的文本块(空结果返回 "")。"""
211
+ res = search(query, k, cfg=cfg)
212
+ picked = select(res["results"], query, budget_tokens=budget_tokens, cfg=cfg, call=call)
213
+ if not picked["kept"]:
214
+ return ""
215
+ lines = [f"## 检索到的相关片段(来源:{res['source']})"]
216
+ for it in picked["kept"]:
217
+ tag = f"[{it['source'] or 'mem'}:{it['id']}]" if it["id"] else f"[{it['source'] or 'mem'}]"
218
+ lines.append(f"- {tag} {it['text'][:400]}")
219
+ return "\n".join(lines)