@zaofan/dsh-qqbot 1.12.22 → 1.12.24
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/client/qqbot-settings.js +23 -3
- package/dist/channel-tools.d.ts.map +1 -1
- package/dist/channel-tools.js +12 -0
- package/dist/channel-tools.js.map +1 -1
- package/examples/ext-commands/dshapi.mjs +355 -0
- package/examples/ext-commands//344/274/232/350/257/235/345/210/227/350/241/250.mjs +151 -28
- package/package.json +1 -1
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dshapi.mjs —— 探测宿主 0.2.2 新服务是否可用(2026-11-13 主人要求)
|
|
3
|
+
*
|
|
4
|
+
* 用法:
|
|
5
|
+
* /dshapi 概览:8 个目标服务「有没有 + 形状」
|
|
6
|
+
* /dshapi title 会话标题(session-title)
|
|
7
|
+
* /dshapi stats 会话统计(session-stats)
|
|
8
|
+
* /dshapi market 插件市场/更新判定(pluginManager.listBundles)
|
|
9
|
+
* /dshapi present 工具呈现(agent-tool-presentation)
|
|
10
|
+
* /dshapi cwd 工具工作目录(tool-working-directory)
|
|
11
|
+
* /dshapi quotes 引用呈现(message-quotes)
|
|
12
|
+
* /dshapi ckpt 检查点策略(session-checkpoint-policy)
|
|
13
|
+
* /dshapi batch 工具批处理(tools 服务的并行线索)
|
|
14
|
+
*
|
|
15
|
+
* 设计约束(都是踩坑来的):
|
|
16
|
+
* · cordis 的 `ctx` / `caps` 是 getter,未 inject 时**读取即抛** → 一切包 try,绝不放进数组字面量顺手取
|
|
17
|
+
* · 命令走独立通道(不激活回合),所以这能干净地反映「不问 AI 时能拿到什么」
|
|
18
|
+
* · 输出控制长度(QQ 单条消息有上限),每项最多几行
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const TARGETS = {
|
|
22
|
+
title: ['sessionTitle', 'sessionTitles', 'session-title'],
|
|
23
|
+
stats: ['sessionStats', 'session-stats', 'sessionProjections', 'stats'],
|
|
24
|
+
market: ['pluginManager', 'pluginMarket', 'plugin-market'],
|
|
25
|
+
present: ['agentToolPresentation', 'toolPresentation', 'toolPresentationSelector'],
|
|
26
|
+
cwd: ['toolWorkingDirectory', 'workingDirectory'],
|
|
27
|
+
quotes: ['messageQuotes', 'sessionMessageQuotes', 'messageQuote', 'quotes'],
|
|
28
|
+
ckpt: ['sessionCheckpointPolicy', 'checkpointPolicy', 'checkpoint', 'sessionDurability'],
|
|
29
|
+
batch: ['tools', 'toolRuntime'],
|
|
30
|
+
ws: ['workspaceRegistry', 'workspaces'],
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
let KERNEL = null;
|
|
34
|
+
|
|
35
|
+
function kernelOf(ctx) {
|
|
36
|
+
if (KERNEL) return KERNEL;
|
|
37
|
+
const c = ctx ?? {};
|
|
38
|
+
for (const v of [c?.caps?.kernel, c?.kernel]) if (v) return v;
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 安全取服务:逐个 try,绝不把 getter 放进数组字面量 */
|
|
43
|
+
function svcOf(ctx, name) {
|
|
44
|
+
const k = kernelOf(ctx);
|
|
45
|
+
if (!k) return null;
|
|
46
|
+
try {
|
|
47
|
+
if (typeof k.get === 'function') {
|
|
48
|
+
const v = k.get(name);
|
|
49
|
+
if (v) return v;
|
|
50
|
+
}
|
|
51
|
+
} catch { /* ignore */ }
|
|
52
|
+
for (const key of ['root', 'ctx', 'caps']) {
|
|
53
|
+
try {
|
|
54
|
+
const c = k[key];
|
|
55
|
+
if (!c) continue;
|
|
56
|
+
const v = typeof c.get === 'function' ? c.get(name) : c[name];
|
|
57
|
+
if (v) return v;
|
|
58
|
+
} catch { /* ignore */ }
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 第一次取到的服务(多个候选名里挑一个) */
|
|
64
|
+
function pick(ctx, names) {
|
|
65
|
+
for (const n of names) {
|
|
66
|
+
const v = svcOf(ctx, n);
|
|
67
|
+
if (v) return { name: n, svc: v };
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function shape(v) {
|
|
73
|
+
if (v == null) return '空';
|
|
74
|
+
if (typeof v !== 'object') return typeof v;
|
|
75
|
+
try {
|
|
76
|
+
const keys = Object.keys(v).slice(0, 10);
|
|
77
|
+
const fns = keys.filter((k) => { try { return typeof v[k] === 'function' } catch { return false } });
|
|
78
|
+
return '{' + keys.join(',') + '}' + (fns.length ? ` 可调用:${fns.slice(0, 6).join('/')}` : '');
|
|
79
|
+
} catch (e) {
|
|
80
|
+
return '不可读(' + (e && e.message ? e.message : String(e)) + ')';
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/* ───────── 各子项 ───────── */
|
|
85
|
+
|
|
86
|
+
function probeTitle(ctx) {
|
|
87
|
+
const L = [];
|
|
88
|
+
const s = pick(ctx, TARGETS.title);
|
|
89
|
+
L.push('【session-title】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有这个服务(可能是 0.2.2 之后才有,或名字不同)'));
|
|
90
|
+
if (s) L.push(' 形状: ' + shape(s.svc));
|
|
91
|
+
|
|
92
|
+
// 关键验证:已结束/历史会话能不能拿到标题
|
|
93
|
+
const sessions = svcOf(ctx, 'sessions');
|
|
94
|
+
if (!sessions || typeof sessions.list !== 'function') {
|
|
95
|
+
L.push(' ⚠️ 拿不到 sessions 服务,无法列表');
|
|
96
|
+
return L;
|
|
97
|
+
}
|
|
98
|
+
let list = [];
|
|
99
|
+
try { list = sessions.list() || []; } catch (e) { L.push(' sessions.list() 抛错: ' + (e && e.message)); return L; }
|
|
100
|
+
// 本会话 id:命令侧能拿到的都试一遍(不同版本挂在不同位置)
|
|
101
|
+
let myId = '';
|
|
102
|
+
for (const v of [ctx?.sessionId, ctx?.peerSessionId, ctx?.caps?.sessionId, ctx?.agentId, ctx?.caps?.agentId, ctx?.message?.sessionId]) {
|
|
103
|
+
if (typeof v === 'string' && v) { myId = v; break }
|
|
104
|
+
}
|
|
105
|
+
L.push(` sessions.list() 共 ${list.length} 个 | 本会话 id=${myId ? myId.slice(0, 12) + '…' : '拿不到'}`);
|
|
106
|
+
// 本会话单独查
|
|
107
|
+
if (myId) {
|
|
108
|
+
const me = list.find((it) => String(it?.id || '') === myId);
|
|
109
|
+
if (!me) L.push(' ⚠️ list 里没有本会话(可能已回收/不在当前 profile)');
|
|
110
|
+
else {
|
|
111
|
+
let t = '';
|
|
112
|
+
try { t = String(me?.header?.title ?? me?.title ?? '') } catch { /* ignore */ }
|
|
113
|
+
if (!t) {
|
|
114
|
+
try {
|
|
115
|
+
const log = me?.log || [];
|
|
116
|
+
for (let i = log.length - 1; i >= 0 && i > log.length - 200; i--) {
|
|
117
|
+
if (log[i]?.type === 'session/title') { t = String(log[i]?.data?.title || ''); break }
|
|
118
|
+
}
|
|
119
|
+
} catch { /* ignore */ }
|
|
120
|
+
}
|
|
121
|
+
L.push(` ★ 本会话标题: ${t || '(空 —— 还没生成)'}`);
|
|
122
|
+
// 试标题服务本身
|
|
123
|
+
// ⚠️ 2026-11-13 实测:`sessionTitle.get(id字符串)` 会抛
|
|
124
|
+
// "session.snapshotEvents is not a function" —— 说明它要的是 **Session 对象**,不是 id。
|
|
125
|
+
// 所以这里**两种都试**:先传 sessions.list() 里的那个对象,再传 id(对比报错)。
|
|
126
|
+
try {
|
|
127
|
+
const a = s.svc;
|
|
128
|
+
for (const fnName of ['get', 'of', 'title', 'current', 'read']) {
|
|
129
|
+
if (typeof a?.[fnName] !== 'function') continue;
|
|
130
|
+
try {
|
|
131
|
+
const r = a[fnName](me);
|
|
132
|
+
L.push(` ${fnName}(Session对象) = ${JSON.stringify(r ?? null).slice(0, 100)}`);
|
|
133
|
+
} catch (e) {
|
|
134
|
+
L.push(` ${fnName}(Session对象) 抛错: ${e && e.message}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
} catch { /* ignore */ }
|
|
138
|
+
// 配置与当前 work 状态(能不能生成标题就看这里)
|
|
139
|
+
try {
|
|
140
|
+
const cfg = s.svc?.config;
|
|
141
|
+
L.push(' config: ' + JSON.stringify(cfg ?? null).slice(0, 200));
|
|
142
|
+
} catch (e) { L.push(' 读 config 抛错: ' + (e && e.message)); }
|
|
143
|
+
try {
|
|
144
|
+
const work = s.svc?.work;
|
|
145
|
+
L.push(' work: ' + (typeof work === 'object' ? JSON.stringify(Object.keys(work || {})).slice(0, 120) : typeof work));
|
|
146
|
+
} catch { /* ignore */ }
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const withTitle = [];
|
|
150
|
+
for (const it of list.slice(0, 40)) {
|
|
151
|
+
let t = '';
|
|
152
|
+
try { t = String(it?.header?.title ?? it?.title ?? '') } catch { /* ignore */ }
|
|
153
|
+
if (!t) {
|
|
154
|
+
// 老办法:翻 log 找 session/title
|
|
155
|
+
try {
|
|
156
|
+
const log = it?.log || [];
|
|
157
|
+
for (let i = log.length - 1; i >= 0 && i > log.length - 60; i--) {
|
|
158
|
+
if (log[i]?.type === 'session/title') { t = String(log[i]?.data?.title || ''); break }
|
|
159
|
+
}
|
|
160
|
+
} catch { /* ignore */ }
|
|
161
|
+
}
|
|
162
|
+
if (t) withTitle.push({ id: String(it?.id || '').slice(0, 8), t, live: !!it?.surfaceManager });
|
|
163
|
+
}
|
|
164
|
+
L.push(` 能取到标题的: ${withTitle.length} 个`);
|
|
165
|
+
for (const x of withTitle.slice(0, 8)) L.push(` ${x.live ? '[live]' : '[存档]'} ${x.id} → ${x.t.slice(0, 24)}`);
|
|
166
|
+
const archivedWithTitle = withTitle.filter((x) => !x.live).length;
|
|
167
|
+
L.push(archivedWithTitle > 0
|
|
168
|
+
? ` ✅ 存档会话也能拿到标题(${archivedWithTitle} 个)→ 手册 §11.22 那条可以改`
|
|
169
|
+
: ' ⚠️ 存档会话仍拿不到标题 → 手册 §11.22 依然成立');
|
|
170
|
+
return L;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function probeStats(ctx) {
|
|
174
|
+
const L = [];
|
|
175
|
+
const s = pick(ctx, TARGETS.stats);
|
|
176
|
+
L.push('【session-stats】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有'));
|
|
177
|
+
if (!s) return L;
|
|
178
|
+
L.push(' 形状: ' + shape(s.svc));
|
|
179
|
+
try {
|
|
180
|
+
const keys = Object.keys(s.svc || {});
|
|
181
|
+
L.push(' 键: ' + keys.slice(0, 12).join(','));
|
|
182
|
+
for (const k of keys.slice(0, 6)) {
|
|
183
|
+
try { if (typeof s.svc[k] === 'function') L.push(` ${k}() 可调用`); } catch { /* ignore */ }
|
|
184
|
+
}
|
|
185
|
+
} catch (e) { L.push(' 读取失败: ' + (e && e.message)); }
|
|
186
|
+
return L;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function probeMarket(ctx) {
|
|
190
|
+
const L = [];
|
|
191
|
+
const s = pick(ctx, TARGETS.market);
|
|
192
|
+
L.push('【pluginManager / market】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有'));
|
|
193
|
+
if (!s) return L;
|
|
194
|
+
L.push(' 形状: ' + shape(s.svc));
|
|
195
|
+
let bundles = [];
|
|
196
|
+
try {
|
|
197
|
+
const r = s.svc.listBundles?.();
|
|
198
|
+
bundles = Array.isArray(r) ? r : (r?.bundles || []);
|
|
199
|
+
} catch (e) { L.push(' listBundles() 抛错: ' + (e && e.message)); return L; }
|
|
200
|
+
L.push(` listBundles() = ${bundles.length} 个`);
|
|
201
|
+
if (bundles.length) {
|
|
202
|
+
const sample = bundles.slice(0, 6);
|
|
203
|
+
for (const b of sample) {
|
|
204
|
+
const upd = 'update' in (b || {}) ? b.update : ('updatable' in (b || {}) ? '(旧字段 updatable=' + b.updatable + ')' : '?');
|
|
205
|
+
const nm = String(b?.name || b?.id || b?.spec || '?').slice(0, 40);
|
|
206
|
+
L.push(` ${nm} → update=${JSON.stringify(upd)}`);
|
|
207
|
+
}
|
|
208
|
+
const hasNew = sample.some((b) => 'update' in (b || {}));
|
|
209
|
+
L.push(hasNew ? ' ✅ 已是新字段 update(可用来做「有新版本」提示)' : ' ⚠️ 还是旧字段 updatable');
|
|
210
|
+
}
|
|
211
|
+
return L;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function probePresent(ctx) {
|
|
215
|
+
const L = [];
|
|
216
|
+
const s = pick(ctx, TARGETS.present);
|
|
217
|
+
L.push('【agent-tool-presentation】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有'));
|
|
218
|
+
if (s) L.push(' 形状: ' + shape(s.svc));
|
|
219
|
+
return L;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function probeCwd(ctx) {
|
|
223
|
+
const L = [];
|
|
224
|
+
const s = pick(ctx, TARGETS.cwd);
|
|
225
|
+
L.push('【tool-working-directory】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有'));
|
|
226
|
+
if (s) L.push(' 形状: ' + shape(s.svc));
|
|
227
|
+
return L;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function probeQuotes(ctx) {
|
|
231
|
+
const L = [];
|
|
232
|
+
const s = pick(ctx, TARGETS.quotes);
|
|
233
|
+
L.push('【message-quotes】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有'));
|
|
234
|
+
if (s) L.push(' 形状: ' + shape(s.svc));
|
|
235
|
+
return L;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function probeCkpt(ctx) {
|
|
239
|
+
const L = [];
|
|
240
|
+
const s = pick(ctx, TARGETS.ckpt);
|
|
241
|
+
L.push('【session-checkpoint-policy】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有'));
|
|
242
|
+
if (s) L.push(' 形状: ' + shape(s.svc));
|
|
243
|
+
return L;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function probeBatch(ctx) {
|
|
247
|
+
const L = [];
|
|
248
|
+
const s = pick(ctx, TARGETS.batch);
|
|
249
|
+
L.push('【tools(批处理线索)】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有'));
|
|
250
|
+
if (!s) return L;
|
|
251
|
+
L.push(' 形状: ' + shape(s.svc));
|
|
252
|
+
let defs = [];
|
|
253
|
+
try {
|
|
254
|
+
const r = s.svc.list?.() ?? s.svc.all?.() ?? s.svc.definitions?.();
|
|
255
|
+
defs = Array.isArray(r) ? r : [];
|
|
256
|
+
} catch { /* ignore */ }
|
|
257
|
+
if (defs.length) {
|
|
258
|
+
L.push(` 当前注册工具 ${defs.length} 个`);
|
|
259
|
+
const one = defs[0] || {};
|
|
260
|
+
const keys = Object.keys(one).slice(0, 12);
|
|
261
|
+
L.push(' 单个工具定义键: ' + keys.join(','));
|
|
262
|
+
const par = defs.filter((d) => ['executionMode', 'parallel', 'exclusive', 'mode'].some((k) => k in (d || {}))).length;
|
|
263
|
+
L.push(par > 0 ? ` ✅ ${par} 个工具带执行模式字段(并行分类就靠它)` : ' ℹ️ 工具定义里没有执行模式字段 → 并行分类在宿主内部(batch.ts),扩展无感');
|
|
264
|
+
} else {
|
|
265
|
+
L.push(' (拿不到工具清单:list()/all() 都没有或抛错)');
|
|
266
|
+
}
|
|
267
|
+
return L;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* workspaceRegistry —— **宿主 UI 那颗「筛选会话 / 隐藏已归档」就是它**(2026-11-13 查到)。
|
|
272
|
+
* 它启动时把 header 全量索引进内存,并维护 registry 级的 `archivedSessionIds`。
|
|
273
|
+
* 所以「列会话」不该再去 `sessionPersistence.list()` 扫盘 —— 直接问它。
|
|
274
|
+
*/
|
|
275
|
+
function probeWs(ctx) {
|
|
276
|
+
const L = [];
|
|
277
|
+
const s = pick(ctx, ['workspaceRegistry', 'workspaces', 'workspace']);
|
|
278
|
+
L.push('【workspaceRegistry】' + (s ? `✅ kernel.get('${s.name}')` : '❌ 没有'));
|
|
279
|
+
if (!s) return L;
|
|
280
|
+
const a = s.svc;
|
|
281
|
+
try { L.push(' 形状: ' + shape(a)); } catch { /* ignore */ }
|
|
282
|
+
try {
|
|
283
|
+
const ids = a.archivedSessionIds;
|
|
284
|
+
L.push(' archivedSessionIds: ' + (Array.isArray(ids) ? `${ids.length} 个` : typeof ids));
|
|
285
|
+
} catch (e) { L.push(' 读 archivedSessionIds 抛错: ' + (e && e.message)); }
|
|
286
|
+
try {
|
|
287
|
+
const pinned = a.pinnedSessionIds;
|
|
288
|
+
L.push(' pinnedSessionIds: ' + (Array.isArray(pinned) ? `${pinned.length} 个` : typeof pinned));
|
|
289
|
+
} catch { /* ignore */ }
|
|
290
|
+
let list = [];
|
|
291
|
+
try { list = a.list() || []; } catch (e) { L.push(' list() 抛错: ' + (e && e.message)); return L; }
|
|
292
|
+
L.push(` list() = ${list.length} 个工作区`);
|
|
293
|
+
// 看一个工作区的形状 + 有没有直接给会话 header
|
|
294
|
+
const one = list[0];
|
|
295
|
+
if (one) {
|
|
296
|
+
// 2026-11-13:重点看 `record`(工作区记录)里有没有会话元数据(标题/时间),
|
|
297
|
+
// 以及 sessionIds 是不是原型上的 getter —— 决定我们能不能完全不再扫盘。
|
|
298
|
+
try { L.push(' 首个工作区 record: ' + JSON.stringify(one.record ?? null).slice(0, 300)); } catch { /* ignore */ }
|
|
299
|
+
try {
|
|
300
|
+
const ids = one.sessionIds;
|
|
301
|
+
L.push(' sessionIds 类型=' + (Array.isArray(ids) ? `数组(${ids.length})` : typeof ids) + ' | 前 3: ' + JSON.stringify((ids || []).slice(0, 3)));
|
|
302
|
+
} catch (e) { L.push(' 读 sessionIds 抛错: ' + (e && e.message)); }
|
|
303
|
+
try {
|
|
304
|
+
const total = list.reduce((n, w) => n + ((w.sessionIds || []).length), 0);
|
|
305
|
+
L.push(` 全部工作区 sessionIds 合计 = ${total}(对比 sessionPersistence 的 1697)`);
|
|
306
|
+
} catch { /* ignore */ }
|
|
307
|
+
try { L.push(' 单个工作区键: ' + Object.keys(one).slice(0, 10).join(',')); } catch { /* ignore */ }
|
|
308
|
+
for (const k of ['sessions', 'sessionIds', 'headers', 'sessionHeaders']) {
|
|
309
|
+
try {
|
|
310
|
+
const v = one[k];
|
|
311
|
+
if (v == null) continue;
|
|
312
|
+
L.push(` ${k} = ${Array.isArray(v) ? v.length + ' 项' : typeof v}`);
|
|
313
|
+
if (Array.isArray(v) && v.length) {
|
|
314
|
+
const it = v[0];
|
|
315
|
+
L.push(' 首项: ' + (typeof it === 'string' ? it.slice(0, 12) : JSON.stringify(Object.keys(it || {})).slice(0, 120)));
|
|
316
|
+
}
|
|
317
|
+
} catch { /* ignore */ }
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return L;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const SUBS = {
|
|
324
|
+
title: probeTitle, stats: probeStats, market: probeMarket, present: probePresent,
|
|
325
|
+
cwd: probeCwd, quotes: probeQuotes, ckpt: probeCkpt, batch: probeBatch, ws: probeWs,
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
function overview(ctx) {
|
|
329
|
+
KERNEL = KERNEL ?? kernelOf(ctx);
|
|
330
|
+
const L = ['【DSH 0.2.2 新服务探测】kernel=' + (KERNEL ? '✅' : '❌')];
|
|
331
|
+
for (const [key, names] of Object.entries(TARGETS)) {
|
|
332
|
+
const hit = pick(ctx, names);
|
|
333
|
+
L.push(` ${key.padEnd(8)} ${hit ? '✅ ' + hit.name : '❌ 无(试过 ' + names.join('/') + ')'}`);
|
|
334
|
+
}
|
|
335
|
+
L.push('');
|
|
336
|
+
L.push('细看:/dshapi title | stats | market | present | cwd | quotes | ckpt | batch');
|
|
337
|
+
return L;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export default {
|
|
341
|
+
name: ['dshapi', 'dsh-api'],
|
|
342
|
+
description: '探测 DSH 0.2.2 新服务(标题/统计/市场/呈现/工作目录/引用/检查点/批处理)',
|
|
343
|
+
usage: '/dshapi [title|stats|market|present|cwd|quotes|ckpt|batch]',
|
|
344
|
+
handler: (ctx) => {
|
|
345
|
+
KERNEL = KERNEL ?? kernelOf(ctx);
|
|
346
|
+
const arg = String(ctx?.command?.raw ?? '').trim().toLowerCase();
|
|
347
|
+
const fn = SUBS[arg];
|
|
348
|
+
try {
|
|
349
|
+
const lines = fn ? fn(ctx) : overview(ctx);
|
|
350
|
+
return lines.join('\n').slice(0, 3500);
|
|
351
|
+
} catch (e) {
|
|
352
|
+
return '探测失败: ' + (e && e.message ? e.message : String(e));
|
|
353
|
+
}
|
|
354
|
+
},
|
|
355
|
+
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
1
2
|
/**
|
|
2
3
|
* 会话列表.mjs — `/会话列表` 斜杠命令(扩展命令第五套)
|
|
3
4
|
*
|
|
@@ -69,15 +70,15 @@ function cn(v) { return v === undefined || v === null ? '' : String(v); }
|
|
|
69
70
|
function short(s, n) { const t = cn(s).replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n) + '…' : t; }
|
|
70
71
|
|
|
71
72
|
/** 诊断日志(沿用 /子会话 的做法:写死路径,排查"点了没反应"最有用) */
|
|
72
|
-
// ★ 2026-10-
|
|
73
|
-
//
|
|
74
|
-
const
|
|
73
|
+
// ★ 2026-10-24 修复(issue #17): 诊断日志原来写死 Windows 路径(D:/…) —— Linux/容器上会被
|
|
74
|
+
// 当成相对路径,在家目录里生成一个叫 "D:" 的畸形目录。日志跟本文件走,跨平台都不会丢。
|
|
75
|
+
const DIAG_FILE = fileURLToPath(new URL('../data/会话列表-diag.log', import.meta.url));
|
|
75
76
|
async function diag(msg) {
|
|
76
77
|
try {
|
|
77
78
|
const { appendFile, mkdir } = await import('node:fs/promises');
|
|
78
79
|
const { dirname } = await import('node:path');
|
|
79
|
-
await mkdir(
|
|
80
|
-
await appendFile(
|
|
80
|
+
await mkdir(dirname(DIAG_FILE), { recursive: true });
|
|
81
|
+
await appendFile(DIAG_FILE, `${new Date().toISOString()} ${msg}\n`);
|
|
81
82
|
} catch { /* 诊断失败绝不影响主流程 */ }
|
|
82
83
|
}
|
|
83
84
|
|
|
@@ -89,9 +90,7 @@ function dataRootOf(ctx) {
|
|
|
89
90
|
const cand = p.dataRoot ?? caps.dataRoot ?? ctx?.dataRoot ?? '';
|
|
90
91
|
if (cand) return String(cand);
|
|
91
92
|
} catch { /* ignore */ }
|
|
92
|
-
|
|
93
|
-
// ({dataRoot}/.qqbot-extensions/commands/x.mjs → 上两级 = {dataRoot})
|
|
94
|
-
try { return decodeURIComponent(new URL('../../', import.meta.url).pathname).replace(/[\\/]+$/, ''); } catch { return ''; }
|
|
93
|
+
return 'D:/newwenjianjia/aiwork/鲸鱼娘/dshqqbot';
|
|
95
94
|
}
|
|
96
95
|
|
|
97
96
|
/**
|
|
@@ -206,22 +205,12 @@ async function sendCard(ctx, text, keyboard) {
|
|
|
206
205
|
const rt = ctx?.replyTarget ?? {};
|
|
207
206
|
const pe = ctx?.peer ?? {};
|
|
208
207
|
const scope = cn(rt.scope || ctx?.scope || pe.scope || mc.kind || ((mc.groupOpenid || pe.groupId || pe.peerId) ? 'group' : 'c2c'));
|
|
209
|
-
|
|
210
|
-
// tier① 直连去请求 /v2/groups/<user_openid>/messages 必然被拒(gid 非空时 body 也不带
|
|
211
|
-
// c2c 需要的 content 字段) → 一路降级成"文字发出来了、按钮消失"。
|
|
212
|
-
// 私聊一律 gid='' 走 /v2/users/<openid>/messages。
|
|
213
|
-
const gid = scope === 'group'
|
|
214
|
-
? cn(mc.groupOpenid || rt.targetId || rt.openid || rt.id || pe.groupId || pe.groupOpenid || pe.peerId || pe.id || '')
|
|
215
|
-
: '';
|
|
208
|
+
const gid = cn(mc.groupOpenid || rt.targetId || rt.openid || rt.id || pe.groupId || pe.groupOpenid || (scope === 'group' ? (pe.peerId || pe.id) : '') || '');
|
|
216
209
|
const uid = cn(mc.senderId || rt.openid || rt.id || pe.openid || pe.userId || '');
|
|
217
210
|
const api = caps.api;
|
|
218
211
|
if (keyboard && typeof api === 'function' && (gid || uid)) {
|
|
219
212
|
const path = gid ? `/v2/groups/${gid}/messages` : `/v2/users/${uid}/messages`;
|
|
220
|
-
|
|
221
|
-
// 否则可能被拒/退化; 群聊保持原样(实测不带 msg_id 也能发)。
|
|
222
|
-
const replyMsgId = cn(rt.msgId || rt.messageId || mc.msgId || mc.messageId || '');
|
|
223
|
-
void diag(`[sendCard] ①path=${path} msgId=${replyMsgId || '-'} kbRows=${keyboard?.content?.rows?.length ?? '?'}`);
|
|
224
|
-
const body = { msg_type: 2, markdown: { content: text }, keyboard, ...(gid ? {} : { content: text, ...(replyMsgId ? { msg_id: replyMsgId } : {}) }) };
|
|
213
|
+
const body = { msg_type: 2, markdown: { content: text }, keyboard, ...(gid ? {} : { content: text }) };
|
|
225
214
|
try {
|
|
226
215
|
const r = await api(path, { method: 'POST', body });
|
|
227
216
|
void diag(`[sendCard] ①api=${JSON.stringify(r ?? null).slice(0, 200)}`);
|
|
@@ -313,6 +302,8 @@ function wsDisplay(dir, max = 52) {
|
|
|
313
302
|
|
|
314
303
|
const OPT_CACHE = new Map();
|
|
315
304
|
const OPT_TTL_MS = 60 * 1000; // 候选缓存:60 秒(新会话能及时冒出来)
|
|
305
|
+
/** 全量会话列表缓存(60s):sessionPersistence.list() 扫盘很慢,别每次向导都重扫 */
|
|
306
|
+
const ALL_CACHE = new Map();
|
|
316
307
|
const TTL_CACHE = new Map(); // 标题缓存(带时间戳,5 分钟过期)
|
|
317
308
|
const TITLE_TTL_MS = 5 * 60 * 1000;
|
|
318
309
|
let KERNEL = null;
|
|
@@ -361,7 +352,89 @@ function fullId(id) { const s = cn(id); return s.startsWith('session-') ? s : `s
|
|
|
361
352
|
* 宿主里**全部**会话(含已结束的)。返回 [{id, cwd, createdAt, sizeBytes}];
|
|
362
353
|
* 拿不到服务时返回 null,调用方回退扫盘。
|
|
363
354
|
*/
|
|
355
|
+
/**
|
|
356
|
+
* 会话索引的**磁盘缓存**(10 分钟):
|
|
357
|
+
* 宿主的 `sessionPersistence.list()` 每次都要扫全盘(本机 1697 个),
|
|
358
|
+
* 而且**没有过滤选项**(0.2.2 源码确认:options 只有 signal)。
|
|
359
|
+
* 所以首次扫完就落盘,后续向导/翻页直接读,跨重启也有效。
|
|
360
|
+
*/
|
|
361
|
+
const SESSION_INDEX_TTL_MS = 10 * 60 * 1000;
|
|
362
|
+
let SESSION_INDEX_FILE = '';
|
|
363
|
+
|
|
364
|
+
function sessionIndexFile() {
|
|
365
|
+
if (SESSION_INDEX_FILE) return SESSION_INDEX_FILE;
|
|
366
|
+
try {
|
|
367
|
+
const dr = String((typeof CTX_CACHE !== 'undefined' && CTX_CACHE && CTX_CACHE.dataRoot) || '');
|
|
368
|
+
if (dr) SESSION_INDEX_FILE = join(dr, '.qqbot', 'session-index-cache.json');
|
|
369
|
+
} catch { /* ignore */ }
|
|
370
|
+
return SESSION_INDEX_FILE;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function readSessionIndexCache() {
|
|
374
|
+
try {
|
|
375
|
+
const f = sessionIndexFile();
|
|
376
|
+
if (!f) return null;
|
|
377
|
+
if (!existsSync(f)) return null;
|
|
378
|
+
const j = JSON.parse(readFileSync(f, 'utf8'));
|
|
379
|
+
if (!j || !Array.isArray(j.items)) return null;
|
|
380
|
+
if (Date.now() - Number(j.at || 0) > SESSION_INDEX_TTL_MS) return null;
|
|
381
|
+
return j.items;
|
|
382
|
+
} catch { return null; }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function writeSessionIndexCache(items) {
|
|
386
|
+
try {
|
|
387
|
+
const f = sessionIndexFile();
|
|
388
|
+
if (!f) return;
|
|
389
|
+
mkdirSync(dirname(f), { recursive: true });
|
|
390
|
+
writeFileSync(f, JSON.stringify({ at: Date.now(), items }), 'utf8');
|
|
391
|
+
} catch { /* 缓存失败不影响主流程 */ }
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* ⭐ 2026-11-13 主线路:从 `workspaceRegistry` 读(宿主界面「隐藏已归档」用的就是它)。
|
|
396
|
+
*
|
|
397
|
+
* 为什么换成它:`sessionPersistence.list()` 每次都要枚举磁盘上全部会话(本机 1697 个,含子代理),
|
|
398
|
+
* 而 `workspaceRegistry` 在**启动时就把 header 索引进内存**,并维护 registry 级 `archivedSessionIds`。
|
|
399
|
+
* 实测:11 个工作区 `sessionIds` 合计 **262**(对比 1697),且拿取是**同步内存操作**。
|
|
400
|
+
*
|
|
401
|
+
* 返回 [{ path, title, ids }],ids 已**剔除归档**。
|
|
402
|
+
*/
|
|
403
|
+
function regWorkspaces(ctx) {
|
|
404
|
+
const reg = svcOf(ctx, 'workspaceRegistry');
|
|
405
|
+
if (!reg || typeof reg.list !== 'function') return null;
|
|
406
|
+
let archived = [];
|
|
407
|
+
try { archived = reg.archivedSessionIds || []; } catch { /* ignore */ }
|
|
408
|
+
const arch = new Set(Array.isArray(archived) ? archived.map((x) => String(x)) : []);
|
|
409
|
+
let list = [];
|
|
410
|
+
try { list = reg.list() || []; } catch { return null; }
|
|
411
|
+
const out = [];
|
|
412
|
+
for (const w of list) {
|
|
413
|
+
let rec = null;
|
|
414
|
+
try { rec = w.record || null; } catch { /* ignore */ }
|
|
415
|
+
let ids = [];
|
|
416
|
+
try { ids = Array.isArray(w.sessionIds) ? w.sessionIds.slice() : []; } catch { /* ignore */ }
|
|
417
|
+
const path = String(rec?.path ?? '');
|
|
418
|
+
const title = String(rec?.title ?? '') || path;
|
|
419
|
+
const live = ids.filter((id) => !arch.has(String(id)));
|
|
420
|
+
out.push({ path, title, ids: live, archivedCount: ids.length - live.length });
|
|
421
|
+
}
|
|
422
|
+
return { list: out, archived: arch.size };
|
|
423
|
+
}
|
|
424
|
+
|
|
364
425
|
async function listAllSessions(ctx) {
|
|
426
|
+
// ★ 2026-11-13(主人:"1359 个?好慢"):`sessionPersistence.list()` 会把**磁盘上所有会话**
|
|
427
|
+
// 枚举出来(含**子代理会话**和归档),一千多个时首次要等好几秒。
|
|
428
|
+
// 这里做两件事:① 结果整体缓存 60s(向导翻页/重试不再重扫);② 把 delegationDepth 带出来供上层过滤。
|
|
429
|
+
const CACHE_KEY = 'allSessions';
|
|
430
|
+
const cacheHit = ALL_CACHE.get(CACHE_KEY);
|
|
431
|
+
if (cacheHit && Date.now() - cacheHit.at < 60_000) return cacheHit.v;
|
|
432
|
+
// ★ 2026-11-13(主人:"还是慢"):`sessionPersistence.list()` **没有"只列未归档"的选项**
|
|
433
|
+
// (签名只有 `{signal}`,我们查过 0.2.2 源码)。它每次都要枚举磁盘上全部会话
|
|
434
|
+
// (本机 1697 个,含子代理/归档)⇒ 首次必然几秒。
|
|
435
|
+
// 所以改成**磁盘缓存**:10 分钟内直接读缓存,跨进程重启也有效;过期才重扫一次。
|
|
436
|
+
const diskHit = readSessionIndexCache();
|
|
437
|
+
if (diskHit) return diskHit;
|
|
365
438
|
const sp = svcOf(ctx, 'sessionPersistence');
|
|
366
439
|
if (!sp || typeof sp.list !== 'function') {
|
|
367
440
|
void diag(`[svc] 拿不到 sessionPersistence(kernel=${!!kernelOf(ctx)} sp=${!!sp})`);
|
|
@@ -377,9 +450,13 @@ async function listAllSessions(ctx) {
|
|
|
377
450
|
cwd: cn(h.cwd ?? it?.cwd),
|
|
378
451
|
createdAt: Number(h.createdAt ?? it?.createdAt ?? 0) || 0,
|
|
379
452
|
sizeBytes: Number(it?.sizeBytes ?? 0) || 0,
|
|
453
|
+
// 子代理会话:delegationDepth > 0(顶层会话没有这个字段或为 0)
|
|
454
|
+
depth: Number(h.delegationDepth ?? it?.delegationDepth ?? 0) || 0,
|
|
380
455
|
};
|
|
381
456
|
}).filter((x) => x.id);
|
|
382
457
|
if (out.length === 0) return null;
|
|
458
|
+
ALL_CACHE.set(CACHE_KEY, { at: Date.now(), v: out });
|
|
459
|
+
writeSessionIndexCache(out);
|
|
383
460
|
return out;
|
|
384
461
|
} catch (e) {
|
|
385
462
|
void diag(`[svc] sessionPersistence.list 抛错=${short(e?.message ?? e, 160)}`);
|
|
@@ -404,6 +481,8 @@ async function liveMap(ctx) {
|
|
|
404
481
|
const hit = TTL_CACHE.get('live');
|
|
405
482
|
if (hit && Date.now() - hit.at < 15 * 1000) return hit.v;
|
|
406
483
|
const out = new Map();
|
|
484
|
+
let titleSvc = null;
|
|
485
|
+
try { titleSvc = svcOf(ctx, 'sessionTitle'); } catch { /* ignore */ }
|
|
407
486
|
const ss = svcOf(ctx, 'sessions');
|
|
408
487
|
if (ss && typeof ss.list === 'function') {
|
|
409
488
|
try {
|
|
@@ -413,12 +492,23 @@ async function liveMap(ctx) {
|
|
|
413
492
|
const id = bareId(o?.id ?? o?.sessionId ?? '');
|
|
414
493
|
if (!id) continue;
|
|
415
494
|
let title = '';
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
495
|
+
// ★ 2026-11-13 更新(实测):`sessionTitle.get()` **没坏** —— 它要的是 **Session 对象**,
|
|
496
|
+
// 传 id 字符串才会抛 "session.snapshotEvents is not a function"。
|
|
497
|
+
// 传对象后能直接拿到标题,且**比扫 log 更全**(log 里只有 "被生成过" 的会话才有 session/title 事件)。
|
|
498
|
+
if (titleSvc) {
|
|
499
|
+
try {
|
|
500
|
+
const r = titleSvc.get(o);
|
|
501
|
+
if (r && typeof r.title === 'string' && r.title) title = r.title;
|
|
502
|
+
} catch { /* 回退扫 log */ }
|
|
503
|
+
}
|
|
504
|
+
if (!title) {
|
|
505
|
+
const lg = o?.log;
|
|
506
|
+
if (Array.isArray(lg)) {
|
|
507
|
+
for (let i = lg.length - 1; i >= 0; i--) {
|
|
508
|
+
if (String(lg[i]?.type ?? '') === 'session/title') {
|
|
509
|
+
const t = lg[i]?.data?.title;
|
|
510
|
+
if (typeof t === 'string' && t) { title = t; break; }
|
|
511
|
+
}
|
|
422
512
|
}
|
|
423
513
|
}
|
|
424
514
|
}
|
|
@@ -446,12 +536,24 @@ async function optionsOfRaw(ctx, step, st) {
|
|
|
446
536
|
try {
|
|
447
537
|
const lib = await loadLib();
|
|
448
538
|
if (step === 'workspace') {
|
|
539
|
+
// ⭐ 先走 registry(内存,瞬间);拿不到才退回扫盘
|
|
540
|
+
const reg = regWorkspaces(ctx);
|
|
541
|
+
if (reg && reg.list.length > 0) {
|
|
542
|
+
const list = reg.list
|
|
543
|
+
.filter((w) => w.ids.length > 0)
|
|
544
|
+
.sort((a, b) => b.ids.length - a.ids.length);
|
|
545
|
+
LAST_SCOPE = `注册表 ${list.length} 个工作区 / 未归档会话 ${list.reduce((n, w) => n + w.ids.length, 0)} 个(另已归档 ${reg.archived} 个)`;
|
|
546
|
+
void diag(`[opts] workspace 走 registry:${LAST_SCOPE}`);
|
|
547
|
+
return list.map((w) => ({ value: w.path, label: `${wsDisplay(w.path)} · ${w.ids.length} 个` }));
|
|
548
|
+
}
|
|
449
549
|
const all = await listAllSessions(ctx);
|
|
450
550
|
if (all) {
|
|
551
|
+
// ★ 只数**顶层会话**:子代理会话(depth>0)不该出现在"工作区有多少会话"里
|
|
552
|
+
const top = all.filter((x) => !x.depth);
|
|
451
553
|
const cnt = new Map();
|
|
452
|
-
for (const s of
|
|
554
|
+
for (const s of top) if (s.cwd) cnt.set(s.cwd, (cnt.get(s.cwd) ?? 0) + 1);
|
|
453
555
|
const list = [...cnt.entries()].sort((a, b) => b[1] - a[1]);
|
|
454
|
-
LAST_SCOPE = `宿主 ${all.length}
|
|
556
|
+
LAST_SCOPE = `宿主 ${top.length} 个会话(另有子代理 ${all.length - top.length} 个,未列出)/ ${list.length} 个工作区`;
|
|
455
557
|
void diag(`[opts] workspace 走宿主:${LAST_SCOPE}`);
|
|
456
558
|
return list.map(([cwd, n]) => ({ value: cwd, label: `${wsDisplay(cwd)} · ${n} 个` }));
|
|
457
559
|
}
|
|
@@ -463,6 +565,27 @@ async function optionsOfRaw(ctx, step, st) {
|
|
|
463
565
|
if (step === 'session') {
|
|
464
566
|
const ws = st.picked.workspace?.value ?? '';
|
|
465
567
|
const live = await liveMap(ctx);
|
|
568
|
+
// ⭐ 同样先走 registry:该工作区的 sessionIds 已在内存里(且已剔除归档)
|
|
569
|
+
const reg = regWorkspaces(ctx);
|
|
570
|
+
const rw = reg?.list.find((w) => w.path === ws);
|
|
571
|
+
if (reg && rw) {
|
|
572
|
+
const ids = rw.ids.slice();
|
|
573
|
+
// 有标题的(live)排前面,其余按 id 稳定排序
|
|
574
|
+
const score = (id) => (live.get(bareId(id))?.title ? 1 : 0);
|
|
575
|
+
ids.sort((a, b) => (score(b) - score(a)) || String(a).localeCompare(String(b)));
|
|
576
|
+
const shown = ids.slice(0, 80);
|
|
577
|
+
const named = ids.filter((id) => live.get(bareId(id))?.title).length;
|
|
578
|
+
LAST_SCOPE = `${ids.length} 个未归档会话(${named} 个在线有名;该区归档 ${rw.archivedCount} 个已隐藏)`;
|
|
579
|
+
void diag(`[opts] session 走 registry ws=${ws} 命中 ${ids.length},有名 ${named}`);
|
|
580
|
+
return shown.map((id) => {
|
|
581
|
+
const info = live.get(bareId(id));
|
|
582
|
+
const t = info?.title ?? '';
|
|
583
|
+
const tag = info ? '🟢' : '⚪';
|
|
584
|
+
const id8 = bareId(id).slice(0, 8);
|
|
585
|
+
const head = t ? short(t, 24) : id8;
|
|
586
|
+
return { value: id, label: `${tag} ${head}${t ? ` · ${id8}` : ''}` };
|
|
587
|
+
});
|
|
588
|
+
}
|
|
466
589
|
const all = await listAllSessions(ctx);
|
|
467
590
|
if (all) {
|
|
468
591
|
const seen = new Set();
|