lingshu-skill 0.0.0-stage → 3.82.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 (135) hide show
  1. package/CHANGELOG.md +2605 -0
  2. package/LICENSE +21 -0
  3. package/README.md +698 -3
  4. package/SKILL-lite.md +45 -0
  5. package/SKILL-tiny.md +37 -0
  6. package/SKILL.md +379 -0
  7. package/assets/panel.html +5616 -0
  8. package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
  9. package/cordis-plugin/lingshu-cron/index.js +4 -0
  10. package/cordis-plugin/lingshu-cron/package.json +34 -0
  11. package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
  12. package/cordis-plugin/lingshu-guard/plugin.js +473 -0
  13. package/cordis-plugin/lingshu-im/plugin.js +635 -0
  14. package/cordis-plugin/lingshu-startup/README.md +123 -0
  15. package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
  16. package/cordis-plugin/lingshu-startup/index.js +4 -0
  17. package/cordis-plugin/lingshu-startup/package.json +25 -0
  18. package/cordis-plugin/lingshu-startup/plugin.js +352 -0
  19. package/cordis.patch.yml +3 -0
  20. package/docs/commands.md +243 -0
  21. package/docs/mechanics.md +610 -0
  22. package/docs/models.md +52 -0
  23. package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
  24. package/docs/panel-api.md +198 -0
  25. package/docs/recovery.md +90 -0
  26. package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
  27. package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +804 -0
  28. package/index.js +102 -0
  29. package/package.json +52 -6
  30. package/scripts/_panel_smoke_v299.py +27 -0
  31. package/scripts/_smoke_v299.py +31 -0
  32. package/scripts/_sync_trae_cn.py +34 -0
  33. package/scripts/assembler.py +197 -0
  34. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
  35. package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
  36. package/scripts/astrbot_plugin_lingshu/README.md +58 -0
  37. package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
  38. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2605 -0
  39. package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
  40. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
  41. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
  42. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
  43. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
  44. package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
  45. package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
  46. package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
  47. package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
  48. package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
  49. package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
  50. package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
  51. package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
  52. package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
  53. package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
  54. package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
  55. package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
  56. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
  57. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
  58. package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
  59. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4867 -0
  60. package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
  61. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2028 -0
  62. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
  63. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
  64. package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
  65. package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
  66. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
  67. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
  68. package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
  69. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
  70. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
  71. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
  72. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
  73. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
  74. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
  75. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4417 -0
  76. package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
  77. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
  78. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
  79. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
  80. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
  81. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
  82. package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
  83. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
  84. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
  85. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
  86. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
  87. package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
  88. package/scripts/astrbot_plugin_lingshu/main.py +703 -0
  89. package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
  90. package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
  91. package/scripts/behavior_baseline.py +280 -0
  92. package/scripts/bench.py +192 -0
  93. package/scripts/brain.py +46 -0
  94. package/scripts/check_pressure_sync.py +55 -0
  95. package/scripts/check_tag.py +215 -0
  96. package/scripts/check_version.py +265 -0
  97. package/scripts/checkpoint.py +165 -0
  98. package/scripts/cli.py +4867 -0
  99. package/scripts/context_ab.py +260 -0
  100. package/scripts/core.py +2028 -0
  101. package/scripts/dream.py +1137 -0
  102. package/scripts/emotion.py +1180 -0
  103. package/scripts/failures.py +107 -0
  104. package/scripts/fallback_embed.py +114 -0
  105. package/scripts/growth.py +4745 -0
  106. package/scripts/growth_parts.py +263 -0
  107. package/scripts/hooks/pre-commit +18 -0
  108. package/scripts/hooks/pre-push +20 -0
  109. package/scripts/insights.py +131 -0
  110. package/scripts/make_dsh_tgz.py +92 -0
  111. package/scripts/make_manifest.py +254 -0
  112. package/scripts/make_plugin_zip.py +88 -0
  113. package/scripts/mem_dialogue.py +242 -0
  114. package/scripts/mem_embed.py +159 -0
  115. package/scripts/mem_lesson.py +160 -0
  116. package/scripts/mem_score.py +210 -0
  117. package/scripts/mem_topic.py +177 -0
  118. package/scripts/memory.py +4417 -0
  119. package/scripts/npm_prepack.py +31 -0
  120. package/scripts/panel_build.py +115 -0
  121. package/scripts/panel_cloud.py +609 -0
  122. package/scripts/panel_server.py +2703 -0
  123. package/scripts/panels.py +591 -0
  124. package/scripts/persona.py +2309 -0
  125. package/scripts/recreate_push.ps1 +117 -0
  126. package/scripts/retriever.py +195 -0
  127. package/scripts/run_tests.py +91 -0
  128. package/scripts/safety.py +368 -0
  129. package/scripts/session_import.py +736 -0
  130. package/scripts/session_rag.py +228 -0
  131. package/scripts/session_summary.py +123 -0
  132. package/scripts/summarizer.py +252 -0
  133. package/scripts/sync_engine.py +139 -0
  134. package/scripts/update_dsh_copy.ps1 +107 -0
  135. package/start-panel.bat +60 -0
