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.
- package/CHANGELOG.md +25 -0
- package/README.md +1 -1
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +1 -1
- package/manifest.json +26 -26
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +15 -15
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +25 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +17 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +282 -259
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +215 -209
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_exchange.py +217 -171
- package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +219 -195
- package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +190 -181
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +11 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +148 -123
- package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +131 -124
- package/scripts/checkpoint.py +17 -3
- package/scripts/mem_dialogue.py +282 -259
- package/scripts/mem_embed.py +215 -209
- package/scripts/mem_exchange.py +217 -171
- package/scripts/retriever.py +219 -195
- package/scripts/rss_ingest.py +190 -181
- package/scripts/session_rag.py +11 -3
- package/scripts/session_summary.py +148 -123
- package/scripts/web_research.py +131 -124
|
@@ -1,123 +1,148 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# -*- coding: utf-8 -*-
|
|
3
|
-
"""会话摘要的触发与落盘(附录 C · P2 收尾)。
|
|
4
|
-
|
|
5
|
-
三件事:
|
|
6
|
-
1. **触发规则**:每 N 轮 / 水位 ≥60% / 用户显式要求,三者任一即触发;
|
|
7
|
-
2. **落盘**:`~/.brain-memory/sessions/summaries/<session>.md`,保留最近 3 版;
|
|
8
|
-
3. **回滚**:`rollback(n)` 把上一版恢复成当前版(摘要漂移时的人工兜底)。
|
|
9
|
-
|
|
10
|
-
摘要生成复用 summarizer.summarize()(模型可选、fail-open)。
|
|
11
|
-
"""
|
|
12
|
-
from __future__ import annotations
|
|
13
|
-
|
|
14
|
-
import json
|
|
15
|
-
import time
|
|
16
|
-
from pathlib import Path
|
|
17
|
-
|
|
18
|
-
KEEP_VERSIONS = 3
|
|
19
|
-
DEFAULT_TURNS = 8
|
|
20
|
-
DEFAULT_PCT = 0.60
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def summaries_dir(home=None) -> Path:
|
|
24
|
-
return Path(home or _home()) / "sessions" / "summaries"
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def _home():
|
|
28
|
-
try:
|
|
29
|
-
import core
|
|
30
|
-
return core.HOME
|
|
31
|
-
except Exception:
|
|
32
|
-
return Path.home() / ".brain-memory"
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
def _paths(session_id: str, home=None) -> list[Path]:
|
|
36
|
-
"""[当前, .1, .2] 三个版本槽。"""
|
|
37
|
-
safe = "".join(c if (c.isalnum() or c in "-_.") else "_" for c in str(session_id or "default"))
|
|
38
|
-
base = summaries_dir(home)
|
|
39
|
-
return [base / f"{safe}.md"] + [base / f"{safe}.{i}.md" for i in range(1, KEEP_VERSIONS)]
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
# ---------------------------------------------------------------- 触发
|
|
43
|
-
|
|
44
|
-
def decide(turns_since_last: int = 0, used_pct: float | None = None,
|
|
45
|
-
force: bool = False, cfg: dict | None = None) -> dict:
|
|
46
|
-
"""返回 {trigger: bool, reason: str}。三个条件任一满足就触发。"""
|
|
47
|
-
cfg = cfg or {}
|
|
48
|
-
every = int(cfg.get("summary_turns") or DEFAULT_TURNS)
|
|
49
|
-
pct_th = float(cfg.get("summary_pct") or DEFAULT_PCT)
|
|
50
|
-
if force:
|
|
51
|
-
return {"trigger": True, "reason": "force(用户/命令显式要求)"}
|
|
52
|
-
if used_pct is not None and float(used_pct) >= pct_th * 100:
|
|
53
|
-
return {"trigger": True, "reason": f"水位 {float(used_pct):.0f}% ≥ {pct_th * 100:.0f}%"}
|
|
54
|
-
if turns_since_last >= every:
|
|
55
|
-
return {"trigger": True, "reason": f"距上次摘要 {turns_since_last} 轮 ≥ {every}"}
|
|
56
|
-
return {"trigger": False, "reason": f"未触发({turns_since_last} 轮 / "
|
|
57
|
-
f"{'—' if used_pct is None else f'{float(used_pct):.0f}%'})"}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
# ---------------------------------------------------------------- 落盘 / 读取 / 回滚
|
|
61
|
-
|
|
62
|
-
def save(text: str, session_id: str = "default", home=None, meta: dict | None = None) -> dict:
|
|
63
|
-
"""
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
paths[0].
|
|
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
|
-
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""会话摘要的触发与落盘(附录 C · P2 收尾)。
|
|
4
|
+
|
|
5
|
+
三件事:
|
|
6
|
+
1. **触发规则**:每 N 轮 / 水位 ≥60% / 用户显式要求,三者任一即触发;
|
|
7
|
+
2. **落盘**:`~/.brain-memory/sessions/summaries/<session>.md`,保留最近 3 版;
|
|
8
|
+
3. **回滚**:`rollback(n)` 把上一版恢复成当前版(摘要漂移时的人工兜底)。
|
|
9
|
+
|
|
10
|
+
摘要生成复用 summarizer.summarize()(模型可选、fail-open)。
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
KEEP_VERSIONS = 3
|
|
19
|
+
DEFAULT_TURNS = 8
|
|
20
|
+
DEFAULT_PCT = 0.60
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def summaries_dir(home=None) -> Path:
|
|
24
|
+
return Path(home or _home()) / "sessions" / "summaries"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _home():
|
|
28
|
+
try:
|
|
29
|
+
import core
|
|
30
|
+
return core.HOME
|
|
31
|
+
except Exception:
|
|
32
|
+
return Path.home() / ".brain-memory"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _paths(session_id: str, home=None) -> list[Path]:
|
|
36
|
+
"""[当前, .1, .2] 三个版本槽。"""
|
|
37
|
+
safe = "".join(c if (c.isalnum() or c in "-_.") else "_" for c in str(session_id or "default"))
|
|
38
|
+
base = summaries_dir(home)
|
|
39
|
+
return [base / f"{safe}.md"] + [base / f"{safe}.{i}.md" for i in range(1, KEEP_VERSIONS)]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ---------------------------------------------------------------- 触发
|
|
43
|
+
|
|
44
|
+
def decide(turns_since_last: int = 0, used_pct: float | None = None,
|
|
45
|
+
force: bool = False, cfg: dict | None = None) -> dict:
|
|
46
|
+
"""返回 {trigger: bool, reason: str}。三个条件任一满足就触发。"""
|
|
47
|
+
cfg = cfg or {}
|
|
48
|
+
every = int(cfg.get("summary_turns") or DEFAULT_TURNS)
|
|
49
|
+
pct_th = float(cfg.get("summary_pct") or DEFAULT_PCT)
|
|
50
|
+
if force:
|
|
51
|
+
return {"trigger": True, "reason": "force(用户/命令显式要求)"}
|
|
52
|
+
if used_pct is not None and float(used_pct) >= pct_th * 100:
|
|
53
|
+
return {"trigger": True, "reason": f"水位 {float(used_pct):.0f}% ≥ {pct_th * 100:.0f}%"}
|
|
54
|
+
if turns_since_last >= every:
|
|
55
|
+
return {"trigger": True, "reason": f"距上次摘要 {turns_since_last} 轮 ≥ {every}"}
|
|
56
|
+
return {"trigger": False, "reason": f"未触发({turns_since_last} 轮 / "
|
|
57
|
+
f"{'—' if used_pct is None else f'{float(used_pct):.0f}%'})"}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ---------------------------------------------------------------- 落盘 / 读取 / 回滚
|
|
61
|
+
|
|
62
|
+
def save(text: str, session_id: str = "default", home=None, meta: dict | None = None) -> dict:
|
|
63
|
+
"""写入当前版,按顺序轮转:.1 ← 旧的当前版,.2 ← .1 ...
|
|
64
|
+
|
|
65
|
+
LS-039(v5.66):摘要轮转失败时保留当前版本!
|
|
66
|
+
旧实现在轮转 .1→.2 / .2→.3 过程中若出现 OSError 只是 pass,
|
|
67
|
+
但此时 paths[0].write_text 已经执行——新旧摘要都被破坏。
|
|
68
|
+
修复:先备份旧当前版,轮转失败时中止覆盖并返回失败,绝不丢失旧摘要。
|
|
69
|
+
"""
|
|
70
|
+
if not str(text or "").strip():
|
|
71
|
+
return {"ok": False, "reason": "空摘要"}
|
|
72
|
+
paths = _paths(session_id, home)
|
|
73
|
+
paths[0].parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
# 先备份旧当前版
|
|
75
|
+
_old_current = None
|
|
76
|
+
if paths[0].exists():
|
|
77
|
+
try:
|
|
78
|
+
_old_current = paths[0].read_text(encoding="utf-8")
|
|
79
|
+
except OSError:
|
|
80
|
+
pass
|
|
81
|
+
for i in range(len(paths) - 1, 0, -1):
|
|
82
|
+
if paths[i - 1].exists():
|
|
83
|
+
try:
|
|
84
|
+
paths[i].write_text(paths[i - 1].read_text(encoding="utf-8"), encoding="utf-8")
|
|
85
|
+
except OSError:
|
|
86
|
+
# 轮转失败,中止覆盖当前版并返回失败
|
|
87
|
+
if _old_current is not None:
|
|
88
|
+
try:
|
|
89
|
+
paths[0].write_text(_old_current, encoding="utf-8")
|
|
90
|
+
except OSError:
|
|
91
|
+
pass
|
|
92
|
+
return {"ok": False, "reason": "摘要轮转失败(已保留当前版本)"}
|
|
93
|
+
payload = str(text).rstrip() + "\n"
|
|
94
|
+
if meta:
|
|
95
|
+
payload = f"<!-- {json.dumps(meta, ensure_ascii=False)} -->\n" + payload
|
|
96
|
+
try:
|
|
97
|
+
paths[0].write_text(payload, encoding="utf-8")
|
|
98
|
+
except OSError:
|
|
99
|
+
if _old_current is not None:
|
|
100
|
+
try:
|
|
101
|
+
paths[0].write_text(_old_current, encoding="utf-8")
|
|
102
|
+
except OSError:
|
|
103
|
+
pass
|
|
104
|
+
return {"ok": False, "reason": "新摘要写入失败(已恢复当前版本)"}
|
|
105
|
+
return {"ok": True, "path": str(paths[0]), "chars": len(text)}
|
|
106
|
+
def load(session_id: str = "default", home=None) -> str:
|
|
107
|
+
p = _paths(session_id, home)[0]
|
|
108
|
+
try:
|
|
109
|
+
return p.read_text(encoding="utf-8")
|
|
110
|
+
except OSError:
|
|
111
|
+
return ""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def rollback(session_id: str = "default", home=None, steps: int = 1) -> dict:
|
|
115
|
+
"""回滚:把最近一版备份恢复成当前版(保留被替换的那版到 .2)。"""
|
|
116
|
+
paths = _paths(session_id, home)
|
|
117
|
+
steps = max(1, int(steps))
|
|
118
|
+
if steps >= len(paths) or not paths[1].exists():
|
|
119
|
+
return {"ok": False, "reason": "没有可回滚的备份"}
|
|
120
|
+
restored = paths[steps].read_text(encoding="utf-8")
|
|
121
|
+
for i in range(len(paths) - 1, 0, -1):
|
|
122
|
+
if paths[i - 1].exists():
|
|
123
|
+
try:
|
|
124
|
+
paths[i].write_text(paths[i - 1].read_text(encoding="utf-8"), encoding="utf-8")
|
|
125
|
+
except OSError:
|
|
126
|
+
pass
|
|
127
|
+
paths[0].write_text(restored, encoding="utf-8")
|
|
128
|
+
return {"ok": True, "path": str(paths[0]), "chars": len(restored)}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ---------------------------------------------------------------- 一步到位
|
|
132
|
+
|
|
133
|
+
def maybe_summarize(turns: list, *, session_id: str = "default", turns_since_last: int = 0,
|
|
134
|
+
used_pct: float | None = None, force: bool = False,
|
|
135
|
+
cfg: dict | None = None, home=None, prev_summary: str = "",
|
|
136
|
+
max_chars: int = 1500) -> dict:
|
|
137
|
+
"""触发判断 → 生成 → 落盘。不触发时不生成(省一次模型/IO)。"""
|
|
138
|
+
from summarizer import summarize
|
|
139
|
+
d = decide(turns_since_last, used_pct, force, cfg)
|
|
140
|
+
if not d["trigger"]:
|
|
141
|
+
return {"ok": True, "skipped": True, "reason": d["reason"]}
|
|
142
|
+
res = summarize(turns, cfg=cfg, prev_summary=prev_summary or load(session_id, home),
|
|
143
|
+
max_chars=max_chars)
|
|
144
|
+
saved = save(res["text"], session_id, home,
|
|
145
|
+
meta={"ts": int(time.time()), "source": res["source"], "reason": d["reason"]})
|
|
146
|
+
return {"ok": bool(saved.get("ok")), "skipped": False, "reason": d["reason"],
|
|
147
|
+
"source": res["source"], "chars": res["chars"], "path": saved.get("path"),
|
|
148
|
+
"warnings": res.get("warnings") or [], "text": res["text"]}
|
|
@@ -1,125 +1,132 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# -*- coding: utf-8 -*-
|
|
3
|
-
"""联网调研工具(零依赖,stdlib)。
|
|
4
|
-
|
|
5
|
-
为什么需要它:`web_search` 工具走模型 provider 的搜索端点,2026-11-30 实测 **HTTP 402 余额不足**;
|
|
6
|
-
但**普通 HTTP 是通的**(实测 api.github.com 200、www.bing.com 200)。所以给灵枢自带一条
|
|
7
|
-
"能联网就联网"的调研路径:
|
|
8
|
-
|
|
9
|
-
brain.py web search "关键词" # Bing HTML 结果(标题 + 链接)
|
|
10
|
-
brain.py web fetch <url> # 抓正文纯文本(去标签/脚本,限长)
|
|
11
|
-
|
|
12
|
-
调研阶梯(按顺序用,失败才降级):
|
|
13
|
-
1. `web` 工具 / `report-page` 技能(如果可用)
|
|
14
|
-
2. 本工具:search + fetch(Bing HTML + urllib)
|
|
15
|
-
3. `skill` 里的 webapp-testing(Playwright,能跑真浏览器)
|
|
16
|
-
4. 本地取证:安装包(asar)/ 源码 / 文档
|
|
17
|
-
|
|
18
|
-
设计约束:零依赖;超时短(默认 12s);UA 伪装;任何异常都返回结构化错误而不是抛栈。
|
|
19
|
-
"""
|
|
20
|
-
from __future__ import annotations
|
|
21
|
-
|
|
22
|
-
import html as _html
|
|
23
|
-
import json
|
|
24
|
-
import re
|
|
25
|
-
import urllib.parse
|
|
26
|
-
import urllib.request
|
|
27
|
-
|
|
28
|
-
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
29
|
-
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36")
|
|
30
|
-
MAX_HTML = 4 << 20 # 4MB 上限,防超大页面拖死
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def _get(url: str, timeout: float = 12.0) -> tuple:
|
|
34
|
-
"""返回 (status, text)。失败返回 (0,
|
|
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
|
-
print(
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""联网调研工具(零依赖,stdlib)。
|
|
4
|
+
|
|
5
|
+
为什么需要它:`web_search` 工具走模型 provider 的搜索端点,2026-11-30 实测 **HTTP 402 余额不足**;
|
|
6
|
+
但**普通 HTTP 是通的**(实测 api.github.com 200、www.bing.com 200)。所以给灵枢自带一条
|
|
7
|
+
"能联网就联网"的调研路径:
|
|
8
|
+
|
|
9
|
+
brain.py web search "关键词" # Bing HTML 结果(标题 + 链接)
|
|
10
|
+
brain.py web fetch <url> # 抓正文纯文本(去标签/脚本,限长)
|
|
11
|
+
|
|
12
|
+
调研阶梯(按顺序用,失败才降级):
|
|
13
|
+
1. `web` 工具 / `report-page` 技能(如果可用)
|
|
14
|
+
2. 本工具:search + fetch(Bing HTML + urllib)
|
|
15
|
+
3. `skill` 里的 webapp-testing(Playwright,能跑真浏览器)
|
|
16
|
+
4. 本地取证:安装包(asar)/ 源码 / 文档
|
|
17
|
+
|
|
18
|
+
设计约束:零依赖;超时短(默认 12s);UA 伪装;任何异常都返回结构化错误而不是抛栈。
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import html as _html
|
|
23
|
+
import json
|
|
24
|
+
import re
|
|
25
|
+
import urllib.parse
|
|
26
|
+
import urllib.request
|
|
27
|
+
|
|
28
|
+
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
29
|
+
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36")
|
|
30
|
+
MAX_HTML = 4 << 20 # 4MB 上限,防超大页面拖死
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _get(url: str, timeout: float = 12.0) -> tuple:
|
|
34
|
+
"""返回 (status, text, truncated)。失败返回 (0, 错误信息, False)。
|
|
35
|
+
|
|
36
|
+
LS-048(v5.66):显式标记网页响应截断!
|
|
37
|
+
r.read(MAX_HTML) 读取到上限时可能**恰好在 HTML/JSON 中间断开**,
|
|
38
|
+
把不完整的正文当成功返回。现在通过多读一字节检测是否截断。
|
|
39
|
+
"""
|
|
40
|
+
try:
|
|
41
|
+
req = urllib.request.Request(url, headers={
|
|
42
|
+
"User-Agent": UA,
|
|
43
|
+
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
|
44
|
+
"Accept": "text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8",
|
|
45
|
+
})
|
|
46
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
47
|
+
raw = r.read(MAX_HTML)
|
|
48
|
+
# LS-048: 多读一字节检测截断——如果还有数据说明被截断了
|
|
49
|
+
truncated = bool(r.read(1))
|
|
50
|
+
charset = r.headers.get_content_charset() or "utf-8"
|
|
51
|
+
try:
|
|
52
|
+
text = raw.decode(charset, "replace")
|
|
53
|
+
except LookupError:
|
|
54
|
+
text = raw.decode("utf-8", "replace")
|
|
55
|
+
return r.status, text, truncated
|
|
56
|
+
except Exception as exc: # noqa: BLE001
|
|
57
|
+
return 0, f"{type(exc).__name__}: {exc}", False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def search(query: str, n: int = 8, timeout: float = 12.0) -> dict:
|
|
61
|
+
"""Bing HTML 搜索,返回 {ok, query, results:[{title,url}], truncated}。"""
|
|
62
|
+
q = urllib.parse.quote_plus(query)
|
|
63
|
+
status, body, truncated = _get(f"https://www.bing.com/search?q={q}&setlang=zh-CN", timeout)
|
|
64
|
+
if status != 200:
|
|
65
|
+
return {"ok": False, "query": query, "error": body, "results": []}
|
|
66
|
+
out, seen = [], set()
|
|
67
|
+
for m in re.finditer(r"<h2[^>]*>\s*<a[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>\s*</h2>", body, re.S):
|
|
68
|
+
url = _html.unescape(m.group(1))
|
|
69
|
+
title = _html.unescape(re.sub(r"<[^>]+>", "", m.group(2))).strip()
|
|
70
|
+
if not title or url.startswith("javascript") or url in seen:
|
|
71
|
+
continue
|
|
72
|
+
# Bing 会把真实链接包在 /ck/a?u=a1... 里,能解就解
|
|
73
|
+
if "bing.com/ck/a" in url:
|
|
74
|
+
qs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
|
|
75
|
+
u = (qs.get("u") or [""])[0]
|
|
76
|
+
if u.startswith("a1"):
|
|
77
|
+
u = u[2:]
|
|
78
|
+
try:
|
|
79
|
+
import base64
|
|
80
|
+
pad = "=" * (-len(u) % 4)
|
|
81
|
+
url = base64.urlsafe_b64decode(u + pad).decode("utf-8", "replace")
|
|
82
|
+
except Exception:
|
|
83
|
+
pass
|
|
84
|
+
seen.add(url)
|
|
85
|
+
out.append({"title": title, "url": url})
|
|
86
|
+
if len(out) >= max(1, int(n)):
|
|
87
|
+
break
|
|
88
|
+
return {"ok": bool(out), "query": query, "results": out, "truncated": truncated}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def fetch(url: str, max_chars: int = 20000, timeout: float = 15.0) -> dict:
|
|
92
|
+
"""抓页面并抽正文纯文本。返回 truncated=True 表示响应被截断。"""
|
|
93
|
+
status, body, truncated = _get(url, timeout)
|
|
94
|
+
if status != 200:
|
|
95
|
+
return {"ok": False, "url": url, "error": body, "text": ""}
|
|
96
|
+
t = re.sub(r"<script[\s\S]*?</script>|<style[\s\S]*?</style>|<!--[\s\S]*?-->", " ", body, flags=re.I)
|
|
97
|
+
t = re.sub(r"<br\s*/?>|</p>|</div>|</h[1-6]>|</li>", "\n", t, flags=re.I)
|
|
98
|
+
t = re.sub(r"<[^>]+>", " ", t)
|
|
99
|
+
t = _html.unescape(t)
|
|
100
|
+
t = re.sub(r"[ \t\u00a0]+", " ", t)
|
|
101
|
+
t = re.sub(r"\n\s*\n+", "\n\n", t).strip()
|
|
102
|
+
return {"ok": True, "url": url, "chars": len(t), "text": t[:max_chars], "truncated": truncated}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def render_search(d: dict) -> list:
|
|
106
|
+
if not d.get("ok"):
|
|
107
|
+
return [f"搜索失败:{d.get('error')}", "(可依次降级:web fetch 直连 → playwright 技能 → 本地取证)"]
|
|
108
|
+
lines = [f"搜索「{d['query']}」→ {len(d['results'])} 条:"]
|
|
109
|
+
for i, r in enumerate(d["results"], 1):
|
|
110
|
+
lines.append(f" {i}. {r['title']}")
|
|
111
|
+
lines.append(f" {r['url']}")
|
|
112
|
+
return lines
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def run(args) -> int:
|
|
116
|
+
action = getattr(args, "web_action", None) or "search"
|
|
117
|
+
if action == "fetch":
|
|
118
|
+
d = fetch(args.url, max_chars=int(getattr(args, "max_chars", 20000) or 20000))
|
|
119
|
+
if getattr(args, "json", False):
|
|
120
|
+
print(json.dumps(d, ensure_ascii=False, indent=2))
|
|
121
|
+
elif d["ok"]:
|
|
122
|
+
print(d["text"])
|
|
123
|
+
else:
|
|
124
|
+
print(f"抓取失败:{d.get('error')}", file=__import__("sys").stderr)
|
|
125
|
+
return 0 if d["ok"] else 1
|
|
126
|
+
d = search(args.query, n=int(getattr(args, "limit", 8) or 8))
|
|
127
|
+
if getattr(args, "json", False):
|
|
128
|
+
print(json.dumps(d, ensure_ascii=False, indent=2))
|
|
129
|
+
else:
|
|
130
|
+
for line in render_search(d):
|
|
131
|
+
print(line)
|
|
125
132
|
return 0 if d.get("ok") else 1
|
package/scripts/checkpoint.py
CHANGED
|
@@ -197,8 +197,22 @@ def checkpoint(repo: str | None = None, note: str = "", *, dry_run: bool = False
|
|
|
197
197
|
except Exception as exc: # noqa: BLE001
|
|
198
198
|
return {"ok": False, "skipped": False, "reason": f"写记忆失败:{exc}",
|
|
199
199
|
"text": text, "evidence": ev}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
200
|
+
# LS-038(v5.65):让 checkpoint 记忆与状态提交一致!
|
|
201
|
+
# 旧代码在 write 成功后直接覆盖 state,若 state 写失败则 memory 已写入
|
|
202
|
+
# 但 state 未更新,下次重试会**重复 remember 同一条 checkpoint**。
|
|
203
|
+
# 修复:状态写失败时返回明确的部分成功结果(含 memory_id),并显式标记
|
|
204
|
+
# "state_pending",让重试逻辑能识别已写记忆不再重复。
|
|
205
|
+
try:
|
|
206
|
+
state[ev["repo"]] = {"head": ev["head"], "ts": int(time.time()),
|
|
207
|
+
"changed": ev["changed"], "version": ev["version"]}
|
|
208
|
+
_save_state(state, home)
|
|
209
|
+
except Exception as exc: # noqa: BLE001
|
|
210
|
+
return {"ok": True, "skipped": False, "state_pending": True,
|
|
211
|
+
"reason": f"记忆已写入但状态提交失败(下次重试不会重复 remember):{exc}",
|
|
212
|
+
"memory_id": mid if isinstance(mid, str) else str(mid),
|
|
213
|
+
"text": text, "evidence": ev}
|
|
214
|
+
# LS-050(v5.65):返回 record["id"] 字符串而非整个 dict
|
|
215
|
+
if isinstance(mid, dict):
|
|
216
|
+
mid = str(mid.get("id") or "")
|
|
203
217
|
return {"ok": True, "skipped": False, "reason": d["reason"], "text": text,
|
|
204
218
|
"memory_id": mid, "evidence": ev, "dry_run": dry_run}
|