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.
Files changed (135) hide show
  1. package/CHANGELOG.md +2571 -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 +802 -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 +2571 -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 +4850 -0
  60. package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
  61. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2025 -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 +4352 -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 +4850 -0
  99. package/scripts/context_ab.py +260 -0
  100. package/scripts/core.py +2025 -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 +4352 -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,736 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """附录 B · P1:DSH 会话日志导入(多平台入口 + 工作区隔离)。
4
+
5
+ DSH 把一场会话写成:
6
+ <sessions>/<工作区编码目录>/<会话目录>/session.v4.jsonl.zstd
7
+
8
+ 其中有三个必须处理的现实约束:
9
+ 1. 文件是**多帧拼接**的 zstd 容器:每行/每批事件一个独立帧。Node 的
10
+ `zlib.zstdDecompressSync` 一次只解第一帧,直接解整个文件只会拿到
11
+ 313 字节的 header(本机实测)。所以 Node 侧先做「帧结构扫描」再逐帧解压
12
+ (与 DSH 自己 `scanZstdFrames` 的结构扫描逻辑等价),把明文流式写进临时文件。
13
+ 2. 本机系统 Python **没有 zstandard 模块**,因此不把 Python 当解码器。
14
+ 3. 会话事件是 `{"type": "...", "time": 毫秒, "data": {...}}`:
15
+ 只导入 `user/message` / `assistant/message` 里的 text 片段(role/content/ts),
16
+ `reasoning`、`tool-call`、`tool/result`、`system/message`、`command/*` 等
17
+ 非对话条目一律跳过;`user/message` 里 `source.kind` 不是 `user` 的注入块
18
+ (runtime-context / system-reminder)也算系统事件,跳过。
19
+
20
+ 解码优先级(都不静默降级):
21
+ Node 22+(先探测 `node -e "require('node:zlib').zstdDecompressSync"`)
22
+ → 系统 `zstd -d` 命令
23
+ → 抛 DecoderUnavailable(「需要 Node 22+ 或 zstd 命令」)。
24
+
25
+ 导入:`session_rag.ingest_messages(rows, session=会话id, platform="dsh",
26
+ workspace=工作区)`,按内容哈希幂等;解压后的临时文件逐行流式解析,每 500 条
27
+ 批量入库,内存不随文件大小增长(8MB 压缩 / 1 万条事件级别实测可用)。
28
+
29
+ CLI:
30
+ python scripts/session_import.py [--sessions-dir PATH] [--limit N]
31
+ [--workspace 名称] [--dry-run] [--json]
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import json
37
+ import os
38
+ import re
39
+ import shutil
40
+ import subprocess
41
+ import sys
42
+ import tempfile
43
+ import time
44
+ from dataclasses import dataclass
45
+ from pathlib import Path
46
+
47
+ HERE = Path(__file__).resolve().parent
48
+ if str(HERE) not in sys.path: # 允许 `python scripts/session_import.py` 与 tests 直接 import
49
+ sys.path.insert(0, str(HERE))
50
+
51
+ import session_rag # noqa: E402
52
+
53
+ PLATFORM = "dsh"
54
+ BATCH_SIZE = 500
55
+ DEFAULT_TIMEOUT = 600.0 # 单文件解码的最长等待(秒)
56
+
57
+ # 只认 DSH 会话日志:session.v4.jsonl.zstd / session.jsonl / 未来版本号
58
+ _SESSION_LOG_RE = re.compile(r"^session(?:\.v\d+)?\.jsonl(\.zstd)?$", re.IGNORECASE)
59
+
60
+ _NODE_PROBE = (
61
+ "process.exit(typeof require('node:zlib').zstdDecompressSync === 'function' ? 0 : 1)"
62
+ )
63
+ _NODE_VERSION = "process.stdout.write(process.version)"
64
+
65
+ # 多帧 zstd 解码器(Node 22+)。先做与 DSH 相同的帧结构扫描,再逐帧解压并
66
+ # 立刻写盘 —— 不把整份明文同时留在内存里。
67
+ _NODE_DECODE_JS = r"""
68
+ const fs = require('node:fs')
69
+ const zlib = require('node:zlib')
70
+ const src = process.argv[2]
71
+ const dst = process.argv[3]
72
+ const MAGIC = 0xFD2FB528
73
+ const buf = fs.readFileSync(src)
74
+
75
+ // 返回完整帧的结束偏移;遇到文件尾部的不完整帧返回 -1(live 会话正在追加)。
76
+ function frameEnd(buffer, start) {
77
+ if (buffer.length - start < 4) return -1
78
+ if (buffer.readUInt32LE(start) !== MAGIC) {
79
+ throw new Error('corrupt Zstandard session log: invalid frame magic at byte ' + start)
80
+ }
81
+ let off = start + 4
82
+ if (off === buffer.length) return -1
83
+ const descriptor = buffer.readUInt8(off)
84
+ off += 1
85
+ if ((descriptor & 0x18) !== 0) {
86
+ throw new Error('corrupt Zstandard session log: reserved frame-header bit at byte ' + (off - 1))
87
+ }
88
+ const contentSizeFlag = descriptor >>> 6
89
+ const singleSegment = (descriptor & 0x20) !== 0
90
+ const checksum = (descriptor & 0x04) !== 0
91
+ const dictionaryFlag = descriptor & 0x03
92
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
93
+ const contentSizeBytes = contentSizeFlag === 0
94
+ ? (singleSegment ? 1 : 0)
95
+ : (1 << contentSizeFlag)
96
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
97
+ if (buffer.length - off < remainingHeaderBytes) return -1
98
+ off += remainingHeaderBytes
99
+ for (;;) {
100
+ if (buffer.length - off < 3) return -1
101
+ const blockHeader = buffer.readUIntLE(off, 3)
102
+ off += 3
103
+ const lastBlock = (blockHeader & 1) !== 0
104
+ const blockType = (blockHeader >>> 1) & 0x03
105
+ const blockSize = blockHeader >>> 3
106
+ if (blockType === 0x03) {
107
+ throw new Error('corrupt Zstandard session log: reserved block type at byte ' + (off - 3))
108
+ }
109
+ const payloadBytes = blockType === 0x01 ? 1 : blockSize
110
+ if (buffer.length - off < payloadBytes) return -1
111
+ off += payloadBytes
112
+ if (lastBlock) break
113
+ }
114
+ if (checksum) {
115
+ if (buffer.length - off < 4) return -1
116
+ off += 4
117
+ }
118
+ return off
119
+ }
120
+
121
+ const fd = fs.openSync(dst, 'w')
122
+ let frames = 0
123
+ let plainBytes = 0
124
+ let tornBytes = 0
125
+ let offset = 0
126
+ try {
127
+ while (offset < buf.length) {
128
+ const end = frameEnd(buf, offset)
129
+ if (end < 0) {
130
+ tornBytes = buf.length - offset
131
+ break
132
+ }
133
+ const plain = zlib.zstdDecompressSync(buf.subarray(offset, end))
134
+ fs.writeSync(fd, plain)
135
+ plainBytes += plain.length
136
+ frames += 1
137
+ offset = end
138
+ }
139
+ } finally {
140
+ fs.closeSync(fd)
141
+ }
142
+ process.stdout.write(JSON.stringify({
143
+ frames: frames,
144
+ plainBytes: plainBytes,
145
+ tornBytes: tornBytes,
146
+ compressedBytes: buf.length,
147
+ }))
148
+ """
149
+
150
+
151
+ class DecoderUnavailable(RuntimeError):
152
+ """本机既没有可解 zstd 的 Node(22+),也没有 zstd 命令。"""
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class Decoder:
157
+ """已探测通过的 zstd 解码后端。"""
158
+
159
+ backend: str # "node" | "zstd"
160
+ exe: str
161
+ version: str = ""
162
+
163
+
164
+ @dataclass(frozen=True)
165
+ class SessionLog:
166
+ """一个待导入的 DSH 会话日志文件。"""
167
+
168
+ path: Path
169
+ workspace_dir: str # sessions/<工作区编码目录>/
170
+ session_dir: str # sessions/<工作区编码目录>/<会话目录>/
171
+ compressed: bool
172
+
173
+
174
+ def default_sessions_dir() -> Path:
175
+ """DSH 会话根目录:默认 ``~/.dsh/sessions``(尊重 DSH_HOME 自定义安装)。"""
176
+ env_home = str(os.environ.get("DSH_HOME") or "").strip()
177
+ base = Path(env_home) if env_home else (Path.home() / ".dsh")
178
+ return base / "sessions"
179
+
180
+
181
+ # ---------------------------------------------------------------- 解码器探测
182
+
183
+ def _run_quiet(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
184
+ return subprocess.run(cmd, capture_output=True, **kwargs)
185
+
186
+
187
+ def _node_has_zstd(exe: str, timeout: float = 20.0) -> bool:
188
+ """探测指定的 node 是否带 node:zlib zstd(Node 22+ / 23.8+ 才有)。"""
189
+ try:
190
+ rep = _run_quiet([exe, "-e", _NODE_PROBE], timeout=timeout)
191
+ except (OSError, subprocess.SubprocessError):
192
+ return False
193
+ return rep.returncode == 0
194
+
195
+
196
+ def _node_version(exe: str) -> str:
197
+ try:
198
+ rep = _run_quiet([exe, "-e", _NODE_VERSION], timeout=20.0)
199
+ except (OSError, subprocess.SubprocessError):
200
+ return ""
201
+ if rep.returncode != 0:
202
+ return ""
203
+ return rep.stdout.decode("utf-8", "replace").strip()
204
+
205
+
206
+ def _dsh_runtime_node_candidates() -> list[str]:
207
+ """DSH 自带的 Node 运行时(PATH 上没有 node 或不支持 zstd 时兜底)。"""
208
+ roots: list[Path] = []
209
+ env_home = str(os.environ.get("DSH_HOME") or "").strip()
210
+ if env_home:
211
+ roots.append(Path(env_home))
212
+ roots.append(Path.home() / ".dsh")
213
+ out: list[str] = []
214
+ seen: set[str] = set()
215
+ for root in roots:
216
+ try:
217
+ runtimes = sorted((root / "dsh-runtimes").glob("*/dependencies/node/bin"))
218
+ except OSError:
219
+ continue
220
+ for bindir in runtimes:
221
+ for name in ("node.exe", "node"):
222
+ cand = bindir / name
223
+ key = os.path.normcase(str(cand))
224
+ if key in seen:
225
+ continue
226
+ seen.add(key)
227
+ if cand.is_file():
228
+ out.append(str(cand))
229
+ return out
230
+
231
+
232
+ def find_node_exe() -> str | None:
233
+ """返回第一个「node 能解 zstd」的可执行文件;没有则 None。
234
+
235
+ 查找顺序:LINGSHU_NODE 环境变量 → PATH 上的 node → DSH 自带运行时。
236
+ 每个候选都真跑一次 ``node -e`` 探测,不只看版本号猜。
237
+ """
238
+ candidates: list[str] = []
239
+ env_node = str(os.environ.get("LINGSHU_NODE") or "").strip()
240
+ if env_node:
241
+ candidates.append(env_node)
242
+ for name in ("node", "node.exe"):
243
+ found = shutil.which(name)
244
+ if found:
245
+ candidates.append(found)
246
+ candidates.extend(_dsh_runtime_node_candidates())
247
+ seen: set[str] = set()
248
+ for cand in candidates:
249
+ key = os.path.normcase(str(cand))
250
+ if not key or key in seen:
251
+ continue
252
+ seen.add(key)
253
+ if _node_has_zstd(str(cand)):
254
+ return str(cand)
255
+ return None
256
+
257
+
258
+ def find_zstd_exe() -> str | None:
259
+ """系统 zstd CLI(次选解码器)。没有则 None。"""
260
+ for name in ("zstd", "zstd.exe"):
261
+ found = shutil.which(name)
262
+ if found:
263
+ return found
264
+ return None
265
+
266
+
267
+ def detect_decoder(*, node_exe: str | None = None) -> Decoder:
268
+ """确定 zstd 解码后端;两者都没有时抛 DecoderUnavailable(绝不静默)。"""
269
+ if node_exe:
270
+ if not _node_has_zstd(str(node_exe)):
271
+ raise DecoderUnavailable(
272
+ f"指定的 Node 不支持 node:zlib zstd:{node_exe}(需要 Node 22+)")
273
+ return Decoder("node", str(node_exe), _node_version(str(node_exe)))
274
+ node = find_node_exe()
275
+ if node:
276
+ return Decoder("node", node, _node_version(node))
277
+ zstd = find_zstd_exe()
278
+ if zstd:
279
+ return Decoder("zstd", zstd, "")
280
+ raise DecoderUnavailable(
281
+ "需要 Node 22+ 或 zstd 命令:本机既没有能解 zstd 的 Node"
282
+ "(node:zlib.zstdDecompressSync 探测失败,PATH 与 DSH 自带运行时都不行),"
283
+ "也没有 zstd 命令。系统 Python 没有 zstandard 模块,安装 Node 22+ 或 "
284
+ "zstd 后重试;不会静默跳过或假装导入成功。")
285
+
286
+
287
+ # ---------------------------------------------------------------- 会话发现
288
+
289
+ def discover_sessions(sessions_dir=None, *, limit: int | None = None) -> list[SessionLog]:
290
+ """遍历 <sessions>/<工作区>/<会话>/session*.jsonl[.zstd],按修改时间倒序。"""
291
+ root = Path(sessions_dir).expanduser() if sessions_dir else default_sessions_dir()
292
+ if not root.is_dir():
293
+ raise FileNotFoundError(f"DSH 会话目录不存在:{root}")
294
+ logs: list[SessionLog] = []
295
+ try:
296
+ projects = sorted(root.iterdir(), key=lambda p: p.name.lower())
297
+ except OSError as exc:
298
+ raise RuntimeError(f"无法读取会话目录 {root}:{exc}") from exc
299
+ for project in projects:
300
+ if not project.is_dir():
301
+ continue
302
+ try:
303
+ sessions = sorted(project.iterdir(), key=lambda p: p.name.lower())
304
+ except OSError:
305
+ continue
306
+ for sess in sessions:
307
+ if not sess.is_dir():
308
+ continue
309
+ try:
310
+ entries = sorted(sess.iterdir(), key=lambda p: p.name.lower())
311
+ except OSError:
312
+ continue
313
+ for f in entries:
314
+ match = _SESSION_LOG_RE.match(f.name)
315
+ if not match or not f.is_file():
316
+ continue
317
+ logs.append(SessionLog(path=f, workspace_dir=project.name,
318
+ session_dir=sess.name,
319
+ compressed=bool(match.group(1))))
320
+ logs.sort(key=lambda x: _mtime(x.path), reverse=True)
321
+ if limit is not None and int(limit) > 0:
322
+ logs = logs[: int(limit)]
323
+ return logs
324
+
325
+
326
+ def _mtime(path: Path) -> float:
327
+ try:
328
+ return path.stat().st_mtime
329
+ except OSError:
330
+ return 0.0
331
+
332
+
333
+ # ---------------------------------------------------------------- zstd 解码
334
+
335
+ def decode_session_file(src, dst, decoder: Decoder) -> dict:
336
+ """把多帧 zstd 会话日志解成明文 JSONL,写进 dst 临时文件;返回解码元数据。
337
+
338
+ 返回统一 snake_case 键:backend/exe/frames/plain_bytes/compressed_bytes/
339
+ torn_bytes(torn_bytes = 文件尾部不完整的 live 帧字节数,已忽略)。
340
+ """
341
+ src = Path(src)
342
+ dst = Path(dst)
343
+ dst.parent.mkdir(parents=True, exist_ok=True)
344
+ raw = _decode_with_node(src, dst, decoder.exe) if decoder.backend == "node" \
345
+ else _decode_with_zstd_cli(src, dst, decoder.exe)
346
+ meta = {
347
+ "backend": str(raw.get("backend") or decoder.backend),
348
+ "exe": str(raw.get("exe") or decoder.exe),
349
+ "frames": raw.get("frames"),
350
+ "plain_bytes": int(raw.get("plainBytes") if raw.get("plainBytes") is not None
351
+ else raw.get("plain_bytes") or 0),
352
+ "compressed_bytes": int(raw.get("compressedBytes")
353
+ if raw.get("compressedBytes") is not None
354
+ else raw.get("compressed_bytes") or 0),
355
+ "torn_bytes": int(raw.get("tornBytes") if raw.get("tornBytes") is not None
356
+ else raw.get("torn_bytes") or 0),
357
+ }
358
+ if raw.get("warning"):
359
+ meta["warning"] = raw["warning"]
360
+ return meta
361
+
362
+
363
+ def _decode_with_node(src: Path, dst: Path, node_exe: str) -> dict:
364
+ with tempfile.TemporaryDirectory(prefix="lingshu-zstd-js-") as td:
365
+ script = Path(td) / "decode_session.js"
366
+ script.write_text(_NODE_DECODE_JS, encoding="utf-8")
367
+ try:
368
+ rep = subprocess.run([node_exe, str(script), str(src), str(dst)],
369
+ capture_output=True, timeout=DEFAULT_TIMEOUT)
370
+ except subprocess.TimeoutExpired as exc:
371
+ raise RuntimeError(f"Node 解压超时(>{DEFAULT_TIMEOUT:g}s):{src}") from exc
372
+ except OSError as exc:
373
+ raise RuntimeError(f"Node 启动失败({node_exe}):{exc}") from exc
374
+ if rep.returncode != 0:
375
+ err = rep.stderr.decode("utf-8", "replace").strip()
376
+ raise RuntimeError(f"Node 解压失败({src}):{err[:500] or f'rc={rep.returncode}'}")
377
+ try:
378
+ meta = json.loads(rep.stdout.decode("utf-8", "replace") or "{}")
379
+ except ValueError:
380
+ meta = {}
381
+ meta.setdefault("plainBytes", dst.stat().st_size if dst.exists() else 0)
382
+ return meta
383
+
384
+
385
+ def _decode_with_zstd_cli(src: Path, dst: Path, zstd_exe: str) -> dict:
386
+ try:
387
+ with open(dst, "wb") as out:
388
+ rep = subprocess.run([zstd_exe, "-d", "-q", "-c", str(src)],
389
+ stdout=out, stderr=subprocess.PIPE,
390
+ timeout=DEFAULT_TIMEOUT)
391
+ except subprocess.TimeoutExpired as exc:
392
+ raise RuntimeError(f"zstd 解压超时(>{DEFAULT_TIMEOUT:g}s):{src}") from exc
393
+ except OSError as exc:
394
+ raise RuntimeError(f"zstd 启动失败({zstd_exe}):{exc}") from exc
395
+ stderr = (rep.stderr or b"").decode("utf-8", "replace").strip()
396
+ meta = {"frames": None, "torn_bytes": 0,
397
+ "plain_bytes": dst.stat().st_size if dst.exists() else 0,
398
+ "compressed_bytes": src.stat().st_size if src.exists() else 0}
399
+ if rep.returncode != 0:
400
+ # live 会话尾部可能是半帧:zstd CLI 会报错但仍吐出完整帧的明文。
401
+ # 只在明文以换行结尾(最后一帧完整)时接受,否则当失败。
402
+ tail = b""
403
+ if dst.exists() and dst.stat().st_size:
404
+ with open(dst, "rb") as fh:
405
+ fh.seek(max(0, dst.stat().st_size - 1))
406
+ tail = fh.read(1)
407
+ if not tail.endswith(b"\n"):
408
+ raise RuntimeError(f"zstd 解压失败({src}):{stderr[:500] or f'rc={rep.returncode}'}")
409
+ meta["warning"] = f"zstd 返回码 {rep.returncode},已接受以换行结尾的部分输出:{stderr[:200]}"
410
+ return meta
411
+
412
+
413
+ # ---------------------------------------------------------------- JSONL 解析
414
+
415
+ def read_session_header(jsonl_file) -> dict:
416
+ """读解压后 JSONL 的第一条 ``{"type":"session"}``(格式保证是首行,最多扫 64 行)。"""
417
+ try:
418
+ with open(jsonl_file, "r", encoding="utf-8-sig", errors="replace") as fh:
419
+ for _ in range(64):
420
+ line = fh.readline()
421
+ if not line:
422
+ break
423
+ line = line.strip()
424
+ if not line:
425
+ continue
426
+ try:
427
+ event = json.loads(line)
428
+ except ValueError:
429
+ continue
430
+ if isinstance(event, dict) and event.get("type") == "session":
431
+ return event
432
+ except OSError:
433
+ pass
434
+ return {}
435
+
436
+
437
+ def _text_fragments(content) -> str:
438
+ """content 可能是字符串或 block 数组:只取 text 片段(跳过 reasoning/image/tool-*)。"""
439
+ if isinstance(content, str):
440
+ return content.strip()
441
+ if not isinstance(content, list):
442
+ return ""
443
+ parts: list[str] = []
444
+ for block in content:
445
+ if isinstance(block, str):
446
+ if block.strip():
447
+ parts.append(block.strip())
448
+ elif isinstance(block, dict) and block.get("type") == "text":
449
+ text = block.get("text")
450
+ if text is not None and str(text).strip():
451
+ parts.append(str(text).strip())
452
+ return "\n".join(parts)
453
+
454
+
455
+ def _event_to_row(event: dict) -> dict | None:
456
+ """把一条 DSH 会话事件转成 ingest 行;非对话事件(工具/推理/系统)返回 None。"""
457
+ event_type = event.get("type")
458
+ data = event.get("data")
459
+ if not isinstance(data, dict):
460
+ data = {}
461
+ if event_type == "user/message":
462
+ source = data.get("source")
463
+ kind = str((source or {}).get("kind") or "") if isinstance(source, dict) else ""
464
+ if kind and kind != "user":
465
+ return None # runtime-context / system-reminder 等注入块不是用户发言
466
+ text = _text_fragments(data.get("content"))
467
+ role = "user"
468
+ elif event_type == "assistant/message":
469
+ message = data.get("message")
470
+ if not isinstance(message, dict):
471
+ message = {}
472
+ text = _text_fragments(message.get("content"))
473
+ role = "assistant"
474
+ else:
475
+ return None
476
+ if not text:
477
+ return None # 只有 reasoning / 只有 tool-call 的 assistant 轮次
478
+ time_ms = event.get("time")
479
+ ts = float(time_ms) / 1000.0 if isinstance(time_ms, (int, float)) else 0.0
480
+ return {"role": role, "content": text, "ts": ts}
481
+
482
+
483
+ # ---------------------------------------------------------------- 导入
484
+
485
+ def _workspace_matches(want, workspace: str, workspace_dir: str) -> bool:
486
+ """--workspace 匹配:精确路径 / basename / 原始工作区目录名,且允许子串。"""
487
+ wanted = str(want or "").strip()
488
+ if not wanted:
489
+ return True
490
+ low = wanted.lower().rstrip("\\/")
491
+ names = {str(workspace or "").strip().lower().rstrip("\\/"),
492
+ str(workspace_dir or "").strip().lower()}
493
+ if workspace:
494
+ names.add(Path(workspace).name.lower())
495
+ if low in names:
496
+ return True
497
+ for name in names:
498
+ if name and low in name:
499
+ return True
500
+ return False
501
+
502
+
503
+ def import_session_file(log: SessionLog, *, decoder: Decoder, dry_run: bool = False,
504
+ db=None, workspace_filter: str | None = None,
505
+ batch_size: int = BATCH_SIZE) -> dict:
506
+ """解压 → 解析 → 批量入库一个会话文件(解压后的明文只在临时目录存活)。"""
507
+ report: dict = {
508
+ "file": str(log.path),
509
+ "workspace_dir": log.workspace_dir,
510
+ "session_dir": log.session_dir,
511
+ "compressed": log.compressed,
512
+ "session": log.session_dir,
513
+ "workspace": log.workspace_dir,
514
+ "messages": 0,
515
+ "added": 0,
516
+ "skipped": 0,
517
+ "bad_lines": 0,
518
+ "workspace_matched": True,
519
+ "torn_bytes": 0,
520
+ }
521
+ with tempfile.TemporaryDirectory(prefix="lingshu-session-decode-") as td:
522
+ plain = Path(td) / "session.jsonl"
523
+ if log.compressed:
524
+ meta = decode_session_file(log.path, plain, decoder)
525
+ else:
526
+ shutil.copyfile(log.path, plain)
527
+ meta = {"backend": "plain", "frames": None, "torn_bytes": 0,
528
+ "plain_bytes": log.path.stat().st_size, "compressed_bytes": 0}
529
+ report["decode"] = {
530
+ "backend": meta.get("backend"),
531
+ "frames": meta.get("frames"),
532
+ "compressed_bytes": meta.get("compressed_bytes"),
533
+ "plain_bytes": meta.get("plain_bytes"),
534
+ }
535
+ report["torn_bytes"] = int(meta.get("torn_bytes") or 0)
536
+ if meta.get("warning"):
537
+ report["warning"] = meta["warning"]
538
+
539
+ header = read_session_header(plain)
540
+ session_id = str(header.get("id") or "").strip() or log.session_dir
541
+ workspace = str(header.get("cwd") or "").strip() or log.workspace_dir
542
+ report["session"] = session_id
543
+ report["workspace"] = workspace
544
+ if not _workspace_matches(workspace_filter, workspace, log.workspace_dir):
545
+ report["workspace_matched"] = False
546
+ return report
547
+
548
+ parsed = added = skipped = bad_lines = 0
549
+ batch: list[dict] = []
550
+
551
+ def flush() -> None:
552
+ nonlocal added, skipped
553
+ if not batch:
554
+ return
555
+ if not dry_run:
556
+ rep = session_rag.ingest_messages(
557
+ batch, session=session_id, platform=PLATFORM,
558
+ workspace=workspace, path=db)
559
+ added += int(rep.get("added") or 0)
560
+ skipped += int(rep.get("skipped") or 0)
561
+ batch.clear()
562
+
563
+ with open(plain, "r", encoding="utf-8-sig", errors="replace") as fh:
564
+ for line in fh:
565
+ line = line.strip()
566
+ if not line:
567
+ continue
568
+ try:
569
+ event = json.loads(line)
570
+ except ValueError:
571
+ bad_lines += 1
572
+ continue
573
+ if not isinstance(event, dict):
574
+ bad_lines += 1
575
+ continue
576
+ if event.get("type") == "session":
577
+ continue # 首行 header,不是对话
578
+ row = _event_to_row(event)
579
+ if row is None:
580
+ continue
581
+ parsed += 1
582
+ batch.append(row)
583
+ if len(batch) >= max(1, int(batch_size)):
584
+ flush()
585
+ flush()
586
+
587
+ report["messages"] = parsed
588
+ report["bad_lines"] = bad_lines
589
+ if not dry_run:
590
+ report["added"] = added
591
+ report["skipped"] = skipped
592
+ else:
593
+ report["dry_run"] = True
594
+ return report
595
+
596
+
597
+ def import_sessions(sessions_dir=None, *, limit: int | None = None,
598
+ workspace: str | None = None, dry_run: bool = False,
599
+ db=None, decoder: Decoder | None = None) -> dict:
600
+ """遍历导入 DSH 会话目录;返回可 JSON 化的报告。
601
+
602
+ ``limit`` 限制「最终导入的会话数」而不是「扫描的文件数」:工作区过滤在
603
+ 解出会话 header 的 cwd 之后生效,过滤通过的按修改时间倒序取前 N 个。
604
+ """
605
+ started = time.time()
606
+ root = Path(sessions_dir).expanduser() if sessions_dir else default_sessions_dir()
607
+ if not root.is_dir():
608
+ raise FileNotFoundError(f"DSH 会话目录不存在:{root}")
609
+ logs = discover_sessions(root)
610
+ dec = decoder if decoder is not None else detect_decoder()
611
+ max_sessions = int(limit) if limit is not None and int(limit) > 0 else None
612
+ files: list[dict] = []
613
+ totals = {"files": 0, "sessions": 0, "messages": 0, "added": 0, "skipped": 0,
614
+ "bad_lines": 0, "torn_bytes": 0}
615
+ errors = 0
616
+ for log in logs:
617
+ try:
618
+ rep = import_session_file(log, decoder=dec, dry_run=dry_run, db=db,
619
+ workspace_filter=workspace)
620
+ except RuntimeError as exc:
621
+ errors += 1
622
+ files.append({"file": str(log.path), "error": str(exc), "workspace_dir":
623
+ log.workspace_dir, "session_dir": log.session_dir})
624
+ continue
625
+ files.append(rep)
626
+ if not rep.get("workspace_matched", True):
627
+ continue
628
+ totals["files"] += 1
629
+ totals["sessions"] += 1
630
+ totals["messages"] += int(rep.get("messages") or 0)
631
+ totals["added"] += int(rep.get("added") or 0)
632
+ totals["skipped"] += int(rep.get("skipped") or 0)
633
+ totals["bad_lines"] += int(rep.get("bad_lines") or 0)
634
+ totals["torn_bytes"] += int(rep.get("torn_bytes") or 0)
635
+ if max_sessions is not None and totals["files"] >= max_sessions:
636
+ break
637
+ report = {
638
+ "ok": errors == 0,
639
+ "sessions_dir": str(root),
640
+ "workspace_filter": str(workspace or ""),
641
+ "dry_run": bool(dry_run),
642
+ "decoder": {"backend": dec.backend, "exe": dec.exe, "version": dec.version},
643
+ "files": files,
644
+ "totals": totals,
645
+ "errors": errors,
646
+ "elapsed_ms": int(round((time.time() - started) * 1000)),
647
+ }
648
+ if not dry_run:
649
+ try:
650
+ report["db"] = session_rag.stats(path=db)
651
+ except Exception as exc: # noqa: BLE001 - 统计失败不该抹掉导入结果
652
+ report["db"] = {"error": f"{type(exc).__name__}: {exc}"}
653
+ return report
654
+
655
+
656
+ # ---------------------------------------------------------------- CLI
657
+
658
+ def _print_human(report: dict) -> None:
659
+ dec = report.get("decoder") or {}
660
+ version = f" {dec['version']}" if dec.get("version") else ""
661
+ print(f"解码器:{dec.get('backend')}{version}({dec.get('exe')})")
662
+ print(f"会话目录:{report.get('sessions_dir')}")
663
+ if report.get("workspace_filter"):
664
+ print(f"工作区过滤:{report['workspace_filter']}")
665
+ for item in report.get("files") or []:
666
+ if item.get("error"):
667
+ print(f"- [错误] {item.get('session_dir') or item.get('file')}:{item['error']}")
668
+ continue
669
+ if not item.get("workspace_matched", True):
670
+ continue
671
+ tail = f"消息 {item.get('messages', 0)},新增 {item.get('added', 0)}," \
672
+ f"跳过 {item.get('skipped', 0)}"
673
+ if item.get("bad_lines"):
674
+ tail += f",坏行 {item['bad_lines']}"
675
+ if item.get("torn_bytes"):
676
+ tail += f",忽略残帧 {item['torn_bytes']}B"
677
+ if item.get("warning"):
678
+ tail += f",警告:{item['warning'][:120]}"
679
+ print(f"- [{item.get('workspace')}] {item.get('session')}({tail})")
680
+ filtered = sum(1 for item in report.get("files") or []
681
+ if not item.get("error") and not item.get("workspace_matched", True))
682
+ if filtered:
683
+ print(f"(按工作区过滤掉 {filtered} 个会话)")
684
+ totals = report.get("totals") or {}
685
+ suffix = "(dry-run,未写库)" if report.get("dry_run") else ""
686
+ print(f"共 {totals.get('files', 0)} 个会话:解析 {totals.get('messages', 0)} 条,"
687
+ f"新增 {totals.get('added', 0)},跳过 {totals.get('skipped', 0)},"
688
+ f"用时 {report.get('elapsed_ms', 0) / 1000.0:.1f}s{suffix}")
689
+ db = report.get("db")
690
+ if isinstance(db, dict) and not db.get("error"):
691
+ print(f"原文库:{db.get('messages', 0)} 条 / {db.get('sessions', 0)} 场会话"
692
+ f"(platform={db.get('by_platform')})")
693
+
694
+
695
+ def build_parser() -> argparse.ArgumentParser:
696
+ parser = argparse.ArgumentParser(
697
+ prog="session_import.py",
698
+ description="把 DSH 会话日志(多帧 zstd)导入 session_rag 原文库(附录 B · P1)")
699
+ parser.add_argument("--sessions-dir", default="",
700
+ help="DSH 会话根目录,默认 ~/.dsh/sessions")
701
+ parser.add_argument("--limit", type=int, default=0,
702
+ help="最多导入 N 个会话(工作区过滤后按修改时间倒序,0=全部)")
703
+ parser.add_argument("--workspace", default="",
704
+ help="只导入匹配的工作区(路径/basename/目录名,子串匹配)")
705
+ parser.add_argument("--dry-run", action="store_true", help="只解析不写库")
706
+ parser.add_argument("--json", action="store_true", help="输出 JSON 报告")
707
+ return parser
708
+
709
+
710
+ def main(argv=None) -> int:
711
+ args = build_parser().parse_args(argv)
712
+ try:
713
+ report = import_sessions(
714
+ sessions_dir=args.sessions_dir or None,
715
+ limit=args.limit or None,
716
+ workspace=args.workspace or None,
717
+ dry_run=bool(args.dry_run),
718
+ )
719
+ except DecoderUnavailable as exc:
720
+ print(f"[错误] {exc}", file=sys.stderr)
721
+ return 2
722
+ except FileNotFoundError as exc:
723
+ print(f"[错误] {exc}", file=sys.stderr)
724
+ return 2
725
+ except RuntimeError as exc:
726
+ print(f"[错误] 导入失败:{exc}", file=sys.stderr)
727
+ return 1
728
+ if args.json:
729
+ print(json.dumps(report, ensure_ascii=False, indent=2))
730
+ else:
731
+ _print_human(report)
732
+ return 0 if report.get("ok") else 1
733
+
734
+
735
+ if __name__ == "__main__":
736
+ sys.exit(main())