@@ -0,0 +1,254 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """生成技能发布清单 manifest.json(文件相对路径 + SHA256 + size + version)。
4
+
5
+ 用法:
6
+ python scripts/make_manifest.py # 在仓库根生成 manifest.json
7
+ python scripts/make_manifest.py --check # 只校验现有 manifest 与工作区是否一致
8
+
9
+ 扫描范围:SKILL.md、SKILL-lite.md、SKILL-tiny.md、scripts/、assets/、docs/、
10
+ cordis-plugin/、CHANGELOG.md、README.md、package.json、cordis.patch.yml、
11
+ index.js、start-panel.bat。
12
+ 排除:__pycache__、.git、*.pyc、.lingshu-* 标记、_ 开头的临时目录、
13
+ scripts/test_*.py(自测脚本)、scripts/astrbot_plugin_lingshu/(宿主侧插件,
14
+ 独立发布,不随灵枢安装)。
15
+
16
+ 清单即发布契约:apply_update 只部署清单里的文件,所以漏扫目录 = 文件永远
17
+ 装不到用户机器;check() 会做目录覆盖面自检,防止再漏。
18
+
19
+ manifest 内置 version 与 SKILL.md 一致性校验,不一致 exit 非 0;
20
+ pre-commit 钩子与 check_version.py 可复用本文件的 read functions。
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import hashlib
26
+ import json
27
+ import re
28
+ import subprocess
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ ROOT = Path(__file__).resolve().parent.parent
33
+ VERSION_RE = re.compile(r"^version:\s*([0-9][0-9.]*)\s*$", re.MULTILINE)
34
+ SCAN_FILES = ["SKILL.md", "SKILL-lite.md", "SKILL-tiny.md", "CHANGELOG.md",
35
+ "README.md", "package.json", "cordis.patch.yml", "index.js",
36
+ "start-panel.bat"]
37
+ SCAN_DIRS = ["scripts", "assets", "docs", "cordis-plugin"]
38
+ EXCLUDE_PARTS = {"__pycache__", ".git"}
39
+ EXCLUDE_SUFFIX = (".pyc", ".pyo", ".tmp", ".lock", ".corrupt", ".log")
40
+ EXCLUDE_NAMES = {".lingshu-source", ".lingshu-sha", "AGENTS.md", "manifest.json"}
41
+ # 不随技能发布的子树:AstrBot 宿主插件(需独立装进 AstrBot 的 data/plugins)
42
+ EXCLUDE_PREFIXES = ("scripts/astrbot_plugin_lingshu/",)
43
+
44
+
45
+ def _excluded(rel: str, name: str) -> bool:
46
+ """rel 是否属于发布排除项(测试脚本、宿主插件、缓存/临时文件等)。"""
47
+ if (EXCLUDE_PARTS & set(rel.split("/"))
48
+ or rel.endswith(EXCLUDE_SUFFIX)
49
+ or name in EXCLUDE_NAMES
50
+ or name.startswith("_")
51
+ or rel.startswith(EXCLUDE_PREFIXES)):
52
+ return True
53
+ # 自测脚本(test_*.py)是开发资产,不装进用户机器
54
+ return name.startswith("test_") and name.endswith(".py")
55
+
56
+
57
+ def sha256_file(p: Path) -> tuple[str, int]:
58
+ """规范形态哈希:CRLF→LF 归一化 + 去 UTF-8 BOM 后再算,返回 (sha256, size)。
59
+
60
+ manifest 是发布契约——它必须对应"发布内容的规范形态",而不是作者本机的
61
+ 磁盘形态。作者机器 core.autocrlf=true + 记事本存盘会把工作区文件写成
62
+ CRLF+带 BOM,逐字节哈希记录的就是这套形态;用户按 raw / zip 拿到的是
63
+ LF+无 BOM,逐字节比对永远失败(v2.52 只修了比对侧,没修生成侧)。
64
+ 换行符与 BOM 都不改变内容语义,归一化后哈希才与发布内容对齐;
65
+ 真正的内容篡改仍拦得住。
66
+
67
+ 分块注意:\r 若恰好落在 64KB 块尾必须暂存到下一块拼回来再替换——否则
68
+ 边界处的 CRLF 被切成 \r|\n 两段各自漏掉,大文件哈希漂移(与比对侧同一坑)。
69
+ """
70
+ h = hashlib.sha256()
71
+ size = 0
72
+ first = True
73
+ tail = b""
74
+ with open(p, "rb") as f:
75
+ for chunk in iter(lambda: f.read(1 << 16), b""):
76
+ if first:
77
+ first = False
78
+ if chunk.startswith(b"\xef\xbb\xbf"):
79
+ chunk = chunk[3:]
80
+ chunk = tail + chunk
81
+ tail = chunk[-1:] if chunk.endswith(b"\r") else b""
82
+ if tail:
83
+ chunk = chunk[:-1]
84
+ chunk = chunk.replace(b"\r\n", b"\n")
85
+ h.update(chunk)
86
+ size += len(chunk)
87
+ if tail:
88
+ h.update(tail.replace(b"\r\n", b"\n"))
89
+ size += len(tail)
90
+ return h.hexdigest(), size
91
+
92
+
93
+ def read_skill_version(root: Path = ROOT) -> str:
94
+ m = VERSION_RE.search((root / "SKILL.md").read_text(encoding="utf-8-sig"))
95
+ if not m:
96
+ raise SystemExit("[manifest] SKILL.md 里读不出 version 字段")
97
+ return m.group(1).strip()
98
+
99
+
100
+ def _tracked_files(root: Path) -> set[str] | None:
101
+ """git 仓库里返回被跟踪文件的相对路径集合;非仓库/失败返回 None。
102
+
103
+ 为什么要这个:docs/ 下可能有作者本地保留的草稿(.gitignore 里写着"永不推送"),
104
+ 扫描时若只看磁盘,就会把它们算进发布清单——本地 --check 通过,CI 干净检出后
105
+ 必然报"清单里的文件不存在"。清单是发布契约,只该包含会被发布的东西。
106
+ """
107
+ try:
108
+ r = subprocess.run(["git", "-C", str(root), "ls-files", "-z"],
109
+ capture_output=True)
110
+ except OSError:
111
+ return None
112
+ if r.returncode != 0:
113
+ return None
114
+ return {p for p in r.stdout.decode("utf-8", "surrogateescape").split("\0") if p}
115
+
116
+
117
+ def _untracked_candidates(root: Path = ROOT) -> list[str]:
118
+ """扫描范围内、**还没 git add**、也没被 .gitignore 忽略的文件。
119
+
120
+ 清单只收被跟踪文件(见 _tracked_files),所以"新建文件忘了 git add"会让清单
121
+ 静默少收一条:本地 --check 绿、CI 干净检出后报"清单与工作区不一致"。v3.45 就
122
+ 是这么红的;v3.48 新增 docs 文件时又差点重演(差一步就把 64 项的清单带上去)。
123
+ 这里把这类文件显式找出来:生成时警告,--check 时直接判红。
124
+ """
125
+ try:
126
+ r = subprocess.run(["git", "-C", str(root), "ls-files", "-z", "--others",
127
+ "--exclude-standard"], capture_output=True)
128
+ except OSError:
129
+ return []
130
+ if r.returncode != 0:
131
+ return []
132
+ out = []
133
+ for name in sorted(p for p in r.stdout.decode("utf-8", "surrogateescape").split("\0") if p):
134
+ if name not in SCAN_FILES and not any(name.startswith(d + "/") for d in SCAN_DIRS):
135
+ continue
136
+ if _excluded(name, Path(name).name):
137
+ continue
138
+ out.append(name)
139
+ return out
140
+
141
+
142
+ def scan_files(root: Path = ROOT) -> dict:
143
+ """返回 {相对路径(posix): {"sha256":…, "size":…}},键已排序。"""
144
+ files: dict[str, dict] = {}
145
+ tracked = _tracked_files(root) # git 仓库:只收被跟踪文件(见 _tracked_files 注释)
146
+ for name in SCAN_FILES:
147
+ p = root / name
148
+ if p.is_file() and (tracked is None or name in tracked):
149
+ sha, size = sha256_file(p)
150
+ files[name] = {"sha256": sha, "size": size}
151
+ for d in SCAN_DIRS:
152
+ base = root / d
153
+ if not base.is_dir():
154
+ continue
155
+ for f in sorted(base.rglob("*")):
156
+ if not f.is_file():
157
+ continue
158
+ rel = f.relative_to(root).as_posix()
159
+ if tracked is not None and rel not in tracked:
160
+ continue
161
+ if _excluded(rel, f.name):
162
+ continue
163
+ sha, size = sha256_file(f)
164
+ files[rel] = {"sha256": sha, "size": size}
165
+ return dict(sorted(files.items()))
166
+
167
+
168
+ def build_manifest(root: Path = ROOT) -> dict:
169
+ version = read_skill_version(root)
170
+ return {"version": version, "files": scan_files(root)}
171
+
172
+
173
+ def check(root: Path = ROOT) -> int:
174
+ mf = root / "manifest.json"
175
+ if not mf.is_file():
176
+ print("[manifest] manifest.json 不存在,先运行 python scripts/make_manifest.py 生成", file=sys.stderr)
177
+ return 1
178
+ cur = build_manifest(root)
179
+ old = json.loads(mf.read_text(encoding="utf-8"))
180
+ old_v = str(old.get("version", ""))
181
+ if old_v != cur["version"]:
182
+ print(f"[manifest] 拒绝:manifest.json version({old_v})与 SKILL.md version"
183
+ f"({cur['version']})不一致。重新运行 python scripts/make_manifest.py。",
184
+ file=sys.stderr)
185
+ return 1
186
+ if old.get("files") != cur["files"]:
187
+ drift = sorted(set(old.get("files") or {}) ^ set(cur["files"]))[:5]
188
+ print(f"[manifest] manifest.json 与工作区不一致(如 {drift})。"
189
+ "重新运行 python scripts/make_manifest.py。", file=sys.stderr)
190
+ return 1
191
+ # 新建文件忘了 git add:清单会静默少收(本地绿、CI 红)。这里直接判红,别等 CI。
192
+ loose = _untracked_candidates(root)
193
+ if loose:
194
+ print(f"[manifest] 拒绝:{len(loose)} 个发布范围内的文件还没 git add,"
195
+ f"清单必然漏收(如 {loose[:3]})。先 git add 再重跑本检查。", file=sys.stderr)
196
+ return 1
197
+ # 覆盖面自检(#73:逐文件比对):发布目录里每个"应发布"的磁盘文件都必须在
198
+ # 清单里;反向清单里也不该有磁盘上不存在的 key。整目录漏扫(如 cordis-plugin
199
+ # 没进 SCAN_DIRS)会让该目录全部文件报"漏",部分漏(10 进 1)也能检出。
200
+ # 只比较"被 git 跟踪"的文件:.gitignore 里的本地草稿不算发布内容(否则本地
201
+ # 检查通过、CI 干净检出必失败,见 #15)。
202
+ tracked = _tracked_files(root)
203
+ for d in SCAN_DIRS:
204
+ base = root / d
205
+ if not base.is_dir():
206
+ continue
207
+ disk = set()
208
+ for f in base.rglob("*"):
209
+ if not f.is_file():
210
+ continue
211
+ rel = f.relative_to(root).as_posix()
212
+ if tracked is not None and rel not in tracked:
213
+ continue
214
+ if _excluded(rel, f.name):
215
+ continue
216
+ disk.add(rel)
217
+ keys = {k for k in cur["files"] if k.startswith(d + "/")}
218
+ missing = sorted(disk - keys)
219
+ extra = sorted(keys - disk)
220
+ if missing or extra:
221
+ if missing:
222
+ print(f"[manifest] 拒绝:{d}/ 下 {len(missing)} 个磁盘文件不在清单(如 {missing[:3]}),"
223
+ "检查 SCAN_DIRS 与排除规则", file=sys.stderr)
224
+ if extra:
225
+ print(f"[manifest] 拒绝:{d}/ 清单里有 {len(extra)} 个磁盘上不存在的文件(如 {extra[:3]})",
226
+ file=sys.stderr)
227
+ return 1
228
+ print(f"[manifest] OK:v{cur['version']},{len(cur['files'])} 个文件哈希全部一致")
229
+ return 0
230
+
231
+
232
+ def build(root: Path = ROOT) -> int:
233
+ data = build_manifest(root)
234
+ out = root / "manifest.json"
235
+ out.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n",
236
+ encoding="utf-8")
237
+ print(f"[manifest] 已生成 {out}:v{data['version']},{len(data['files'])} 个文件")
238
+ loose = _untracked_candidates(root)
239
+ if loose:
240
+ print(f"[manifest] 警告:{len(loose)} 个发布范围内的文件还没 git add,"
241
+ f"本次清单没收它们({loose[:3]}{' …' if len(loose) > 3 else ''})。"
242
+ "git add 之后重新生成一次。", file=sys.stderr)
243
+ return 0
244
+
245
+
246
+ def main(argv: list[str] | None = None) -> int:
247
+ ap = argparse.ArgumentParser(description="灵枢:生成/校验 manifest.json 发布清单")
248
+ ap.add_argument("--check", action="store_true", help="校验现有 manifest 与工作区一致")
249
+ args = ap.parse_args(argv)
250
+ return check() if args.check else build()
251
+
252
+
253
+ if __name__ == "__main__":
254
+ sys.exit(main())
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """打包 AstrBot 插件 zip(#24)。
4
+
5
+ 在仓库根生成 astrbot.zip(.gitignore 已忽略),内容为
6
+ scripts/astrbot_plugin_lingshu/ 整目录(顶层目录名 astrbot_plugin_lingshu/,
7
+ AstrBot 可直接上传安装)。排除 __pycache__、.pyc、运行数据。
8
+
9
+ **打包前会先跑 sync_engine.sync()**(P1-1):engine/ 是根目录 scripts/docs 的
10
+ 副本,两份都在 git 里维护代价太大,正解是"打包时生成、不打进版本库"。所以这里
11
+ 不再假设 engine/ 已就绪,而是每次都从根目录重新铺一遍,杜绝把陈旧副本打进包里。
12
+ 确实需要跳过(比如刚跑过、只想重新压一次)用 `--no-sync`。
13
+
14
+ 用法:python scripts/make_plugin_zip.py [--out astrbot.zip] [--no-sync]
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import sys
21
+ import zipfile
22
+ from pathlib import Path
23
+
24
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
25
+
26
+ REPO = Path(__file__).resolve().parent.parent
27
+ SRC = REPO / "scripts" / "astrbot_plugin_lingshu"
28
+ EXCLUDE_DIRS = {"__pycache__"}
29
+ EXCLUDE_SUFFIX = {".pyc", ".pyo", ".log", ".zip"}
30
+ EXCLUDE_NAMES = {"panel-token.txt", ".home", "consent.json",
31
+ "hippocampus.jsonl", "persona.json", "emotions.jsonl"}
32
+
33
+
34
+ def collect() -> list[Path]:
35
+ files = []
36
+ for p in sorted(SRC.rglob("*")):
37
+ if p.is_dir():
38
+ continue
39
+ if any(part in EXCLUDE_DIRS for part in p.relative_to(SRC).parts):
40
+ continue
41
+ if p.suffix.lower() in EXCLUDE_SUFFIX or p.name in EXCLUDE_NAMES:
42
+ continue
43
+ files.append(p)
44
+ return files
45
+
46
+
47
+ def make(out: Path) -> Path:
48
+ if not SRC.is_dir():
49
+ print(f"[错误] 找不到插件目录:{SRC}", file=sys.stderr)
50
+ raise SystemExit(1)
51
+ files = collect()
52
+ out.parent.mkdir(parents=True, exist_ok=True)
53
+ with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
54
+ for p in files:
55
+ z.write(p, Path("astrbot_plugin_lingshu") / p.relative_to(SRC))
56
+ return out
57
+
58
+
59
+ def main() -> int:
60
+ ap = argparse.ArgumentParser(description="打包 AstrBot 插件 zip")
61
+ ap.add_argument("--out", default=str(REPO / "astrbot.zip"))
62
+ ap.add_argument("--no-sync", action="store_true",
63
+ help="跳过 engine 副本同步(默认打包前会从根目录重新生成)")
64
+ args = ap.parse_args()
65
+ out = Path(args.out).resolve()
66
+ if not args.no_sync:
67
+ try:
68
+ import sync_engine
69
+ if sync_engine.sync() != 0:
70
+ print("[错误] engine 副本同步失败,拒绝打出可能过期的包", file=sys.stderr)
71
+ return 1
72
+ except SystemExit as exc: # sync_engine 里若有 sys.exit
73
+ if exc.code not in (0, None):
74
+ print(f"[错误] engine 同步异常退出:{exc.code}", file=sys.stderr)
75
+ return 1
76
+ except Exception as exc: # noqa: BLE001 绝不让打包静默带着旧副本
77
+ print(f"[错误] engine 同步失败:{type(exc).__name__}: {exc}", file=sys.stderr)
78
+ return 1
79
+ if out.exists():
80
+ out.unlink()
81
+ make(out)
82
+ n = len(collect())
83
+ print(f"OK {out} ({n} files)")
84
+ return 0
85
+
86
+
87
+ if __name__ == "__main__":
88
+ sys.exit(main())
@@ -0,0 +1,242 @@
1
+ # -*- coding: utf-8 -*-
2
+ """跨对话上下文摄取(v3.39 从 memory.py 拆出)。
3
+
4
+ 依赖约定:
5
+ - 可变全局(HOME/锁/原子写/日志)走 `core.*`,不复制值;
6
+ - 需要 memory 的读写(remember/load_all)在调用时取模块,避免导入期循环。
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from pathlib import Path
14
+
15
+ import core
16
+ from core import * # noqa: F401,F403 (now_ts/_num/_cfg_num 等纯函数)
17
+
18
+
19
+ def _mem():
20
+ import memory
21
+ return memory
22
+
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
+