dsh-session-detox 0.0.0-stage → 0.3.2

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/lib/find.js ADDED
@@ -0,0 +1,187 @@
1
+ // 按名字找会话:先查 bili 账本的 sessions 表(title / host_title 都是现成的),
2
+ // 账本里没有的再退回读会话文件开头几帧的首条用户消息。返回 id + 标题 + 体积 + 空闲秒数。
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import zlib from 'node:zlib';
6
+ import { DatabaseSync } from 'node:sqlite';
7
+
8
+ import { BILI_DB, SESSIONS_ROOT } from './paths.js';
9
+
10
+ const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
11
+ const HEAD_BYTES = 1 << 20;
12
+
13
+ /** 磁盘上所有会话:uuid → { dir, file, size, mtime }。 */
14
+ function indexDisk() {
15
+ const out = new Map();
16
+ if (!fs.existsSync(SESSIONS_ROOT)) return out;
17
+ const workspaces = fs.readdirSync(SESSIONS_ROOT, { withFileTypes: true }).filter((d) => d.isDirectory());
18
+ for (const ws of workspaces) {
19
+ const base = path.join(SESSIONS_ROOT, ws.name);
20
+ let entries = [];
21
+ try {
22
+ entries = fs.readdirSync(base, { withFileTypes: true });
23
+ } catch {
24
+ continue;
25
+ }
26
+ for (const e of entries) {
27
+ if (!e.isDirectory()) continue;
28
+ // 目录名可能是 session-<uuid>,也可能就是 <uuid>
29
+ const id = e.name.startsWith('session-') ? e.name.slice('session-'.length) : e.name;
30
+ if (!/^[0-9a-f-]{36}$/.test(id)) continue;
31
+ const dir = path.join(base, e.name);
32
+ const file = path.join(dir, 'session.v4.jsonl.zstd');
33
+ let st;
34
+ try {
35
+ st = fs.statSync(file);
36
+ } catch {
37
+ continue;
38
+ }
39
+ out.set(id, { dir, file, size: st.size, mtime: st.mtimeMs });
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /** 账本里的标题:uuid → { title, host, updatedAt }。没有账本就返回空。 */
46
+ function indexDb() {
47
+ const out = new Map();
48
+ if (!fs.existsSync(BILI_DB)) return out;
49
+ let db;
50
+ try {
51
+ db = new DatabaseSync(BILI_DB);
52
+ const rows = db.prepare('select session_id, title, host_title, updated_at from sessions').all();
53
+ for (const r of rows) {
54
+ const id = String(r.session_id || '').replace(/^session-/, '');
55
+ if (!id) continue;
56
+ out.set(id, { title: r.title || '', host: r.host_title || '', updatedAt: Number(r.updated_at) || 0 });
57
+ }
58
+ } catch {
59
+ // 账本被占用或表结构变了:不致命,只是没有标题可用
60
+ } finally {
61
+ try {
62
+ db?.close();
63
+ } catch {
64
+ /* ignore */
65
+ }
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /** 只读文件开头一段,够解前几帧。 */
71
+ function headSlice(file) {
72
+ const fd = fs.openSync(file, 'r');
73
+ try {
74
+ const buf = Buffer.alloc(HEAD_BYTES);
75
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
76
+ return buf.subarray(0, n);
77
+ } finally {
78
+ fs.closeSync(fd);
79
+ }
80
+ }
81
+
82
+ function textOf(content) {
83
+ if (typeof content === 'string') return content;
84
+ if (Array.isArray(content)) {
85
+ return content.map((x) => (typeof x === 'string' ? x : x?.text || '')).join(' ');
86
+ }
87
+ return '';
88
+ }
89
+
90
+ /** 会话文件里第一条用户消息的开头(账本没标题时的兜底)。 */
91
+ function firstUserText(file) {
92
+ let buf;
93
+ try {
94
+ buf = headSlice(file);
95
+ } catch {
96
+ return '';
97
+ }
98
+ const offs = [];
99
+ let i = 0;
100
+ for (;;) {
101
+ const j = buf.indexOf(MAGIC, i);
102
+ if (j < 0) break;
103
+ offs.push(j);
104
+ i = j + 4;
105
+ }
106
+ if (!offs.length) return '';
107
+ const parts = [];
108
+ for (let k = 0; k < Math.min(offs.length, 3); k++) {
109
+ const end = k + 1 < offs.length ? offs[k + 1] : buf.length;
110
+ try {
111
+ parts.push(zlib.zstdDecompressSync(buf.subarray(offs[k], end)).toString('utf8'));
112
+ } catch {
113
+ break;
114
+ }
115
+ }
116
+ for (const line of parts.join('').split('\n')) {
117
+ if (!line.trim()) continue;
118
+ let ev;
119
+ try {
120
+ ev = JSON.parse(line);
121
+ } catch {
122
+ continue;
123
+ }
124
+ if (ev.type === 'user/message') {
125
+ const t = textOf(ev.data?.content).replace(/\s+/g, ' ').trim();
126
+ if (t) return t;
127
+ }
128
+ }
129
+ return '';
130
+ }
131
+
132
+ /**
133
+ * 按名字找会话。query 为空时列出最近的若干条。
134
+ * @param {string} [query] 会话名关键词(子串,不区分大小写),也可以是 id 前缀
135
+ * @param {number} [limit=10]
136
+ */
137
+ export function findSessions(query = '', limit = 10) {
138
+ const q = String(query || '').trim().toLowerCase();
139
+ const disk = indexDisk();
140
+ const db = indexDb();
141
+ const rows = [];
142
+
143
+ for (const [id, d] of disk) {
144
+ const meta = db.get(id);
145
+ let title = meta?.title || '';
146
+ let host = meta?.host || '';
147
+ if (!title && !host && q) {
148
+ title = firstUserText(d.file);
149
+ }
150
+ rows.push({
151
+ id,
152
+ host,
153
+ title,
154
+ sizeBytes: d.size,
155
+ idleSec: Math.max(0, Math.round((Date.now() - d.mtime) / 1000)),
156
+ inDb: Boolean(meta),
157
+ });
158
+ }
159
+
160
+ let picked = rows;
161
+ if (q) {
162
+ picked = rows.filter((r) => {
163
+ const hay = `${r.id} ${r.host} ${r.title}`.toLowerCase();
164
+ return hay.includes(q) || r.id.startsWith(q);
165
+ });
166
+ }
167
+
168
+ // host 命中优先(那是鱼的名字),其次标题,最后才是 id;同组按最近活跃排。
169
+ const score = (r) => {
170
+ if (!q) return 0;
171
+ if (r.host.toLowerCase().includes(q)) return 0;
172
+ if (r.title.toLowerCase().includes(q)) return 1;
173
+ return 2;
174
+ };
175
+ picked.sort((a, b) => score(a) - score(b) || a.idleSec - b.idleSec);
176
+ const total = picked.length;
177
+ const lim = Math.max(1, Math.min(50, Number(limit) || 10));
178
+ return {
179
+ query: q,
180
+ total,
181
+ sessions: picked.slice(0, lim).map((r) => ({
182
+ ...r,
183
+ title: r.title.slice(0, 100),
184
+ host: r.host.slice(0, 40),
185
+ })),
186
+ };
187
+ }
package/lib/index.js ADDED
@@ -0,0 +1,418 @@
1
+ // 注册三个工具 + 自带 skill:detox_scan(只读诊断)/ detox_cut(剪会话文件)/ detox_blocks(剪压缩块摘要)。
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ import { findSessionDir } from './paths.js';
7
+ import { scanSessionFile, cutSessionFile, IDLE_SECONDS } from './session.js';
8
+ import { scanBlocks, cutBlocks } from './blocks.js';
9
+ import { scanWorkspace, countHits } from './workspace.js';
10
+ import { findSessions } from './find.js';
11
+ import { guardStream } from './stream.js';
12
+ import { loadConfig, applyRuntime, RUNTIME } from './config.js';
13
+
14
+ export const name = 'dsh-session-detox';
15
+
16
+ /** 工具注册表是唯一硬依赖。 */
17
+ export const inject = ['tools'];
18
+
19
+ const pluginRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
20
+
21
+ const SESSION_PARAM = {
22
+ type: 'string',
23
+ description: '会话 id 或它的前缀(uuid 前 8 位即可,例如 "5422f542")。必填——不看磁盘分不清是哪条。',
24
+ };
25
+
26
+ function findTool() {
27
+ return {
28
+ name: 'detox_find',
29
+ description:
30
+ '按名字找会话:给关键词(会话名、标题片段、host 名)或 id 前缀,返回匹配的会话 id + 标题 + 体积 + 空闲秒数。'
31
+ + '不给关键词就列出最活跃的若干条。先用它拿到 8 位 id,再喂给 detox_scan / detox_cut / detox_blocks。'
32
+ + '标题优先取 billion-context 账本里的 title / host_title,账本里没有的再读会话文件开头几帧。',
33
+ parameters: {
34
+ type: 'object',
35
+ properties: {
36
+ query: { type: 'string', description: '会话名关键词(子串,不区分大小写),也可以直接给 id 前缀。省略=列最近的。' },
37
+ limit: { type: 'number', description: '最多返回几条,默认 10,上限 50。' },
38
+ },
39
+ required: [],
40
+ additionalProperties: false,
41
+ },
42
+ output: {
43
+ schema: {
44
+ type: 'object',
45
+ properties: {
46
+ query: { type: 'string' },
47
+ total: { type: 'number' },
48
+ sessions: {
49
+ type: 'array',
50
+ items: {
51
+ type: 'object',
52
+ properties: {
53
+ id: { type: 'string' },
54
+ host: { type: 'string' },
55
+ title: { type: 'string' },
56
+ sizeBytes: { type: 'number' },
57
+ idleSec: { type: 'number' },
58
+ inDb: { type: 'boolean' },
59
+ },
60
+ },
61
+ },
62
+ },
63
+ required: ['total', 'sessions'],
64
+ additionalProperties: true,
65
+ },
66
+ render: (_a, v) => {
67
+ if (!v.total) {
68
+ return [{ type: 'text', text: `没有匹配 "${v.query}" 的会话。换个关键词,或者不带关键词先看一遍。` }];
69
+ }
70
+ const rows = v.sessions.map((s) => {
71
+ const who = s.host ? `${s.host}` : '(无 host)';
72
+ const mb = (s.sizeBytes / 1048576).toFixed(1);
73
+ const state = s.idleSec < IDLE_SECONDS ? `还在写(${s.idleSec}s)` : `空闲 ${s.idleSec}s`;
74
+ return `${s.id.slice(0, 8)} ${who} ${mb}MB ${state}\n ${s.title || '(无标题)'}`;
75
+ });
76
+ return [{
77
+ type: 'text',
78
+ text: lines([
79
+ `匹配 "${v.query}" 的会话 ${v.total} 条${v.total > v.sessions.length ? `(只显示前 ${v.sessions.length} 条)` : ''}:`,
80
+ '',
81
+ ...rows,
82
+ '',
83
+ '下一步:把上面的 8 位 id 传给 detox_scan。idle 小于 180 秒的会话还在写,detox_cut 会拒绝。',
84
+ ]),
85
+ }];
86
+ },
87
+ },
88
+ async execute(args) {
89
+ const r = findSessions(args?.query, args?.limit);
90
+ return { query: r.query, total: r.total, sessions: r.sessions };
91
+ },
92
+ };
93
+ }
94
+
95
+ function workspaceTool() {
96
+ return {
97
+ name: 'detox_workspace',
98
+ description:
99
+ '扫描工作区里「会被注入上下文」的文件——AGENTS.md(进每轮系统提示)、.dsh/skills 下的 skill(描述进目录、正文按需加载)'
100
+ + '——列出里面残留的可疑内容:点名这类的措辞、相关小节标题、连写循环段。'
101
+ + '只报告,不改任何文件:文档里的内容是给人看的,删不删要人判断。'
102
+ + '只扫 DSH 通用结构,别的工作区自建的目录(如记忆库)不默认扫,要扫就显式传 root。',
103
+ parameters: {
104
+ type: 'object',
105
+ properties: {
106
+ root: { type: 'string', description: '工作区根目录;省略用进程当前目录。' },
107
+ },
108
+ additionalProperties: false,
109
+ },
110
+ output: {
111
+ schema: {
112
+ type: 'object',
113
+ properties: {
114
+ root: { type: 'string' },
115
+ scanned: { type: 'number' },
116
+ total: { type: 'number' },
117
+ files: {
118
+ type: 'array',
119
+ items: {
120
+ type: 'object',
121
+ properties: {
122
+ path: { type: 'string' },
123
+ kind: { type: 'string' },
124
+ hits: { type: 'array', items: { type: 'object' } },
125
+ },
126
+ },
127
+ },
128
+ },
129
+ required: ['root', 'scanned', 'total', 'files'],
130
+ additionalProperties: true,
131
+ },
132
+ render: (_a, v) => {
133
+ const head = v.total
134
+ ? `扫了 ${v.scanned} 个会被注入的文件,${v.files.length} 个文件里共 ${v.total} 处可疑`
135
+ : `扫了 ${v.scanned} 个会被注入的文件,没有发现可疑内容`;
136
+ const body = [];
137
+ for (const f of v.files) {
138
+ body.push(`\n${f.path} (${f.kind})`);
139
+ for (const h of f.hits.slice(0, 12)) {
140
+ body.push(` L${h.line} [${h.label}] ${h.snippet}`);
141
+ }
142
+ if (f.hits.length > 12) body.push(` …还有 ${f.hits.length - 12} 处`);
143
+ }
144
+ return [{ type: 'text', text: lines([head, ...body, v.total ? '\n这些要人来看:改不改、怎么改由你定,工具只指位置。' : '']) }];
145
+ },
146
+ },
147
+ async execute(args) {
148
+ const root = args?.root || process.cwd();
149
+ const r = scanWorkspace(root);
150
+ return { root, scanned: r.scanned, total: countHits(r), files: r.files };
151
+ },
152
+ };
153
+ }
154
+
155
+ function resolve(session) {
156
+ const hit = findSessionDir(session);
157
+ if (!hit) throw new Error(`找不到会话 "${session}"。去 ~/.dsh/sessions/ 下看目录名。`);
158
+ return hit;
159
+ }
160
+
161
+ function lines(arr) {
162
+ return arr.filter(Boolean).join('\n');
163
+ }
164
+
165
+ function scanTool() {
166
+ return {
167
+ name: 'detox_scan',
168
+ description:
169
+ '只读扫描一条 DSH 会话:数出思考里有多少条要改、多少处极短行、多少段连写循环,'
170
+ + '以及压缩块摘要里几块还带着重复行。不改任何文件,随时可以跑。'
171
+ + '要动手之前先跑它确认数字。',
172
+ parameters: {
173
+ type: 'object',
174
+ properties: { session: SESSION_PARAM },
175
+ required: ['session'],
176
+ additionalProperties: false,
177
+ },
178
+ output: {
179
+ schema: {
180
+ type: 'object',
181
+ properties: {
182
+ session: { type: 'string' },
183
+ file: { type: 'string' },
184
+ mtimeAgeSec: { type: 'number' },
185
+ writable: { type: 'boolean' },
186
+ events: { type: 'number' },
187
+ touched: { type: 'number' },
188
+ stubs: { type: 'number' },
189
+ loops: { type: 'number' },
190
+ chars: { type: 'number' },
191
+ blocksTotal: { type: 'number' },
192
+ blocksHit: { type: 'array', items: { type: 'string' } },
193
+ },
194
+ required: ['session', 'file', 'mtimeAgeSec', 'writable', 'events', 'touched', 'blocksTotal', 'blocksHit'],
195
+ additionalProperties: true,
196
+ },
197
+ render: (_a, v) => [{
198
+ type: 'text',
199
+ text: lines([
200
+ `会话 ${v.session}`,
201
+ `文件 ${v.file}(mtime ${v.mtimeAgeSec} 秒前${v.writable ? ',可动' : ',还在写'})`,
202
+ `会话语料:事件 ${v.events},待改 ${v.touched} 条,极短行 ${v.stubs},循环段 ${v.loops},删字符 ${v.chars}`,
203
+ v.blocksTotal
204
+ ? `压缩块:共 ${v.blocksTotal} 块,${v.blocksHit.length ? `有残留:${v.blocksHit.join(', ')}` : '无残留'}`
205
+ : '压缩块:没找到 billion-context 的账本——要么没装它,要么用的是别的压缩插件(看下面那行)',
206
+ '判据说明:极短行按「字数」认(默认 1~3 个汉字、可选句号、独占一行,不认具体是哪个字)——'
207
+ + '这个长度在思考里没有正经用途,删了不算误伤。循环段按「连写」认。'
208
+ + '要放宽到 4~5 个字就改 lib/detect.js 的 STUB_LINE 成 {1,4},但那时会开始碰到正常短句,一格一格试;'
209
+ + '两条按词的判据(可疑小节标题、点名这个形态的那句话)是同源历史留下的说法,别处不叫这个名字就抓不到,补词即可。',
210
+ '压缩块识别:只认两种——billion-context 的 index.db(detox_blocks)与会话文件内的 compaction/summary 事件(detox_cut)。'
211
+ + '官方 dsh-compaction-basic 与多数第三方后端(vcc / instant / pro / better-compact 等)最终都写 compaction/summary,已覆盖;'
212
+ + '换成把块存在自己数据库里的压缩插件(如 compaction-tower)时,这一项会假阴性——显示无残留但实际可能有。'
213
+ + '遇到不认识的压缩块,去 lib/blocks.js 照着加一个读取器,别信这里的 0。',
214
+ ]),
215
+ }],
216
+ },
217
+ async execute(args) {
218
+ const hit = resolve(args?.session);
219
+ const s = scanSessionFile(hit.file);
220
+ let blocks = { total: 0, hits: [] };
221
+ try {
222
+ blocks = scanBlocks(hit.id.slice(0, 8));
223
+ } catch {
224
+ // 没装 billion-context 时压缩块这一项直接用空
225
+ }
226
+ return {
227
+ session: hit.id,
228
+ file: hit.file,
229
+ mtimeAgeSec: s.mtimeAgeSec,
230
+ writable: s.mtimeAgeSec >= IDLE_SECONDS,
231
+ events: s.events,
232
+ touched: s.touched,
233
+ stubs: s.stubs,
234
+ loops: s.loops,
235
+ chars: s.chars,
236
+ blocksTotal: blocks.total,
237
+ blocksHit: blocks.hits,
238
+ };
239
+ },
240
+ };
241
+ }
242
+
243
+ function cutTool() {
244
+ return {
245
+ name: 'detox_cut',
246
+ description:
247
+ '剪一条 DSH 会话的思考历史:把反复出现的极短碎句从 reasoning 块里删掉,'
248
+ + '自动备份、打包回读校验、校验通过才覆盖,并删掉投影缓存。'
249
+ + '会话还在写(mtime 不足 180 秒)时会拒绝——运行中写盘会把 seq 写断。只碰 reasoning 与 system/tool 文本,user 一个字不动。',
250
+ parameters: {
251
+ type: 'object',
252
+ properties: {
253
+ session: SESSION_PARAM,
254
+ force: { type: 'boolean', description: '跳过 180 秒空闲检查(危险,通常不要用)。' },
255
+ },
256
+ required: ['session'],
257
+ additionalProperties: false,
258
+ },
259
+ output: {
260
+ schema: {
261
+ type: 'object',
262
+ properties: {
263
+ session: { type: 'string' },
264
+ backup: { type: 'string' },
265
+ removedCache: { type: 'boolean' },
266
+ events: { type: 'number' },
267
+ touched: { type: 'number' },
268
+ stubs: { type: 'number' },
269
+ loops: { type: 'number' },
270
+ chars: { type: 'number' },
271
+ bytesAfter: { type: 'number' },
272
+ },
273
+ required: ['session', 'backup', 'events', 'touched'],
274
+ additionalProperties: true,
275
+ },
276
+ render: (_a, v) => [{
277
+ type: 'text',
278
+ text: lines([
279
+ `会话 ${v.session} 已处理`,
280
+ `备份 ${v.backup}`,
281
+ `事件 ${v.events},改 ${v.touched} 条,极短行 ${v.stubs},循环段 ${v.loops},删字符 ${v.chars}`,
282
+ `现在体积 ${v.bytesAfter} B${v.removedCache ? ',已删投影缓存' : ''}`,
283
+ '会话文件已落盘、投影缓存已删——下次打开这条会话读到就是清洗后的内容,不用重启 DSH。',
284
+ '(只有清压缩块的 detox_blocks 才必须重启:bili 进程内存里存着整份 payload,不重启会把磁盘改回去。)',
285
+ `复查:再跑一次 detox_scan ${String(v.session || '').slice(0, 8)},待改必须是 0。`,
286
+ ]),
287
+ }],
288
+ },
289
+ async execute(args) {
290
+ const hit = resolve(args?.session);
291
+ const r = cutSessionFile(hit.file, hit.id, { force: args?.force === true });
292
+ return {
293
+ session: r.session,
294
+ backup: r.backup,
295
+ removedCache: r.removedCache,
296
+ events: r.events,
297
+ touched: r.touched,
298
+ stubs: r.stubs,
299
+ loops: r.loops,
300
+ chars: r.chars,
301
+ bytesAfter: r.sizeAfter,
302
+ };
303
+ },
304
+ };
305
+ }
306
+
307
+ function blocksTool() {
308
+ return {
309
+ name: 'detox_blocks',
310
+ description:
311
+ '清压缩块摘要里残留的重复行(billion-context 的 index.db)。这些摘要每轮随上下文注入,'
312
+ + '留着等于每轮反复提醒模型用这种写法。改前整库备份(约 800MB),只改 summary,不动全文。'
313
+ + '改完必须重启 DSH,否则进程内存里的整份 payload 会把磁盘改回去。',
314
+ parameters: {
315
+ type: 'object',
316
+ properties: { session: SESSION_PARAM },
317
+ required: ['session'],
318
+ additionalProperties: false,
319
+ },
320
+ output: {
321
+ schema: {
322
+ type: 'object',
323
+ properties: {
324
+ backup: { type: 'string' },
325
+ changed: { type: 'number' },
326
+ details: { type: 'array', items: { type: 'object' } },
327
+ },
328
+ required: ['backup', 'changed'],
329
+ additionalProperties: true,
330
+ },
331
+ render: (_a, v) => [{
332
+ type: 'text',
333
+ text: lines([
334
+ `账本备份 ${v.backup}`,
335
+ `改了 ${v.changed} 块`,
336
+ ...v.details.map((d) => ` ${d.id}: ${d.before} -> ${d.after} 字符`),
337
+ v.changed ? '改了压缩块:必须重启 DSH 才会真正生效(不重启,进程内存里的整份 payload 几十秒内会把磁盘改回去)。重启后再跑 detox_scan 确认没有回退。' : '没有需要改的块。不用重启。',
338
+ ]),
339
+ }],
340
+ },
341
+ async execute(args) {
342
+ const hit = resolve(args?.session);
343
+ const r = cutBlocks(hit.id.slice(0, 8));
344
+ return { backup: r.backup, changed: r.changed, details: r.details };
345
+ },
346
+ };
347
+ }
348
+
349
+ /**
350
+ * @param {import('cordis').Context} ctx
351
+ */
352
+ export function apply(ctx) {
353
+ applyRuntime(loadConfig());
354
+
355
+ for (const tool of [findTool(), scanTool(), cutTool(), blocksTool(), workspaceTool()]) {
356
+ ctx.effect(() => ctx.tools.register(tool), `dsh-session-detox: ${tool.name}`);
357
+ }
358
+
359
+ // skill 是说明书,不是硬依赖:没有 skills 服务的 profile 照样能用工具。
360
+ if (typeof ctx.inject === 'function') {
361
+ ctx.inject(['skills'], (skillCtx) => {
362
+ try {
363
+ const skillDir = path.join(pluginRoot, 'skills', 'session-detox');
364
+ const content = fs.readFileSync(path.join(skillDir, 'SKILL.md'), 'utf8');
365
+ skillCtx.effect(() => skillCtx.skills.register({
366
+ name: 'session-detox',
367
+ description: '用 dsh-session-detox 插件清理 DSH 会话:扫描 → 剪会话文件 → 清压缩块 → 重启复查。',
368
+ whenToUse: '当用户说「给这条会话清理一下」「她思考里老重复极短句」「压缩块里还留着重复行」「帮我切一下她的历史」,'
369
+ + '或者你要判断一条会话里残留多少时。',
370
+ content,
371
+ resourceBase: { kind: 'directory', path: skillDir },
372
+ source: 'bundled',
373
+ }), 'dsh-session-detox: skill');
374
+ } catch {
375
+ // 没 skill 服务就算了,工具还能用
376
+ }
377
+ });
378
+ }
379
+
380
+ // ---- 流中截断:挂在 llm/stream waterfall 上 ----
381
+ //
382
+ // ⚠️ 必须**同步返回** AsyncIterable:cordis 的 waterfall 是纯同步的(next() 直接 return
383
+ // 最外层监听器的返回值),监听器一旦写成 async,宿主拿到的是 Promise 而不是流,
384
+ // for await 立刻抛「stream is not async iterable」,整个回合零输出。
385
+ // 所以默认 streamGuard = false;确认要开再改 ~/.dsh/session-detox.json。
386
+ if (typeof ctx.on === 'function') {
387
+ try {
388
+ const off = ctx.on('llm/stream', (options, next) => {
389
+ const upstream = next();
390
+ if (!upstream || typeof upstream[Symbol.asyncIterator] !== 'function') {
391
+ return upstream; // 上游不是流,原样放行
392
+ }
393
+ if (RUNTIME.streamGuard !== true) return upstream; // 没开
394
+ try {
395
+ return guardStream(upstream, {
396
+ onHit: (info) => {
397
+ // 只记一行,不写文件:这一步不该影响生成
398
+ try {
399
+ console.error('[session-detox] 流中截断', JSON.stringify(info));
400
+ } catch {
401
+ /* 记日志失败忽略 */
402
+ }
403
+ },
404
+ });
405
+ } catch {
406
+ return upstream; // 包不起来就原样放行
407
+ }
408
+ });
409
+ if (typeof off === 'function') {
410
+ ctx.effect(() => off, 'dsh-session-detox: llm/stream');
411
+ }
412
+ } catch (e) {
413
+ console.error('[session-detox] 挂 llm/stream 失败(只保留工具):', e?.message ?? e);
414
+ }
415
+ }
416
+ }
417
+
418
+ export default { name, inject, apply };
package/lib/paths.js ADDED
@@ -0,0 +1,74 @@
1
+ // 路径解析:DSH 家目录、会话目录、bili 账本、备份目录。全部按 DSH_HOME / homedir 推,不写死盘符。
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ /** DSH 家目录:优先环境变量,否则 ~/.dsh。 */
7
+ export const DSH_HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
8
+
9
+ /** 会话根目录:~/.dsh/sessions/<workspace>/session-<uuid>/session.v4.jsonl.zstd */
10
+ export const SESSIONS_ROOT = path.join(DSH_HOME, 'sessions');
11
+
12
+ /** 投影缓存目录:删掉对应 session-<uuid>.json 让宿主重算。 */
13
+ export const PROJCACHE_DIR = path.join(DSH_HOME, 'storages', 'session_projcache', 'sessions');
14
+
15
+ /** billion-context 账本(压缩块摘要在这里)。 */
16
+ export const BILI_DB = path.join(os.homedir(), '.local', 'share', 'billion-context', 'sessions', 'index.db');
17
+
18
+ /** 手术备份目录。 */
19
+ export const BACKUP_ROOT = path.join(DSH_HOME, 'detox-backups');
20
+
21
+ /**
22
+ * 在 sessions 根下按 id 前缀找会话目录。
23
+ * @param {string} prefix 会话 id 前缀(uuid 前 8 位即可)
24
+ * @returns {{ dir: string, id: string, file: string } | null}
25
+ */
26
+ export function findSessionDir(prefix) {
27
+ if (!fs.existsSync(SESSIONS_ROOT)) return null;
28
+ const workspaces = fs.readdirSync(SESSIONS_ROOT, { withFileTypes: true }).filter((d) => d.isDirectory());
29
+ const hits = [];
30
+ for (const ws of workspaces) {
31
+ const base = path.join(SESSIONS_ROOT, ws.name);
32
+ let entries = [];
33
+ try {
34
+ entries = fs.readdirSync(base, { withFileTypes: true });
35
+ } catch {
36
+ continue;
37
+ }
38
+ for (const e of entries) {
39
+ if (!e.isDirectory()) continue;
40
+ // 目录名两种都有:session-<uuid> 和裸 <uuid>,只认前者会漏掉一大半
41
+ const raw = e.name.startsWith('session-') ? e.name.slice('session-'.length) : e.name;
42
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-/.test(raw)) continue;
43
+ if (!raw.startsWith(prefix)) continue;
44
+ const dir = path.join(base, e.name);
45
+ const file = path.join(dir, 'session.v4.jsonl.zstd');
46
+ if (fs.existsSync(file)) hits.push({ dir, id: raw, file });
47
+ }
48
+ }
49
+ // 前缀也可能带 "session-" 前缀传进来
50
+ if (!hits.length && prefix.startsWith('session-')) return findSessionDir(prefix.slice('session-'.length));
51
+ if (hits.length === 1) return hits[0];
52
+ if (hits.length > 1) {
53
+ const exact = hits.find((h) => h.id === prefix);
54
+ if (exact) return exact;
55
+ throw new Error(`前缀 "${prefix}" 匹配到 ${hits.length} 个会话,请给长一点:${hits.map((h) => h.id.slice(0, 12)).join(', ')}`);
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /** 某会话的投影缓存文件路径(可能不存在)。 */
61
+ export function projcacheFile(id) {
62
+ return path.join(PROJCACHE_DIR, `session-${id}.json`);
63
+ }
64
+
65
+ /** 备份文件名里的时间戳:YYYYMMDD-HHMMSS。 */
66
+ export function stamp(d = new Date()) {
67
+ const p = (n) => String(n).padStart(2, '0');
68
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
69
+ }
70
+
71
+ /** 确保目录存在。 */
72
+ export function ensureDir(dir) {
73
+ fs.mkdirSync(dir, { recursive: true });
74
+ }