lingshu-skill 0.0.0-stage → 3.79.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 +2571 -0
- package/LICENSE +21 -0
- package/README.md +698 -3
- package/SKILL-lite.md +45 -0
- package/SKILL-tiny.md +37 -0
- package/SKILL.md +379 -0
- package/assets/panel.html +5616 -0
- package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-cron/index.js +4 -0
- package/cordis-plugin/lingshu-cron/package.json +34 -0
- package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
- package/cordis-plugin/lingshu-guard/plugin.js +473 -0
- package/cordis-plugin/lingshu-im/plugin.js +635 -0
- package/cordis-plugin/lingshu-startup/README.md +123 -0
- package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-startup/index.js +4 -0
- package/cordis-plugin/lingshu-startup/package.json +25 -0
- package/cordis-plugin/lingshu-startup/plugin.js +352 -0
- package/cordis.patch.yml +3 -0
- package/docs/commands.md +243 -0
- package/docs/mechanics.md +610 -0
- package/docs/models.md +52 -0
- package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
- package/docs/panel-api.md +198 -0
- package/docs/recovery.md +90 -0
- package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +802 -0
- package/index.js +102 -0
- package/package.json +52 -6
- package/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/_smoke_v299.py +31 -0
- package/scripts/_sync_trae_cn.py +34 -0
- package/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
- package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
- package/scripts/astrbot_plugin_lingshu/README.md +58 -0
- package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2571 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4850 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2025 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4352 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
- package/scripts/astrbot_plugin_lingshu/main.py +703 -0
- package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
- package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
- package/scripts/behavior_baseline.py +280 -0
- package/scripts/bench.py +192 -0
- package/scripts/brain.py +46 -0
- package/scripts/check_pressure_sync.py +55 -0
- package/scripts/check_tag.py +215 -0
- package/scripts/check_version.py +265 -0
- package/scripts/checkpoint.py +165 -0
- package/scripts/cli.py +4850 -0
- package/scripts/context_ab.py +260 -0
- package/scripts/core.py +2025 -0
- package/scripts/dream.py +1137 -0
- package/scripts/emotion.py +1180 -0
- package/scripts/failures.py +107 -0
- package/scripts/fallback_embed.py +114 -0
- package/scripts/growth.py +4745 -0
- package/scripts/growth_parts.py +263 -0
- package/scripts/hooks/pre-commit +18 -0
- package/scripts/hooks/pre-push +20 -0
- package/scripts/insights.py +131 -0
- package/scripts/make_dsh_tgz.py +92 -0
- package/scripts/make_manifest.py +254 -0
- package/scripts/make_plugin_zip.py +88 -0
- package/scripts/mem_dialogue.py +242 -0
- package/scripts/mem_embed.py +159 -0
- package/scripts/mem_lesson.py +160 -0
- package/scripts/mem_score.py +210 -0
- package/scripts/mem_topic.py +177 -0
- package/scripts/memory.py +4352 -0
- package/scripts/npm_prepack.py +31 -0
- package/scripts/panel_build.py +115 -0
- package/scripts/panel_cloud.py +609 -0
- package/scripts/panel_server.py +2703 -0
- package/scripts/panels.py +591 -0
- package/scripts/persona.py +2309 -0
- package/scripts/recreate_push.ps1 +117 -0
- package/scripts/retriever.py +195 -0
- package/scripts/run_tests.py +91 -0
- package/scripts/safety.py +368 -0
- package/scripts/session_import.py +736 -0
- package/scripts/session_rag.py +228 -0
- package/scripts/session_summary.py +123 -0
- package/scripts/summarizer.py +252 -0
- package/scripts/sync_engine.py +139 -0
- package/scripts/update_dsh_copy.ps1 +107 -0
- package/start-panel.bat +60 -0
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""growth.py 的纯计算部分(从 growth.py 拆出)。
|
|
3
|
+
|
|
4
|
+
拆分约束(与 mem_score.py / mem_embed.py 同一套):
|
|
5
|
+
- 只放纯计算:入参是文本/数字/dict,不读盘、不写盘、不依赖 HOME;
|
|
6
|
+
- 需要时间/数值/分词时仍走 brain 命名空间(brain.now_ts / brain._num /
|
|
7
|
+
brain.fmt_date / brain.DAY / brain.terms)——与搬迁前调用的是同一批函数对象,
|
|
8
|
+
语义零变化;
|
|
9
|
+
- brain 不在导入期 import:`import growth` 时 growth.py 末尾的 `from growth_parts
|
|
10
|
+
import *` 可能发生在 brain 初始化过程中(core._recompute_paths 会 import growth),
|
|
11
|
+
导入期再 import brain 会成环并让星号导入拿到半初始化命名空间;所以只在函数调用期
|
|
12
|
+
延迟 import,本模块也不 import growth;
|
|
13
|
+
- growth.py 末尾 `from growth_parts import *`,旧调用面照旧可用。
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
|
|
19
|
+
# 星号导入必须显式列出下划线开头/常量名(growth.py 末尾的 `from growth_parts import *` 依赖它)
|
|
20
|
+
__all__ = [
|
|
21
|
+
# 通用文本与数值
|
|
22
|
+
"_split", "_dedupe", "_clip",
|
|
23
|
+
# 技能名与 SKILL.md 纯文本处理
|
|
24
|
+
"SLUG_RE", "_WINDOWS_RESERVED", "_SKILL_NAME_ALIASES", "_SLUG_TO_LEGACY_NAME",
|
|
25
|
+
"_require_slug", "parse_frontmatter", "_compose",
|
|
26
|
+
# 版本 / 时长 / 连续天数
|
|
27
|
+
"_ver", "_fmt_ago", "_streak",
|
|
28
|
+
# 知识淡出时间窗口
|
|
29
|
+
"FADE_ACTIVE_DAYS", "FADE_DORMANT_DAYS", "_FADE_PENALTY", "_FADE_MARK",
|
|
30
|
+
"_protected_knowledge", "knowledge_fade_phase",
|
|
31
|
+
# 知识文档词袋与生成物识别
|
|
32
|
+
"_kdoc", "_LEGACY_AGENTS_SIGNATURE", "_looks_generated",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------- 通用文本与数值(纯计算,无 IO)
|
|
37
|
+
|
|
38
|
+
def _split(text: str | None) -> list:
|
|
39
|
+
if not text:
|
|
40
|
+
return []
|
|
41
|
+
return [x.strip() for x in re.split(r"[、,,;;\n/|]+", text) if x.strip()]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _dedupe(items: list) -> list:
|
|
45
|
+
out, seen = [], set()
|
|
46
|
+
for x in items:
|
|
47
|
+
x = str(x).strip()
|
|
48
|
+
if x and x not in seen:
|
|
49
|
+
seen.add(x)
|
|
50
|
+
out.append(x)
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _clip(text: str, n: int) -> str:
|
|
55
|
+
text = re.sub(r"\s+", " ", (text or "").strip())
|
|
56
|
+
return text if len(text) <= n else text[:n].rstrip() + "…"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---------------------------------------------------------------- 技能名与 SKILL.md 文本处理(纯字符串,不碰盘)
|
|
60
|
+
|
|
61
|
+
# 技能名:小写字母/数字/连字符/下划线,也允许中文(中文生态里技能就叫「质检评审」这类名字)
|
|
62
|
+
SLUG_RE = re.compile(r"^[a-z0-9\u4e00-\u9fff][a-z0-9-_\u4e00-\u9fff]{0,62}$")
|
|
63
|
+
# Windows 保留设备名:即使过了正则也不能当技能目录名(con/com1 建目录会失败或异常)
|
|
64
|
+
_WINDOWS_RESERVED = {"con", "prn", "aux", "nul",
|
|
65
|
+
*(f"com{i}" for i in range(1, 10)),
|
|
66
|
+
*(f"lpt{i}" for i in range(1, 10))}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# 中文显示名 → kebab-case 目录名。DSH 的文件系统技能发现只认 kebab-case 的 name,
|
|
70
|
+
# 中文名会被静默跳过(装完像"改名"或干脆不出现),所以装/查/删都统一折算成英文 slug。
|
|
71
|
+
_SKILL_NAME_ALIASES = {
|
|
72
|
+
"灵枢": "lingshu",
|
|
73
|
+
"灵枢-lite": "lingshu-lite",
|
|
74
|
+
"灵枢-tiny": "lingshu-tiny",
|
|
75
|
+
}
|
|
76
|
+
# 反查:kebab slug → 它对应的旧中文目录名(旧版安装会把中文名当目录名)
|
|
77
|
+
_SLUG_TO_LEGACY_NAME = {v: k for k, v in _SKILL_NAME_ALIASES.items()}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _require_slug(name: str) -> str:
|
|
81
|
+
# 统一归一化:大小写、空格、下划线都折算成连字符,保证 new / show / rm 用同一个名字都能找到
|
|
82
|
+
name = (name or "").strip().lower().replace(" ", "-").replace("_", "-")
|
|
83
|
+
name = _SKILL_NAME_ALIASES.get(name, name) # 中文名折算成 kebab-case(DSH 才认)
|
|
84
|
+
if not SLUG_RE.match(name):
|
|
85
|
+
raise ValueError("技能名不合法:只能用字母/数字/连字符/下划线/中文,1-63 个字符")
|
|
86
|
+
if name in _WINDOWS_RESERVED: # con/com1 这类设备名在 Windows 上建目录会失败
|
|
87
|
+
raise ValueError(f"技能名不能用 Windows 保留设备名:{name}")
|
|
88
|
+
return name
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_frontmatter(text: str) -> tuple:
|
|
92
|
+
"""解析 YAML frontmatter。纯标准库,不引 yaml 依赖。
|
|
93
|
+
|
|
94
|
+
支持:单行 key: value、引号包裹、块标量(| 保留换行 / > 折叠为空格)、
|
|
95
|
+
以及常见简写(值里含冒号、以 # 开头)。够读 DSH / Claude / Trae 各家的 SKILL.md。
|
|
96
|
+
"""
|
|
97
|
+
text = text.lstrip("\ufeff")
|
|
98
|
+
if not text.startswith("---"):
|
|
99
|
+
return {}, text
|
|
100
|
+
# 闭界必须是整行 "---"(行尾可带空白):裸 find("\n---") 会把正文里
|
|
101
|
+
# "---xxx" 这类行误当边界,导致 head 被提前截断
|
|
102
|
+
m = re.search(r"\n---[ \t]*(?:\n|$)", text)
|
|
103
|
+
if m is None or m.start() < 3:
|
|
104
|
+
return {}, text
|
|
105
|
+
end = m.start()
|
|
106
|
+
head = text[3:end]
|
|
107
|
+
body = text[m.end():].lstrip("\n")
|
|
108
|
+
|
|
109
|
+
meta = {}
|
|
110
|
+
lines = head.splitlines()
|
|
111
|
+
i = 0
|
|
112
|
+
while i < len(lines):
|
|
113
|
+
line = lines[i]
|
|
114
|
+
if not line.strip() or line.lstrip().startswith("#"):
|
|
115
|
+
i += 1
|
|
116
|
+
continue
|
|
117
|
+
if ":" not in line:
|
|
118
|
+
i += 1
|
|
119
|
+
continue
|
|
120
|
+
key, val = line.split(":", 1)
|
|
121
|
+
key = key.strip()
|
|
122
|
+
val = val.strip()
|
|
123
|
+
if val in ("|", ">", "|-", ">-", "|+", ">+"):
|
|
124
|
+
# 块标量:收集后续缩进行
|
|
125
|
+
block, j = [], i + 1
|
|
126
|
+
while j < len(lines):
|
|
127
|
+
nxt = lines[j]
|
|
128
|
+
if nxt.strip() and not nxt.startswith((" ", "\t")):
|
|
129
|
+
break
|
|
130
|
+
block.append(nxt.strip())
|
|
131
|
+
j += 1
|
|
132
|
+
sep = "\n" if val.startswith("|") else " "
|
|
133
|
+
meta[key] = sep.join(x for x in block if x)
|
|
134
|
+
i = j
|
|
135
|
+
continue
|
|
136
|
+
if len(val) >= 2 and val[0] == val[-1] and val[0] in ("'", '"'):
|
|
137
|
+
val = val[1:-1]
|
|
138
|
+
meta[key] = val
|
|
139
|
+
i += 1
|
|
140
|
+
return meta, body
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _compose(name: str, description: str, body: str, version: int, created: str, updated: str,
|
|
144
|
+
origin: str = "灵枢") -> str:
|
|
145
|
+
description = re.sub(r"\s+", " ", description).strip()
|
|
146
|
+
return (
|
|
147
|
+
"---\n"
|
|
148
|
+
f"name: {name}\n"
|
|
149
|
+
f"description: {description}\n"
|
|
150
|
+
f"origin: {origin}\n"
|
|
151
|
+
f"version: {version}\n"
|
|
152
|
+
f"created: {created}\n"
|
|
153
|
+
f"updated: {updated}\n"
|
|
154
|
+
"---\n\n"
|
|
155
|
+
+ body.strip() + "\n"
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# ---------------------------------------------------------------- 版本 / 时长 / 连续天数换算(纯计算)
|
|
160
|
+
|
|
161
|
+
def _ver(v) -> object:
|
|
162
|
+
"""版本号容错:自建技能是自增整数,本体是语义化版本(2.11.2)。
|
|
163
|
+
直接 int('2.11.2') 会抛 ValueError 把 skill list 整个搞崩,这里退化成原串。"""
|
|
164
|
+
try:
|
|
165
|
+
return int(v)
|
|
166
|
+
except (TypeError, ValueError):
|
|
167
|
+
return str(v or "1").strip() or "1"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _fmt_ago(secs: float) -> str:
|
|
171
|
+
import brain # 延迟导入:导入期成环风险见模块 docstring
|
|
172
|
+
secs = max(0.0, secs) # 系统时钟回拨/last 写了未来时间时会出现负数,钳为 0
|
|
173
|
+
if secs < 3600:
|
|
174
|
+
return f"{secs / 60:.0f} 分钟"
|
|
175
|
+
if secs < brain.DAY:
|
|
176
|
+
return f"{secs / 3600:.1f} 小时".replace(".0", "")
|
|
177
|
+
return f"{secs / brain.DAY:.1f} 天".replace(".0", "")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _streak(days: set) -> int:
|
|
181
|
+
import brain # 延迟导入:导入期成环风险见模块 docstring
|
|
182
|
+
n = 0
|
|
183
|
+
for i in range(0, 3650):
|
|
184
|
+
d = brain.fmt_date(brain.now_ts() - i * brain.DAY)
|
|
185
|
+
if d in days:
|
|
186
|
+
n += 1
|
|
187
|
+
elif i == 0:
|
|
188
|
+
continue
|
|
189
|
+
else:
|
|
190
|
+
break
|
|
191
|
+
return n
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ---------------------------------------------------------------- 知识淡出时间窗口(按 updated 距今换算相位,纯计算)
|
|
195
|
+
|
|
196
|
+
# 知识淡出分层(借鉴 Mnemosyne/大肥鱼 memory_policy 的 detail→gist→dormant 三相):
|
|
197
|
+
# 分层不写入、不删原文,检索/展示时按 updated 距今实时计算相位——
|
|
198
|
+
# active 活跃:30 天内动过(更新或验证),正常检索;
|
|
199
|
+
# fading 淡出:30–180 天,检索降权,正文展示截短(细节淡出,概要与来源保留);
|
|
200
|
+
# dormant 休眠:>180 天,默认检索跳过;关键词仍能命中但只给标题线索,
|
|
201
|
+
# 看原文走 knowledge show <id>(对应"ID 可查原始证据")。
|
|
202
|
+
# 豁免(始终 active,对应 protected):pinned 置顶、E4/E3 已验证铁律——
|
|
203
|
+
# 这些条目代表"重要或反复被证实",不该因为没人提就沉底。
|
|
204
|
+
FADE_ACTIVE_DAYS = 30
|
|
205
|
+
FADE_DORMANT_DAYS = 180
|
|
206
|
+
_FADE_PENALTY = 0.03 # fading 相位检索降权:淡出的结论该让位给新鲜说法
|
|
207
|
+
|
|
208
|
+
_FADE_MARK = {"active": "🌱", "fading": "🍂", "dormant": "💤"}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _protected_knowledge(rec: dict) -> bool:
|
|
212
|
+
return bool(rec.get("pinned")) or rec.get("evidence_level") in ("E3", "E4")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def knowledge_fade_phase(rec: dict, now: float | None = None) -> str:
|
|
216
|
+
"""计算一条知识的淡出相位:active / fading / dormant。只读,不写盘。"""
|
|
217
|
+
import brain # 延迟导入:导入期成环风险见模块 docstring
|
|
218
|
+
if _protected_knowledge(rec):
|
|
219
|
+
return "active"
|
|
220
|
+
ts = brain._num(rec.get("updated"), 0) or brain._num(rec.get("created"), 0)
|
|
221
|
+
if ts <= 0:
|
|
222
|
+
return "active" # 时间不明的条目不推测新鲜程度(借鉴 memory_policy 对 unknown 的处理)
|
|
223
|
+
days = (now if now is not None else brain.now_ts()) - ts
|
|
224
|
+
if days < FADE_ACTIVE_DAYS * 86400:
|
|
225
|
+
return "active"
|
|
226
|
+
if days < FADE_DORMANT_DAYS * 86400:
|
|
227
|
+
return "fading"
|
|
228
|
+
return "dormant"
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# ---------------------------------------------------------------- 知识文档词袋与生成物识别(纯字符串)
|
|
232
|
+
|
|
233
|
+
def _kdoc(rec: dict) -> set:
|
|
234
|
+
import brain # 延迟导入:导入期成环风险见模块 docstring
|
|
235
|
+
# 字段可能是 None(手改/LLM 产出),统一转成字符串再切词,避免 " ".join 抛 TypeError
|
|
236
|
+
def _s(x):
|
|
237
|
+
return str(x) if x is not None else ""
|
|
238
|
+
return brain.terms(" ".join([
|
|
239
|
+
_s(rec.get("title")) * 2, _s(rec.get("body")),
|
|
240
|
+
" ".join(_s(p) for p in (rec.get("points") or [])),
|
|
241
|
+
" ".join(_s(t) for t in (rec.get("tags") or [])),
|
|
242
|
+
]))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# 旧版(无区块标记)生成文件的可识别签名:命中说明整文件都是灵枢生成的,没有用户手写内容
|
|
246
|
+
_LEGACY_AGENTS_SIGNATURE = "由灵枢在全局化时生成"
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _looks_generated(text: str) -> bool:
|
|
250
|
+
"""旧版无标记文件是否「整份都是灵枢生成的」——只有这样才能安全整体替换。
|
|
251
|
+
任何一行不属于生成结构,就说明用户手写过,必须保留。"""
|
|
252
|
+
if _LEGACY_AGENTS_SIGNATURE not in text:
|
|
253
|
+
return False
|
|
254
|
+
for line in text.splitlines():
|
|
255
|
+
s = line.strip()
|
|
256
|
+
if not s:
|
|
257
|
+
continue
|
|
258
|
+
if (s.startswith("#") or s.startswith("**何时用**") or s.startswith("**怎么用**")
|
|
259
|
+
or s.startswith("**入口**") or s.startswith("**来源**") or s.startswith("**版本**")
|
|
260
|
+
or _LEGACY_AGENTS_SIGNATURE in s):
|
|
261
|
+
continue
|
|
262
|
+
return False
|
|
263
|
+
return True
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""面板「运行洞察」聚合(只读、全部 fail-open)。
|
|
4
|
+
|
|
5
|
+
一次请求返回面板需要的小结:版本 / 上下文账单 / 原文检索库 / 收尾清点 /
|
|
6
|
+
群聊鉴权 / 嵌入状态 / A/B 灰度样本。任何一块失败只降级该块并记 warning,
|
|
7
|
+
不影响其余。
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _root() -> Path:
|
|
17
|
+
return Path(__file__).resolve().parent.parent
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _version() -> str:
|
|
21
|
+
for cand, pat in (("SKILL.md", "version:"), ("package.json", '"version"')):
|
|
22
|
+
try:
|
|
23
|
+
for line in (_root() / cand).read_text(encoding="utf-8").splitlines():
|
|
24
|
+
if pat in line:
|
|
25
|
+
return line.split(pat, 1)[1].strip().strip('":, ').strip()
|
|
26
|
+
except OSError:
|
|
27
|
+
continue
|
|
28
|
+
return ""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _context() -> dict:
|
|
32
|
+
import memory
|
|
33
|
+
rep: dict = {}
|
|
34
|
+
memory.build_injection(report=rep)
|
|
35
|
+
secs = sorted((s for s in rep.get("sections") or []),
|
|
36
|
+
key=lambda s: -int(s.get("chars") or 0))[:3]
|
|
37
|
+
return {"total_tokens": rep.get("total_tokens"), "total_chars": rep.get("total_chars"),
|
|
38
|
+
"budget": rep.get("budget"), "top": secs}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _rag() -> dict:
|
|
42
|
+
import session_rag
|
|
43
|
+
return session_rag.stats()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _checkpoints() -> dict:
|
|
47
|
+
import checkpoint
|
|
48
|
+
st = checkpoint._load_state()
|
|
49
|
+
items = [(k, v) for k, v in st.items() if isinstance(v, dict)]
|
|
50
|
+
items.sort(key=lambda kv: -int(kv[1].get("ts") or 0))
|
|
51
|
+
return {"count": len(items),
|
|
52
|
+
"last": ({"repo": Path(k).name, "head": v.get("head"),
|
|
53
|
+
"ts": v.get("ts"), "version": v.get("version")}
|
|
54
|
+
if items else None)}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _guard() -> dict:
|
|
58
|
+
import core
|
|
59
|
+
cfg = core.load_config()
|
|
60
|
+
g = cfg.get("guard") or {}
|
|
61
|
+
out = {"enabled": g.get("enabled", True) is not False,
|
|
62
|
+
"shadow": g.get("shadow", True) is not False,
|
|
63
|
+
"events": []}
|
|
64
|
+
try:
|
|
65
|
+
log = Path(core.HOME) / "lingshu-guard.log"
|
|
66
|
+
lines = log.read_text(encoding="utf-8", errors="replace").splitlines()[-5:]
|
|
67
|
+
for line in lines:
|
|
68
|
+
try:
|
|
69
|
+
out["events"].append(json.loads(line))
|
|
70
|
+
except ValueError:
|
|
71
|
+
continue
|
|
72
|
+
except OSError:
|
|
73
|
+
pass
|
|
74
|
+
return out
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _embed() -> dict:
|
|
78
|
+
import core
|
|
79
|
+
cfg = core.load_config()
|
|
80
|
+
emb = cfg.get("embed") or {}
|
|
81
|
+
left = max(0, int(core._EMBED_DOWN_UNTIL - time.time())) if getattr(core, "_EMBED_DOWN_UNTIL", 0) else 0
|
|
82
|
+
return {"url": str(emb.get("url") or ""), "model": str(emb.get("model") or ""),
|
|
83
|
+
"cooldown_sec": left}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _failures() -> dict:
|
|
87
|
+
import failures
|
|
88
|
+
return failures.summarize(1)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _ab() -> dict:
|
|
92
|
+
"""P4 灰度 A/B 采样小结:只读 metrics.jsonl,无样本时 total=0。
|
|
93
|
+
|
|
94
|
+
面板只关心「最近 7 天省了多少、当前跑哪个模式」,所以这里把
|
|
95
|
+
context_ab.summary() 的三段分位数裁成 p50/p95,并附上
|
|
96
|
+
config.context_mode。summary 本身不写盘,失败由 build() 统一降级。
|
|
97
|
+
"""
|
|
98
|
+
import context_ab
|
|
99
|
+
s = context_ab.summary(7)
|
|
100
|
+
return {"total": int(s.get("total") or 0),
|
|
101
|
+
"mean_saved_pct": s.get("mean_saved_pct"),
|
|
102
|
+
"p50": s.get("p50_saved_pct"),
|
|
103
|
+
"p95": s.get("p95_saved_pct"),
|
|
104
|
+
"by_mode": s.get("by_mode") or {},
|
|
105
|
+
"mode": context_ab.context_mode()}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def build(light: bool = False) -> dict:
|
|
109
|
+
"""light=True 跳过最重的上下文账单(面板自动刷新时用)。
|
|
110
|
+
|
|
111
|
+
A/B 样本块只有一次 512KB 上限的小文件读,不进 light 跳过名单:
|
|
112
|
+
面板自动刷新走 light=1,跳了它「A/B 样本」这行就永远是空的。
|
|
113
|
+
"""
|
|
114
|
+
warnings = []
|
|
115
|
+
data = {"version": _version()}
|
|
116
|
+
for name, fn in (("context", _context), ("rag", _rag), ("checkpoints", _checkpoints),
|
|
117
|
+
("guard", _guard), ("embed", _embed), ("failures", _failures),
|
|
118
|
+
("ab", _ab)):
|
|
119
|
+
if name == "context" and light:
|
|
120
|
+
continue
|
|
121
|
+
try:
|
|
122
|
+
data[name] = fn()
|
|
123
|
+
except Exception as exc: # noqa: BLE001
|
|
124
|
+
warnings.append(f"{name}: {type(exc).__name__}: {exc}")
|
|
125
|
+
data[name] = None
|
|
126
|
+
try:
|
|
127
|
+
import failures
|
|
128
|
+
failures.record("insights." + name, f"{type(exc).__name__}: {exc}")
|
|
129
|
+
except Exception:
|
|
130
|
+
pass
|
|
131
|
+
return {"ok": True, "ts": int(time.time()), "data": data, "warnings": warnings}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""打 DSH 可安装 tgz(tgz 直链方案)。
|
|
4
|
+
|
|
5
|
+
产物 lingshu-skill-<version>.tgz 符合 npm/pnpm tgz 结构(顶层 package/),
|
|
6
|
+
DSH 读 package.json 的 dsh.bundle.patch 挂载插件。与 git 源码安装的区别:
|
|
7
|
+
pnpm 下载 tgz 解压即可,**不需要 git、不需要 clone GitHub**——给网络受限
|
|
8
|
+
(国内 GitHub ECONNREFUSED / 没装 git)的用户直接装。
|
|
9
|
+
|
|
10
|
+
打包前先跑 sync_engine.sync(),把 engine/ 副本从根 scripts/docs 生成出来
|
|
11
|
+
(engine/ 已从 git 移除、不入库,但插件运行需要它),确保 tgz 不是空壳。
|
|
12
|
+
打包内容在 manifest.json 的发布文件基础上 **额外包含整个 engine/ 目录**,
|
|
13
|
+
排除 __pycache__/.pyc/本地运行数据。
|
|
14
|
+
|
|
15
|
+
用法:python scripts/make_dsh_tgz.py [--out <路径>]
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import io
|
|
21
|
+
import json
|
|
22
|
+
import sys
|
|
23
|
+
import tarfile
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
27
|
+
sys.path.insert(0, str(ROOT / "scripts"))
|
|
28
|
+
|
|
29
|
+
EXCLUDE_PARTS = {"__pycache__", ".git", "node_modules", "downloads", "verbatim"}
|
|
30
|
+
EXCLUDE_SUFFIX = {".pyc", ".pyo", ".log", ".zip", ".tgz", ".jsonl", ".tmp"}
|
|
31
|
+
EXCLUDE_NAMES = {"panel-token.txt", ".env", "LINGSHU_PANEL_TOKEN", "config.json"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def collect() -> list[Path]:
|
|
35
|
+
"""manifest 发布文件 + engine/ 全目录(都要先 sync 生成)。"""
|
|
36
|
+
# manifest.json 里的发布文件(git 跟踪的核心文件)
|
|
37
|
+
manifest = json.loads((ROOT / "manifest.json").read_text(encoding="utf-8"))
|
|
38
|
+
files = [ROOT / rel for rel in manifest["files"]]
|
|
39
|
+
# engine/ 派生副本(打包时生成,不入库)
|
|
40
|
+
engine = ROOT / "scripts" / "astrbot_plugin_lingshu" / "engine"
|
|
41
|
+
if engine.is_dir():
|
|
42
|
+
for p in engine.rglob("*"):
|
|
43
|
+
if p.is_file():
|
|
44
|
+
files.append(p)
|
|
45
|
+
# 去重 + 过滤
|
|
46
|
+
out, seen = [], set()
|
|
47
|
+
for p in files:
|
|
48
|
+
rel = p.relative_to(ROOT).as_posix()
|
|
49
|
+
if rel in seen or not p.is_file():
|
|
50
|
+
continue
|
|
51
|
+
if any(part in EXCLUDE_PARTS for part in p.relative_to(ROOT).parts):
|
|
52
|
+
continue
|
|
53
|
+
if p.suffix.lower() in EXCLUDE_SUFFIX or p.name in EXCLUDE_NAMES:
|
|
54
|
+
continue
|
|
55
|
+
seen.add(rel)
|
|
56
|
+
out.append(p)
|
|
57
|
+
return sorted(out, key=lambda p: p.relative_to(ROOT).as_posix())
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def make(out: Path) -> Path:
|
|
61
|
+
import sync_engine
|
|
62
|
+
if sync_engine.sync() != 0:
|
|
63
|
+
raise SystemExit("[错误] engine 副本同步失败,拒绝打空壳包")
|
|
64
|
+
files = collect()
|
|
65
|
+
pkg = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))
|
|
66
|
+
version = pkg["version"]
|
|
67
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
# npm tgz:gzip + 顶层 package/ 目录 + pax headers
|
|
69
|
+
with tarfile.open(out, "w:gz", format=tarfile.PAX_FORMAT) as tf:
|
|
70
|
+
for p in files:
|
|
71
|
+
rel = "package/" + p.relative_to(ROOT).as_posix()
|
|
72
|
+
info = tf.gettarinfo(str(p), arcname=rel)
|
|
73
|
+
info.uid = info.gid = 0
|
|
74
|
+
info.uname = info.gname = ""
|
|
75
|
+
info.mtime = 0
|
|
76
|
+
with p.open("rb") as fh:
|
|
77
|
+
tf.addfile(info, fh)
|
|
78
|
+
print(f"[tgz] {out} v{version} {len(files)} 文件 {out.stat().st_size/1024:.0f} KB")
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def main() -> int:
|
|
83
|
+
ap = argparse.ArgumentParser(description="打 DSH 可安装 tgz(tgz 直链方案)")
|
|
84
|
+
ver = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))["version"]
|
|
85
|
+
ap.add_argument("--out", default=str(ROOT / f"lingshu-skill-{ver}.tgz"))
|
|
86
|
+
args = ap.parse_args()
|
|
87
|
+
make(Path(args.out).resolve())
|
|
88
|
+
return 0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
sys.exit(main())
|