@zaofan/dsh-qqbot 1.13.16 → 1.13.17

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.
@@ -1,1315 +1,1319 @@
1
- /**
2
- * session_watch_lib.mjs — 「回合结束回灌」的共用实现(放在 tools/lib/ 下,不被当工具扫描)
3
- *
4
- * 口径**照抄 qqbot 的 passive 收尾**(src/transport/outbound.ts:80-211):
5
- * · 回合内累积 `assistant/message` 的正文(= 它的 noteGenerated(sessionKey, msgId, text))
6
- * · `turn/end` 时结算(它的注释原文:「assistant/message 用完即清,turn/end 兜底清」)
7
- * · 取**最后一个正文块**的文本(它收尾时也是"把最后一块复制一份")
8
- *
9
- * ★ 2026-10-12 主人定案(回灌模式三档 + 转发到 QQ + 引用回流):
10
- * **一档(mode=1,默认)**:只把**末段正文**回灌给父会话(原行为),**同时**转发到父会话所在的 QQ。
11
- * **二档(mode=2)**:本回合的**所有正文块 + 报错**都转发到 QQ,但**不进父会话上下文**。
12
- * **三档(mode=3)**:所有正文 + 报错**进**父会话上下文(**只插话、不唤醒**),同时也转发到 QQ。
13
- *
14
- * ★ 转发到 QQ 的三条口径:
15
- * ① **行首归属**:每条转发消息的第一行是 `【子会话 xxxx】`(xxxx=会话短 id)。
16
- * 它**短且在最前**是硬要求 —— QQ 入站引用块只带被引原文**前 60 字**(inbound 的 QUOTE_KEEP),
17
- * 归属跑出这 60 字就再也认不出来了(见下面的"引用回流")。
18
- * ② **markdown + 失败降级**:直接走 `sender.sendMarkdown(replyTarget, text)` ——
19
- * 插件自带的 markdown→纯文本降级链(`send_md` 工具用的就是它),失败再退回 `sender.sendText`。
20
- * ③ **被动优先**:`replyTarget` 自带该会话最近的 `msgId`,带它发即"被动回复"
21
- * (不吃主动配额、QQ 也不吞);插件侧在被动失败时会自动去掉 msgId 转主动。
22
- * ⚠️ 这两件事都在**插件**里做好了,本库直接用 `sender` + `replyTarget` 即可,不重复造。
23
- *
24
- * ★ 引用回流(主人 2026-10-12 明确口径:**靠行首会话信息判断,不依赖台账**):
25
- * 群里有人**引用**那条转发消息时,入站引用块会把被引原文的前 60 字带进来,
26
- * 归属行就在里面 ⇒ 本库从入站 user 消息里正则认出 `【子会话 xxxx】`
27
- * → 把这条引用的原文**插话**给对应子会话(忙时 inject、空闲 followup)。
28
- * **不需要 QQ 的 msg_id**,也**不需要维护任何 msg_id→会话 的映射表**。
29
- * 短 id → 完整会话 id 是**当场**在会话注册表里查的(见 resolveShortId)。
30
- *
31
- * 本库只做三件事:挂监听、结算回灌/转发、认引用回流。
32
- *
33
- * ★ 2026-10-12 定案(主人):回灌**模拟用户消息**(source.kind='user')+ **唤醒**父会话(一档)。
34
- * `followup` 就是 `inject` 的唤醒档(inject=next-step 不唤醒;followup=next-turn 唤醒),
35
- * 所以"注入 + 唤醒"用 followup。
36
- * 原因(实测结论):`inject` 落 `agent/inbox/spliced **target=next-step**` —— 排队到下次组包、
37
- * **不产生回合**,因此既没有 turn 触发节点、**UI 上也什么都没有**。
38
- * 而 `followup` 落 `target=next-turn` ⇒ 产生回合 ⇒ 被渲染成 `TurnTriggerNodeView`(那个「白框」)。
39
- * 代价:回灌会**唤醒父会话跑一轮**(烧 token),故正文里加了一行"无需回复"提示。
40
- * → 三档(mode=3)要的是"进上下文但**不唤醒**",所以那一档**强制走 inject**。
41
- *
42
- * ⚠️ 回灌消息的形状**必须**对齐宿主「子会话结算通知」(createSettlementMessage):
43
- * { id, role:'user', content:[摘要行, 结尾正文引导语, ...正文块],
44
- * source:{ kind:'subagent-settled', form:'notice', summary, senderSessionId } }
45
- *
46
- * ⚠️ 注入前必须过 isInjectableMessage() 自检(fail-closed)。宿主的顺序是
47
- * **先 append 落盘、后读 `msg.source.kind`**:形状不合法时坏记录已经写进
48
- * `agent/inbox/spliced.data.inserted[]`,之后投影抛错 —— 会话文件从此无法加载。
49
- * 事故实例:会话 9643a885 的 seq 4222 曾被写成 `inserted: ["<字符串>"]`。
50
- *
51
- * 用法:
52
- * import { register } from './lib/session_watch_lib.mjs';
53
- * await register(root, { parentAgentId, childSessionId, label, mode, sender, replyTarget });
54
- */
55
- /**
56
- * 版本标记:供调用方打印,用来确认**热刷后加载到的到底是哪一版**。
57
- * 改动本文件时顺手把这个号 +1(或换日期),排查"改了不生效"时一眼就能看出来。
58
- */
59
- export const __LIB_VERSION__ = 'lib-v14-20261014-通用路由+扫盘解析+会话列表+父会话跟QQ对象走+二档路由隔绝';
60
-
61
- // ── ★ 2026-10-13 持久化改造(主人指示:**以本地存档为准,别只靠内存**)──────────────
62
- // 本文件的风格是"用到时动态 import";这里用**顶层 await** 一次性取到同步版 fs,
63
- // 后面的 ensureLoaded()(同步读存档)才能被同步函数(如 listWatching)直接调用。
64
- const { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } = await import('node:fs');
65
- const { dirname, join } = await import('node:path');
66
- const { fileURLToPath } = await import('node:url');
67
-
68
- /**
69
- * 盯梢名单。**放在 globalThis 上**,不是模块局部变量。
70
- *
71
- * 原因:`tools/lib/` 的 import 带了 `?v=<mtime>` 版本号(为让热刷生效),
72
- * 于是每改一次本文件就会产生一个**新的模块实例**。若名单是模块局部的,
73
- * 改一次 lib 就把已登记的盯梢对象全丢了。放 globalThis 上跨实例共享。
74
- */
75
- const WATCHING_KEY = Symbol.for('dsh-qqbot.session-watch.watching');
76
- /**
77
- * ★ 2026-10-13:**扩展工具侧注入的 sender/replyTarget**(跨模块实例共享)。
78
- * 工具 env 里**一定有**这两样(扩展工具 env = `{cwd, manager, sender, replyTarget, exec, ctx, logger}`),
79
- * 而插件根 ctx(handler 拿到的 root)上实测**拿不到** sender ⇒ 单靠 root 补不回 QQ 转发。
80
- * 所以让扩展工具每次被调用时顺手写进来,handler 侧再读它去补 fwd。
81
- */
82
- const FWD_KEY = Symbol.for('dsh-qqbot.session-watch.fwd');
83
-
84
- /**
85
- * 供扩展工具调用:把本次 env 的 sender/replyTarget 交给回灌库。
86
- * 调一次之后,回灌库在"父会话发言"时就能把 QQ 转发能力补回来(重启后尤其需要)。
87
- * @returns {boolean} 是否记住
88
- */
89
- export function rememberFwd(sender, replyTarget) {
90
- try {
91
- if (sender && replyTarget) {
92
- globalThis[FWD_KEY] = { sender, replyTarget };
93
- return true;
94
- }
95
- return false;
96
- } catch { return false; }
97
- }
98
- const watching = (globalThis[WATCHING_KEY] ??= new Map()); // childSessionId -> entry
99
-
100
- /**
101
- * ★★ 2026-10-14:**父会话跟着「QQ 对象」走**(主人定:绑的应该是 QQ 对象,不是那一刻的会话 id)
102
- *
103
- * 病根:原来 `parentAgentId` 是绑定时写死的 session id,回灌直接 `agents.get(那个 id)`。
104
- * 在 QQ 里发 `/bot-new` 会**新开一个会话**(新 id),名单里那条记录却还指着旧会话
105
- * ⇒ 回灌继续落进旧会话;而"转发到 QQ"那一路用的是 openid、照旧正常 ⇒ 表面上完全看不出错。
106
- *
107
- * 修法(不需要插件内部 API):记一张 `peerKey = scope:peerId`(QQ 对象)→ **最近一次为该对象发言的
108
- * 会话 id** 的表;回灌前先按 peerKey 取最新会话,取不到才回落到写死的旧 id。
109
- * `/bot-new` 之后该对象的下一条消息必然落到新会话 ⇒ 这张表立刻学到新 id ⇒ 回灌自动跟过去。
110
- *
111
- * 自愈:老记录(没有 peerKey)在"它的父会话下一次发言"时自动补上 peerKey —— 与 fwd 补回同一套路数。
112
- */
113
- const PEER_KEY = Symbol.for('dsh-qqbot.session-watch.peerLatest');
114
- const peerLatest = (globalThis[PEER_KEY] ??= new Map()); // peerKey -> sessionId
115
-
116
- /** 从**会话对象**里取 QQ 对象键(scope:peerId)。刻意不用 `o.id` —— 那是会话 id,不是 peer */
117
- function peerKeyOfSession(s) {
118
- try {
119
- if (!s) return '';
120
- const peerId = String(s.peerId ?? s.groupOpenid ?? s.groupId ?? '');
121
- if (!peerId) return '';
122
- const scope = String(s.scope ?? s.peerScope ?? '') || 'group';
123
- return scope + ':' + peerId;
124
- } catch { return ''; }
125
- }
126
-
127
- /** 从 **replyTarget / peer 视图**里取 QQ 对象键 */
128
- function peerKeyOfTarget(rt) {
129
- try {
130
- if (!rt) return '';
131
- const id = String(rt.peerId ?? rt.targetId ?? rt.groupOpenid ?? rt.openid ?? rt.groupId ?? rt.id ?? '');
132
- if (!id) return '';
133
- const scope = String(rt.scope ?? rt.kind ?? '') || 'group';
134
- return scope + ':' + id;
135
- } catch { return ''; }
136
- }
137
-
138
- /** 学到"这个 QQ 对象最近在哪个会话里说话",顺手给老盯梢补 peerKey(自愈) */
139
- export function notePeerSeen(session, sid) {
140
- try {
141
- const pk = peerKeyOfSession(session);
142
- if (!pk || !sid) return false;
143
- let changed = peerLatest.get(pk) !== sid;
144
- if (changed) peerLatest.set(pk, sid);
145
- for (const w of watching.values()) {
146
- if (!w.peerKey && w.parentAgentId === sid) { w.peerKey = pk; changed = true; }
147
- }
148
- if (changed) void persist(); // 落盘失败静默,不影响监听
149
- return changed;
150
- } catch { return false; }
151
- }
152
-
153
- /** 回灌该投给谁:优先"该 QQ 对象当前所在的会话",其次绑定时写死的父会话(老行为) */
154
- function resolveParentId(w) {
155
- try {
156
- const pk = String(w?.peerKey ?? '');
157
- const latest = pk ? String(peerLatest.get(pk) ?? '') : '';
158
- return latest || String(w?.parentAgentId ?? '');
159
- } catch { return String(w?.parentAgentId ?? ''); }
160
- }
161
-
162
- /**
163
- * 默认存档路径:`{dataRoot}/.qqbot-extensions/tools/data/session-watch-watching.json`
164
- * (**与 `vote.json` 同一个 data 目录** —— 对齐既有约定:扩展各类的存档都放
165
- * `{数据根}/.qqbot-extensions/<类型>/data/<名字>.json`)。
166
- * 本文件在 `.../tools/lib/` ⇒ `../data/` 正好是 `tools/data/`。
167
- * 为什么要兜底:`setStateFile()` 此前**全项目无人调用** ⇒ `stateFileOf()` 恒为 '' ⇒
168
- * `persist()` 里 `if (!file) return` 直接空转 ⇒ **名单从来没落过盘**(重启自然恢复不了)。
169
- */
170
- const DEFAULT_STATE_FILE = (() => {
171
- try { return fileURLToPath(new URL('../data/session-watch-watching.json', import.meta.url)); }
172
- catch { return ''; }
173
- })();
174
-
175
- let loadedOnce = false;
176
-
177
- /**
178
- * ★ 持久化读回(主人 2026-10-13 指示:**以本地存档为准,不要只靠内存**)。
179
- * 幂等:只从文件读一次;此后内存是运行期缓存,所有写操作都会 persist() 回文件。
180
- * 同步实现 ⇒ 可被 listWatching() / handler() 这类同步路径直接调用。
181
- * @returns 读回后内存里的条目数
182
- */
183
- export function ensureLoaded() {
184
- if (loadedOnce) return watching.size;
185
- loadedOnce = true;
186
- try {
187
- const file = stateFileOf();
188
- if (!file) return watching.size;
189
- const j = JSON.parse(readFileSync(file, 'utf8'));
190
- const rows = Array.isArray(j?.rows) ? j.rows : [];
191
- // ★ 2026-10-14:读回"QQ 对象 → 最近发言会话"表(父会话跟着 QQ 对象走的依据)
192
- try { for (const [k, v] of Object.entries(j?.peers ?? {})) if (k && v) peerLatest.set(String(k), String(v)); } catch { /* ignore */ }
193
- for (const r of rows) {
194
- const child = String(r?.child ?? '').trim();
195
- const parent = String(r?.parent ?? '').trim();
196
- if (!child || !parent) continue;
197
- if (watching.has(child)) continue;
198
- watching.set(child, {
199
- parentAgentId: parent,
200
- label: String(r?.label ?? ''),
201
- mode: Number(r?.mode) === 2 ? 2 : (Number(r?.mode) === 3 ? 3 : 1),
202
- shortId: shortSessionId(child),
203
- name: String(r?.name ?? r?.label ?? ''),
204
- preset: String(r?.preset ?? ''),
205
- workspace: String(r?.workspace ?? ''),
206
- peerName: String(r?.peerName ?? ''),
207
- peerKey: String(r?.peerKey ?? ''),
208
- // ⚠️ 重启后拿不到 sender/replyTarget ⇒ 先恢复"回灌父会话",
209
- // QQ 转发等下次 register(或主人重挂)时补上 ⇒ 这里如实置空、不假装就绪。
210
- fwd: null,
211
- lastText: '', texts: [], errors: [], seen: 0, firedAt: 0, lastForwarded: '',
212
- });
213
- }
214
- } catch { /* 读不到就当空名单 */ }
215
- return watching.size;
216
- }
217
-
218
- /**
219
- * ★ 启动恢复(给启动钩子用):读回存档 + **重装监听器**。
220
- * 名单以文件为准;而监听器(`root.on('session/event')`)是内存态、重启必丢 ⇒ 只能靠这里重装。
221
- */
222
- export async function rehydrate(root) {
223
- const n = ensureLoaded();
224
- try { installHook(root); } catch { /* 装不上就只恢复名单 */ }
225
- // ★ 2026-10-13:顺手把 QQ 转发能力也补上 —— 只要 `session_watch` 工具刚把 sender/replyTarget
226
- // 注入过(rememberFwd),这里就能立刻补回,**不必等父会话下一次发言**。
227
- let fwdFixed = 0;
228
- try {
229
- for (const [, w] of watching) if (hydrateFwd(w, root, null)) fwdFixed += 1;
230
- } catch { /* ignore */ }
231
- return { restored: n, hooked, fwdFixed };
232
- }
233
-
234
- /**
235
- * 盯梢名单落盘(2026-10-12 新增)。
236
- *
237
- * 为什么要:名单原本只在内存里,**dsh 一重启,之前 attach 的盯梢全没了**。
238
- * 落盘后由启动钩子(`.qqbot-extensions/hooks/`)在宿主启动时读回来重新登记 ——
239
- * 这正是主人要的"让用户写一些在运行 dsh 时启动的东西"的第一个用例。
240
- */
241
- const STATE_KEY = Symbol.for('dsh-qqbot.session-watch.stateFile');
242
- // ★ 兜底默认路径:没人调 setStateFile() 时也能落盘/读回(见上面 DEFAULT_STATE_FILE 的说明)
243
- const stateFileOf = () => String(globalThis[STATE_KEY] || DEFAULT_STATE_FILE || '');
244
-
245
- /** 记下状态文件路径(由 register 的调用方给;没给就不落盘) */
246
- export function setStateFile(p) {
247
- try { globalThis[STATE_KEY] = String(p || ''); } catch { /* ignore */ }
248
- }
249
-
250
- /** 把当前名单落盘(静默失败:落不了盘只影响"重启后自动恢复",不影响回灌本身) */
251
- async function persist() {
252
- const file = stateFileOf();
253
- if (!file) return;
254
- try {
255
- const { writeFileSync, mkdirSync } = await import('node:fs');
256
- const { dirname } = await import('node:path');
257
- mkdirSync(dirname(file), { recursive: true });
258
- const rows = [...watching.entries()].map(([child, w]) => ({
259
- child,
260
- parent: w.parentAgentId,
261
- label: w.label ?? '',
262
- name: w.name ?? '',
263
- preset: w.preset ?? '',
264
- workspace: w.workspace ?? '',
265
- mode: w.mode ?? 1,
266
- peerName: w.peerName ?? '',
267
- peerKey: w.peerKey ?? '',
268
- }));
269
- // ★ 2026-10-14:把"QQ 对象 → 最近发言会话"表一起落盘(父会话跟着 QQ 对象走的依据)
270
- const peers = {};
271
- for (const [k, v] of peerLatest.entries()) if (k && v) peers[k] = v;
272
- writeFileSync(file, JSON.stringify({ v: 1, at: Date.now(), rows, peers }, null, 2), 'utf8');
273
- } catch { /* ignore */ }
274
- }
275
-
276
- /** 读回落盘的名单(给启动钩子用;返回原始行数组) */
277
- export async function loadPersisted() {
278
- const file = stateFileOf();
279
- if (!file) return [];
280
- try {
281
- const { readFileSync } = await import('node:fs');
282
- const j = JSON.parse(readFileSync(file, 'utf8'));
283
- return Array.isArray(j?.rows) ? j.rows : [];
284
- } catch { return []; }
285
- }
286
-
287
- /** 回灌钩子总开关。false = 正常挂 `session/event` 监听。 */
288
- const HOOK_DISABLED = false;
289
-
290
- /** 监听只装一次(跨模块实例去重);handler 指针让新实例能立刻接管旧监听。 */
291
- const HOOK_KEY = Symbol.for('dsh-qqbot.session-watch.hook');
292
- const HANDLER_KEY = Symbol.for('dsh-qqbot.session-watch.handler');
293
- let hooked = false;
294
-
295
- /**
296
- * turn/end 的 data.reason → 人话。
297
- * 口径来自 webui 的两条文案(dsh-client-ui-chat/lib/client.js):
298
- * "message.turnProcess.worked" = 已完成 ← 正常跑完
299
- * "message.stopped" = 已停止 ← 被停止/中断
300
- * 宿主在 index.js:912 把 event.data.reason 记进 inflight.endReason,webui 据此显示。
301
- */
302
- function reasonText(reason) {
303
- const r = String(reason ?? '').toLowerCase();
304
- if (!r) return '结束';
305
- if (/stop|abort|cancel|interrupt|halt/.test(r)) return '已停止';
306
- if (/complet|done|finish|success|ok/.test(r)) return '已完成';
307
- if (/error|fail/.test(r)) return '出错';
308
- return r; // 未知取值就原样带出来,便于以后补映射
309
- }
310
-
311
- /**
312
- * `notice` 摘要行的长度上限,与宿主 `dsh-llm` 的 CONTEXT_SUMMARY_MAX_CHARS 保持一致。
313
- * 宿主原文注释:producer 的一行说明会写进持久日志,所以要限长。
314
- */
315
- const CONTEXT_SUMMARY_MAX_CHARS = 120;
316
-
317
- /** 把摘要行压到上限内(超出用省略号),口径照抄宿主 dsh-llm 的 boundContextSummary()。 */
318
- function boundContextSummary(summary) {
319
- const t = String(summary ?? '');
320
- return t.length <= CONTEXT_SUMMARY_MAX_CHARS ? t : `${t.slice(0, CONTEXT_SUMMARY_MAX_CHARS - 1)}…`;
321
- }
322
-
323
- /**
324
- * 取会话短 id 用于显示。
325
- * ⚠️ 子会话 id 形如 `session-f147236a-…`,直接 slice(0,8) 只会得到无意义的 `session-`。
326
- * 所以先剥掉 `session-` 前缀再截断。
327
- */
328
- export function shortSessionId(id) {
329
- const s = String(id ?? '');
330
- return (s.startsWith('session-') ? s.slice(8) : s).slice(0, 8);
331
- }
332
-
333
- /**
334
- * 行首归属标记(2026-10-12 主人定:除了短 id,还要**会话名 / 预设名 / 工作区**)。
335
- *
336
- * ⚠️ 排版有硬约束:QQ 入站引用块只带被引原文**前 60 字**,而引用回流就靠这一行认路。
337
- * 所以顺序是**路由键打头、其余信息跟在后面** —— 即使后面被截掉,`【子会话 xxxx` 也稳稳留在前 15 字内。
338
- * 路由键后面的 `】` **不保证存在**(可能正好被截断),因此解析正则**不要求右括号**。
339
- *
340
- * 例:`【子会话 87c87c3b · 回灌转发自测 · standard · 鲸鱼娘】`(约 40 字,安全)
341
- */
342
- export function ownerLine(parts) {
343
- const p = (typeof parts === 'string') ? { shortId: parts } : (parts ?? {});
344
- const seg = [`【子会话 ${String(p.shortId ?? '').slice(0, 8)}`];
345
- for (const v of [p.name, p.preset, p.workspace]) {
346
- const s = String(v ?? '').trim();
347
- if (s) seg.push(s.replace(/[·】\n]/g, ' ').slice(0, 24)); // 别让分隔符/换行混进来
348
- }
349
- return seg.join(' · ') + '】';
350
- }
351
-
352
- /**
353
- * 认出归属标记(引用回流的路由键)。
354
- * **故意不要求右括号** —— 引用块只带前 60 字,归属行尾可能被截掉。
355
- * 同时容忍中间的空格与全角/半角差异。
356
- */
357
- const OWNER_RE = /【\s*子会话\s*([0-9a-fA-F]{4,12})/;
358
-
359
- /** 从一段文本里抽归属短 id(找不到返回 '') */
360
- export function parseOwner(text) {
361
- const m = OWNER_RE.exec(String(text ?? ''));
362
- return m ? m[1].toLowerCase() : '';
363
- }
364
-
365
- /**
366
- * 短 id → 完整会话 id。**当场查**,不依赖任何持久台账(主人 2026-10-12 明确口径)。
367
- * 会话注册表的 API 形状随版本变,这里逐种试,全部失败就返回 ''。
368
- */
369
- // ── ★ 2026-10-14 主人需求:**通用路由**(正文里带会话 id ⇒ 投递到那个会话)─────────────
370
- /**
371
- * 认两种写法(**不要求行首**,写在句子中间也认):
372
- * `[s:xxxxxxxx]` ← 推荐;短 id(uuid 前 8 位)或完整 uuid 都行
373
- * `【会话 xxxxxxxx】` ← 兼容"直接复制模板再改"
374
- *
375
- * 与 `routeQuoteBack`(引用回流)的分工:
376
- * · `routeQuoteBack` 只认 `【子会话 xxxx】`,且**必须是已盯梢条目的父会话在说话** —— 语义是"回";
377
- * · 本组函数认**任意 id**、**不需要绑定**、也不用先盯梢 —— 语义是"去"。
378
- */
379
- const ROUTE_RE = /(?:\[s:|【\s*会话\s*)([0-9a-zA-Z][0-9a-zA-Z-]{2,63})\s*\]?】?/;
380
-
381
- /** 从正文里抽路由目标 key(返回 '' = 这不是一条路由消息) */
382
- export function parseRouteKey(text) {
383
- const m = ROUTE_RE.exec(String(text ?? ''));
384
- return m ? m[1] : '';
385
- }
386
-
387
- /** 剥掉路由标记 —— 送进目标会话的是"去掉标记后的正文" */
388
- export function stripRouteMark(text) {
389
- return String(text ?? '')
390
- .replace(new RegExp(ROUTE_RE.source, 'g'), ' ')
391
- .replace(/[ \t]{2,}/g, ' ')
392
- .trim();
393
- }
394
-
395
- /** `~/.dsh/sessions` 根目录(Windows 用 USERPROFILE,其余用 HOME) */
396
- function sessionsRootDir() {
397
- const home = String(process.env.USERPROFILE || process.env.HOME || '').trim();
398
- return home ? join(home, '.dsh', 'sessions') : '';
399
- }
400
-
401
- /**
402
- * **扫盘**把短 id 解析成完整会话 id —— **不依赖对方是否 live**(这是"任何已有会话"的关键)。
403
- * 目录形状:`~/.dsh/sessions/<工作区转义名>/<uuid>/`。
404
- * @returns {{id: string, workspace: string}} 找不到时 id 为 ''
405
- */
406
- export function findSessionOnDisk(key) {
407
- const want = String(key ?? '').toLowerCase().trim();
408
- if (!want) return { id: '', workspace: '' };
409
- // 已经是完整 uuid ⇒ 直接认
410
- if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(want)) {
411
- return { id: want, workspace: '' };
412
- }
413
- if (want.length < 4) return { id: '', workspace: '' };
414
- const root = sessionsRootDir();
415
- if (!root) return { id: '', workspace: '' };
416
- try {
417
- for (const ws of readdirSync(root)) {
418
- let entries = [];
419
- try { entries = readdirSync(join(root, ws)); } catch { continue; }
420
- for (const d of entries) {
421
- const raw = String(d).toLowerCase();
422
- // ⚠️ 会话目录名**可能带前缀**(子会话是 `session-<uuid>`)⇒ 两边都过 shortSessionId 再比,
423
- // 否则像 `cf871e99` 这种短 id 会解析失败(本轮实测踩到)。
424
- const sh = shortSessionId(String(d)).toLowerCase();
425
- if (sh.startsWith(want) || raw.startsWith(want)) return { id: String(d), workspace: String(ws) };
426
- }
427
- }
428
- } catch { /* ignore */ }
429
- return { id: '', workspace: '' };
430
- }
431
-
432
- /**
433
- * 列会话目录(按 mtime 从新到旧)—— 给「/会话列表」命令用。
434
- * @param {string} [workspaceDir] 传了就只列该工作区;不传列全部
435
- */
436
- export function listSessionDirs(workspaceDir) {
437
- const root = sessionsRootDir();
438
- if (!root) return [];
439
- const out = [];
440
- const pushWs = (ws) => {
441
- const wsDir = join(root, ws);
442
- let entries = [];
443
- try { entries = readdirSync(wsDir); } catch { return; }
444
- for (const d of entries) {
445
- const dir = join(wsDir, d);
446
- let mtime = 0;
447
- try { mtime = statSync(dir).mtimeMs; } catch { /* ignore */ }
448
- out.push({ id: String(d), short: shortSessionId(String(d)), workspace: String(ws), mtime });
449
- }
450
- };
451
- try {
452
- if (workspaceDir) pushWs(workspaceDir);
453
- else for (const ws of readdirSync(root)) pushWs(ws);
454
- } catch { /* ignore */ }
455
- return out.sort((a, b) => (b.mtime || 0) - (a.mtime || 0));
456
- }
457
-
458
- /** 列出 `~/.dsh/sessions` 下的工作区转义目录名(给向导第一步用) */
459
- export function listWorkspaceDirs() {
460
- const root = sessionsRootDir();
461
- if (!root) return [];
462
- try { return readdirSync(root).filter((d) => !String(d).startsWith('.')); } catch { return []; }
463
- }
464
-
465
- export function resolveShortId(root, short) {
466
- const want = String(short ?? '').toLowerCase();
467
- if (!want) return '';
468
- const hit = (id) => {
469
- const s = String(id ?? '');
470
- return s && shortSessionId(s).toLowerCase().startsWith(want) ? s : '';
471
- };
472
- try {
473
- // ① 最快的一条:agents 服务上按 id 前缀找(若提供了 list)
474
- const svc = (k) => { try { return root?.get?.(k); } catch { return undefined; } };
475
- for (const key of ['sessions', 'agents']) {
476
- const s = svc(key);
477
- if (!s) continue;
478
- const bags = [];
479
- if (typeof s.list === 'function') { try { bags.push(s.list()); } catch { /* ignore */ } }
480
- if (typeof s.values === 'function') { try { bags.push([...s.values()]); } catch { /* ignore */ } }
481
- if (typeof s.all === 'function') { try { bags.push(s.all()); } catch { /* ignore */ } }
482
- if (Array.isArray(s)) bags.push(s);
483
- for (const bag of bags) {
484
- const arr = Array.isArray(bag) ? bag : (bag && typeof bag === 'object' ? Object.values(bag) : []);
485
- for (const it of arr) {
486
- const id = String(it?.id ?? it?.sessionId ?? it ?? '');
487
- const got = hit(id);
488
- if (got) return got;
489
- }
490
- }
491
- }
492
- } catch { /* ignore */ }
493
- return '';
494
- }
495
-
496
- /**
497
- * 把 `turn/end` 的 reason 归一成字符串。
498
- *
499
- * ⚠️ 2026-10-12 实测:`event.data.reason` **不是字符串而是对象**,形如
500
- * `{kind:'completed'}` 或 `{kind:'aborted', reason:{kind:'user'}}`。
501
- * 旧代码直接 `String(reason)` ⇒ 摘要行里出现 `回合[object object](reason=[object Object])`。
502
- * 本函数优先取最外层的 `kind`,没有就下钻内层 `reason`,都不是才退回 String()。
503
- */
504
- export function reasonKind(value) {
505
- if (value === null || value === undefined) return '';
506
- if (typeof value === 'string') return value;
507
- if (typeof value === 'object') {
508
- if (typeof value.kind === 'string' && value.kind) return value.kind;
509
- if (value.reason !== undefined && value.reason !== value) return reasonKind(value.reason);
510
- if (typeof value.status === 'string' && value.status) return value.status;
511
- if (typeof value.stopReason === 'string' && value.stopReason) return value.stopReason;
512
- }
513
- return String(value);
514
- }
515
-
516
- /**
517
- * 把各种可能的 content 形状压成纯文本。
518
- *
519
- * ★ 2026-10-12 修(主人实测):**只取 `type === 'text'` 的正文块**。
520
- * 早先的过滤条件是 `x.type === 'text' || typeof x.text === 'string'` ——
521
- * 而 **reasoning(思考)块同样带 `.text` 字符串**,于是思考被一起并进来,
522
- * 回灌的"结尾正文"里冒出一整段英文思考(子会话 3bee83ac 那次实测)。
523
- * reasoning / tool-call 等块一律丢弃。
524
- */
525
- function asText(c) {
526
- if (typeof c === 'string') return c.trim();
527
- if (Array.isArray(c)) {
528
- return c
529
- .filter((x) => x && x.type === 'text' && typeof x.text === 'string')
530
- .map((x) => String(x.text))
531
- .join('\n')
532
- .trim();
533
- }
534
- if (c && typeof c === 'object') {
535
- if (c.type === 'reasoning') return ''; // 思考块不算正文
536
- if (typeof c.text === 'string') return String(c.text).trim();
537
- if (Array.isArray(c.blocks)) return asText(c.blocks); // 有些版本正文藏在 blocks 里
538
- }
539
- return '';
540
- }
541
-
542
- /** 从事件里尽力抽正文(assistant/message 的形状随版本变,逐层试) */
543
- function textOf(ev) {
544
- const cands = [
545
- ev?.data?.message?.content,
546
- ev?.data?.content,
547
- ev?.message?.content,
548
- ev?.data?.text,
549
- ev?.text,
550
- ev?.data?.message?.text,
551
- ];
552
- for (const c of cands) {
553
- const t = asText(c);
554
- if (t) return t;
555
- }
556
- return '';
557
- }
558
-
559
- /** 兜底:直接从会话实例取"最后一条助手消息"的正文 */
560
- function lastAssistantText(root, sid) {
561
- try {
562
- const sess = root.get('sessions')?.get?.(sid);
563
- const msgs = sess?.deriveMessages?.() ?? [];
564
- for (let i = msgs.length - 1; i >= 0; i -= 1) {
565
- const m = msgs[i];
566
- const role = String(m?.role ?? m?.type ?? '');
567
- if (role.includes('assistant')) {
568
- const t = asText(m?.content);
569
- if (t) return t;
570
- }
571
- }
572
- } catch { /* ignore */ }
573
- return '';
574
- }
575
-
576
- /**
577
- * 注入前的形状自检(fail-closed)。
578
- *
579
- * 复刻宿主 v4 的准入条件(dsh-session-persistence-jsonl/lib/worker.cjs):
580
- * ① `agent/inbox/spliced` 的 `inserted[]` 每项必须 `isSessionFormatJsonObject`;
581
- * ② 每项的 `source` 必须是对象、`kind` 为非空字符串、且 !== 'plugin'
582
- * (源码原文:`format v4 message requires a producer-owned source kind`)。
583
- *
584
- * 为什么必须自检而不是交给 inject():宿主是**先 append 落盘、后读 source.kind** 的顺序。
585
- * 传进非对象时,坏记录已经写进 `inserted[]`,之后投影抛错 —— 文件从此无法加载。
586
- * 事故实例:会话 9643a885 的 seq 4222 被写成 `inserted: ["<字符串>"]`,整个会话读不出来。
587
- */
588
- export function isInjectableMessage(m) {
589
- if (!m || typeof m !== 'object' || Array.isArray(m)) return false;
590
- if (typeof m.role !== 'string' || !m.role) return false;
591
- if (!Array.isArray(m.content) || m.content.length === 0) return false;
592
- const src = m.source;
593
- if (!src || typeof src !== 'object' || Array.isArray(src)) return false;
594
- if (typeof src.kind !== 'string' || !src.kind || src.kind === 'plugin') return false;
595
- return true;
596
- }
597
-
598
- /** 造一条纯文本 user 消息(供 inject / followup 用;形状已过 isInjectableMessage) */
599
- function userText(text) {
600
- return {
601
- id: (globalThis.crypto?.randomUUID?.() ?? ('inj-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8))),
602
- role: 'user',
603
- content: [{ type: 'text', text: String(text ?? '') }],
604
- source: { kind: 'user' },
605
- };
606
- }
607
-
608
- /**
609
- * 构造一条「子会话结算通知」形状的回灌消息(纯函数,便于单测)。
610
- *
611
- * 形状**对齐宿主** dsh-subagent/lib/index.js 的 `createSettlementMessage()`:
612
- * source : { kind:'subagent-settled', form:'notice', summary, senderSessionId }
613
- * content: [ 摘要行, 结尾正文引导语, ...正文块 ],role 由 createUserMessage 固定为 'user'
614
- *
615
- * 采用宿主形状的三个理由:
616
- * ① kind 是宿主自有的 producer-owned 值,不再冒充真人 user 发言;
617
- * ② senderSessionId 明确归属到具体子会话,UI 侧归进**子任务**那条通道而不是混进
618
- * 用户真实发言流里 —— 这与上一轮「回灌插错位置」是同一类隐患;
619
- * ③ summary 与宿主同口径(dsh-llm CONTEXT_SUMMARY_MAX_CHARS = 120)。
620
- *
621
- * @param {{sessionId?: string, label?: string, rawReason?: string, text?: string}} input
622
- * @returns 可直接交给 agent.inject() 的完整消息对象
623
- */
624
- export function buildSettlementNotice(input = {}) {
625
- const sid = String(input.sessionId ?? '');
626
- const label = String(input.label ?? '');
627
- const rawReason = String(input.rawReason ?? '');
628
- const stage = reasonText(rawReason);
629
- const summary = boundContextSummary(
630
- `子会话${label ? '「' + label + '」' : ''} ${shortSessionId(sid)}… 回合${stage}` +
631
- `${rawReason && rawReason !== stage ? '(reason=' + rawReason + ')' : ''}`,
632
- );
633
- return {
634
- id: (globalThis.crypto?.randomUUID?.() ?? ('inj-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8))),
635
- role: 'user',
636
- content: [
637
- // ★ 主人 2026-10-12 定:模拟用户消息的**首行直接给出源会话 id**(完整 id)。
638
- { type: 'text', text: '【来自会话 ' + sid + '】' },
639
- { type: 'text', text: summary },
640
- { type: 'text', text: '它的结尾正文:' },
641
- { type: 'text', text: String(input.text ?? '') },
642
- { type: 'text', text: '(这是子会话的自动回灌,父会话无需回复。)' },
643
- ],
644
- // ★ 2026-10-12 主人定案:回灌**一律模拟用户消息**(source.kind='user'),
645
- // 不再伪装成子会话结算通知 / 系统消息 / 开发者消息。
646
- source: { kind: 'user' },
647
- };
648
- }
649
-
650
- // ─────────────────────────── 转发到 QQ ───────────────────────────
651
-
652
- /**
653
- * 往「父会话所在的 QQ」发一条消息。
654
- *
655
- * 链路(**全部复用插件已有的能力**,本库不自己重写降级/被动逻辑):
656
- * · `sender.sendMarkdown(replyTarget, text)` —— replyTarget 自带最近 msgId ⇒ 被动回复;
657
- * 插件的 sendMarkdown 自带 markdown → 纯文本的降级链。
658
- * · 失败再退 `sender.sendText(replyTarget, text)`(纯文本兜底)。
659
- *
660
- * @returns 人话结果('' = 没配 sender,静默不发)
661
- */
662
- async function forwardToQq(entry, text) {
663
- const fwd = entry?.fwd;
664
- const body = String(text ?? '').trim();
665
- // ★ 2026-10-15:**不再静默**。之前三个条件任一不满足就 `return ''`,日志里一个字都没有,
666
- // "重启后那段时间子会话内容悄悄没转发"因此无从定位(主人实测踩到)。
667
- if (!fwd?.sender || !fwd?.replyTarget || !body) {
668
- void swDiag('forward-skip short=' + String(entry?.shortId ?? '?')
669
- + ' fwd=' + (fwd ? 'obj' : String(fwd))
670
- + ' sender=' + !!fwd?.sender + ' replyTarget=' + !!fwd?.replyTarget
671
- + ' bodyLen=' + body.length);
672
- return '';
673
- }
674
- const target = fwd.replyTarget;
675
-
676
- /**
677
- * ★★ 2026-10-15:**摘掉 msgId 的"主动版" target** ★★
678
- * 实测真凶:`fwd.replyTarget` 里钉着**绑定那一刻的 msgId**(为走"被动回复"),
679
- * 而 QQ 的被动回复 **msg_id 会过期** ⇒ 老盯梢(如 bee798c0)发送时报
680
- * `API Error: 回复消息msg_id已过期`,markdown/纯文本两条降级链**都**因此失败,
681
- * 内容静默丢失。新建的盯梢 msgId 新鲜 ⇒ 正常。
682
- * ⇒ 发送失败时摘掉 msgId 再发一次 = 转"主动发送"(会耗主动配额,但总比丢消息好)。
683
- */
684
- const activeTarget = (() => {
685
- try {
686
- if (!target || typeof target !== 'object') return null;
687
- const t = { ...target };
688
- let touched = false;
689
- for (const k of ['msgId', 'msg_id', 'messageId', 'referenceMessageId']) {
690
- if (k in t) { delete t[k]; touched = true; }
691
- }
692
- return touched ? t : null;
693
- } catch { return null; }
694
- })();
695
-
696
- /**
697
- * ★ 2026-10-15 主人定:**同一 msgId 用满 4 条就直接转主动**(不等它失败)。
698
- * 被动回复有两条硬限制:①同一 msg_id 最多 ~4-5 条;②msg_id 会过期。
699
- * 插件的 outbound.ts 对"AI 正文"有 ADAPTIVE_MAX_PASSIVE=5 的同类计数,但**转发这条路没有**,
700
- * 所以这里自己数:同一 msgId 发到第 4 条起就摘掉它走主动。
701
- */
702
- const _midOf = (t) => String(t?.msgId ?? t?.msg_id ?? t?.messageId ?? '');
703
- const passiveMid = _midOf(target);
704
- const counts = (entry.__fwdPassiveCounts ??= new Map());
705
- const used = passiveMid ? (counts.get(passiveMid) ?? 0) : 0;
706
- const PASSIVE_LIMIT = 4;
707
- const skipPassive = !passiveMid || used >= PASSIVE_LIMIT;
708
- if (skipPassive) {
709
- void swDiag('forward-passive-skip short=' + String(entry?.shortId ?? '?')
710
- + ' mid=' + (passiveMid ? passiveMid.slice(0, 12) : '-') + ' used=' + used);
711
- }
712
-
713
- const trySend = async (tg) => {
714
- try {
715
- if (typeof fwd.sender.sendMarkdown === 'function') {
716
- await fwd.sender.sendMarkdown(tg, body);
717
- return 'md';
718
- }
719
- } catch (e) {
720
- const em = String(e?.message ?? e);
721
- try {
722
- if (typeof fwd.sender.sendText === 'function') {
723
- await fwd.sender.sendText(tg, body);
724
- return 'text';
725
- }
726
- } catch (e2) { throw new Error(em + ' | text:' + String(e2?.message ?? e2)); }
727
- throw new Error(em);
728
- }
729
- try {
730
- if (typeof fwd.sender.sendText === 'function') {
731
- await fwd.sender.sendText(tg, body);
732
- return 'text';
733
- }
734
- } catch (e) { throw new Error(String(e?.message ?? e)); }
735
- return '';
736
- };
737
-
738
- // ① 先按原样(被动回复,省主动配额)
739
- try {
740
- // ★ 同一 msgId 用满 4 条 ⇒ 直接跳过被动、走下面的主动分支(不再等它失败)
741
- if (skipPassive) throw new Error('skip-passive: mid=' + (passiveMid || '-') + ' used=' + used);
742
- const how = await trySend(target);
743
- if (how) {
744
- if (passiveMid) counts.set(passiveMid, used + 1);
745
- void swDiag('forward-ok(' + how + ') short=' + String(entry?.shortId ?? '?') + ' len=' + body.length
746
- + ' passive=' + (passiveMid ? passiveMid.slice(0, 12) + '#' + (used + 1) : '-'));
747
- return how;
748
- }
749
- } catch (e1) {
750
- void swDiag('forward-passive-fail short=' + String(entry?.shortId ?? '?')
751
- + ' err=' + String(e1?.message ?? e1));
752
- // ② 失败 ⇒ 摘掉 msgId 重发(主动)。这是"msg_id 过期"的正解。
753
- if (activeTarget) {
754
- try {
755
- const how2 = await trySend(activeTarget);
756
- if (how2) {
757
- void swDiag('forward-ok-active(' + how2 + ') short=' + String(entry?.shortId ?? '?')
758
- + ' len=' + body.length + '(被动失败后转主动)');
759
- return how2 + '-active';
760
- }
761
- } catch (e2) {
762
- void swDiag('forward-active-fail short=' + String(entry?.shortId ?? '?')
763
- + ' err=' + String(e2?.message ?? e2));
764
- }
765
- } else {
766
- void swDiag('forward-active-skip short=' + String(entry?.shortId ?? '?')
767
- + '(target 上没有 msgId 可摘,或 target 形状异常)');
768
- }
769
- }
770
- void swDiag('forward-fail short=' + String(entry?.shortId ?? '?') + ' senderKeys='
771
- + (fwd?.sender ? Object.keys(fwd.sender).slice(0, 10).join(',') : '-'));
772
- return '';
773
- }
774
-
775
- /**
776
- * ★ 2026-10-15:诊断**落盘**。route-isolate 文件头留过教训:
777
- * "一开始只往 logger 写,而**从来没人注入过 logger** ⇒ 真机上完全静默、无法定位。"
778
- * 本库涉及"转发到 QQ",静默一次就是一条内容永久丢失,必须能事后追。
779
- */
780
- // ★ 2026-10-24 修复(issue #17): 原来写死 Windows 路径(D:/…) —— Linux/容器/手机上会被当成
781
- // 相对路径,在家目录里生成一个叫 "D:" 的畸形目录,日志全丢。改成跟着本文件走。
782
- const SW_DIAG_FILE = fileURLToPath(new URL('../../data/session-watch-diag.log', import.meta.url));
783
-
784
- async function swDiag(line) {
785
- try {
786
- const { appendFile, mkdir } = await import('node:fs/promises');
787
- const { dirname } = await import('node:path');
788
- await mkdir(dirname(SW_DIAG_FILE), { recursive: true });
789
- await appendFile(SW_DIAG_FILE, new Date().toISOString() + ' ' + line + '\n');
790
- } catch { /* 诊断失败不影响主链 */ }
791
- }
792
-
793
- /**
794
- * 转发到 QQ 之前,把「只给插件自己看的标记」洗掉(主人 2026-10-12 要求:"剥掉 @")。
795
- *
796
- * 为什么必须洗:子会话继承的是同一个人设,所以它写正文时会带上本插件的出站约定标记。
797
- * 而我们是用 `sender.sendMarkdown()` **直发**的,插件那层出站解析并不参与 ⇒ 这些标记会
798
- * 原样变成裸文本出现在群里。实测踩到的两条:
799
- * · `[rf:1012ad]` —— 引用标记,本来是给插件出站解析用的,转发后就是一行看不懂的裸文本;
800
- * · `<@E9020753…>` —— **QQ 提及语法,会真的在群里 @ 到人**(子会话回主人一句就被 @ 一下)。
801
- * 只洗这三类,别的(正文、换行、markdown)一律不动。
802
- */
803
- export function sanitizeForQq(text) {
804
- return String(text ?? '')
805
- .replace(/\[\s*rf\s*:[^\]]*\]/gi, '') // [rf:1012ad] 引用标记
806
- .replace(/<@[^>\s]{2,}>/g, '') // <@openid> 提及语法(会真 @ 到人)
807
- .replace(/^\s*@[^\s@]{1,24}\s+/gm, '') // 行首零散的 @某人(只吃行首那一下)
808
- .replace(/[ \t]{2,}/g, ' ') // 洗掉留下的多余空格
809
- .replace(/\n{3,}/g, '\n\n')
810
- .trim();
811
- }
812
-
813
- /** 给转发消息套上行首归属(**路由键在最前**,会话名/预设/工作区跟在后面,引用回流就靠它认路) */
814
- function withOwner(entry, text) {
815
- return ownerLine({
816
- shortId: entry?.shortId,
817
- name: entry?.name,
818
- preset: entry?.preset,
819
- workspace: entry?.workspace,
820
- }) + '\n' + sanitizeForQq(text);
821
- }
822
-
823
- // ─────────────────────────── 事件处理 ───────────────────────────
824
-
825
- /** 该会话是不是某个盯梢对象的父会话(引用回流只从父会话的入站消息里认) */
826
- function parentEntryOf(sid) {
827
- for (const [, w] of watching) if (w.parentAgentId === sid) return w;
828
- return null;
829
- }
830
-
831
- /**
832
- * 引用回流:入站消息里认出 `【子会话 xxxx】` → 把这段引用**插话**给对应子会话。
833
- *
834
- * 主人 2026-10-12 口径:**只靠行首的会话信息判断,不依赖台账**。
835
- * 短 id → 完整 id 用 resolveShortId 当场查;查不到就静默放弃(绝不猜)。
836
- */
837
- /**
838
- * ★ 2026-10-14 主人需求:**通用路由** —— 把群里这条消息投递给"正文里点名的那个会话"。
839
- *
840
- * 流程:解析 key → 找会话(**先 live、后扫盘**)→ 投递(忙 `inject` 插话 / 闲 `followup` 唤醒)。
841
- * 与 `routeQuoteBack` 的区别:**不限"已盯梢"、不限"父会话在说话"、认任意 id**。
842
- *
843
- * ★ 附件(2026-10-14 补):QQ 里**引用图片/文件**时,图**不在正文里** —— 它在入站事件的
844
- * `attachments`(`{contentType,url,filename,asrText}`,见插件 `transport/inbound.ts`)。
845
- * 只取文本会把图丢掉,所以这里额外把附件 URL/语音转写一并拼进载荷。
846
- * @returns {Promise<{ok: boolean, reason: string, id?: string, workspace?: string, atts?: number}>}
847
- */
848
- /**
849
- * ★ 对外导出(2026-10-14):入站扩展要**在钩子之前**自己投递 —— 因为"二档路由隔绝"会把这条消息
850
- * 在早挂点就 annihilate 掉,一旦消灭成功,`session/event` 的 `user/message` 就永远不会发生,
851
- * 原来那条投递路径(本文件里的监听器)根本不会跑。所以投递逻辑必须能被扩展直接调。
852
- */
853
- export async function routeToSession(root, text, ev) {
854
- try {
855
- const key = parseRouteKey(text);
856
- if (!key) return { ok: false, reason: 'no-key' };
857
- const body = stripRouteMark(text);
858
- // ① 先问宿主(快,只认 live)
859
- let fullId = resolveShortId(root, key);
860
- let workspace = '';
861
- // ② live 查不到 ⇒ **扫盘**("任何已有会话"就靠这一步)
862
- if (!fullId) {
863
- const disk = findSessionOnDisk(key);
864
- fullId = disk.id;
865
- workspace = disk.workspace;
866
- }
867
- if (!fullId) return { ok: false, reason: 'not-found', id: key };
868
- const agents = (() => { try { return root?.get?.('agents'); } catch { return null; } })();
869
- let target = (() => { try { return agents?.get?.(fullId) ?? null; } catch { return null; } })();
870
- // ③ 没活着 ⇒ 试着唤醒(宿主 agents.resume;拿不到就算了,绝不硬造 agent)
871
- if (!target && agents && typeof agents.resume === 'function') {
872
- try { target = await agents.resume(fullId); } catch { /* ignore */ }
873
- }
874
- if (!target) return { ok: false, reason: 'not-live', id: fullId, workspace };
875
- // ④ 附件(图片/文件的 URL、语音转写)—— 引用图片时图就在这里
876
- const atts = attachmentsOf(ev);
877
- if (!body && !atts.length) return { ok: false, reason: 'empty-body', id: fullId, workspace };
878
- const lines = ['【群里有人把这条消息路由给你】'];
879
- if (body) lines.push(body);
880
- if (atts.length) {
881
- lines.push('');
882
- lines.push('(随消息一起来的附件:)');
883
- for (const a of atts) {
884
- const kind = String(a?.contentType ?? '');
885
- const url = String(a?.url ?? '');
886
- const name = String(a?.filename ?? '');
887
- const asr = String(a?.asrText ?? '');
888
- const tag = /image/i.test(kind) ? '图片' : (/video/i.test(kind) ? '视频' : (/audio|voice/i.test(kind) ? '语音' : (/file|application/i.test(kind) ? '文件' : '附件')));
889
- let line = `- ${tag}`;
890
- if (name) line += `:${name}`;
891
- if (url) line += `\n ${url}`;
892
- if (asr) line += `\n (语音转写)${asr}`;
893
- lines.push(line);
894
- }
895
- }
896
- lines.push('(这是跨会话路由,按需回应即可。)');
897
- const msg = userText(lines.join('\n'));
898
- if (!isInjectableMessage(msg)) return { ok: false, reason: 'bad-shape', id: fullId, workspace };
899
- const busy = (() => {
900
- try {
901
- const st = String(target.status ?? target.phase ?? '');
902
- return st !== '' && st !== 'idle';
903
- } catch { return false; }
904
- })();
905
- if (busy) await target.inject(msg);
906
- else await target.followup(msg);
907
- return { ok: true, reason: busy ? 'inject' : 'followup', id: fullId, workspace, atts: atts.length };
908
- } catch (e) {
909
- return { ok: false, reason: 'error:' + (e instanceof Error ? e.message : String(e)) };
910
- }
911
- }
912
-
913
- /**
914
- * 从入站事件里挖附件(多路兜底,形状照插件 `transport/inbound.ts` 的 `RawAttachment`)。
915
- * 只保留有 url / asrText 的项,避免塞一堆空对象过去。
916
- */
917
- export function attachmentsOf(ev) {
918
- const cands = [
919
- ev?.data?.message?.attachments,
920
- ev?.data?.attachments,
921
- ev?.message?.attachments,
922
- ev?.attachments,
923
- ];
924
- for (const c of cands) {
925
- if (!Array.isArray(c) || c.length === 0) continue;
926
- const out = [];
927
- for (const a of c) {
928
- if (!a || typeof a !== 'object') continue;
929
- const url = String(a.url ?? a.URL ?? '').trim();
930
- const asr = String(a.asrText ?? a.asr_text ?? '').trim();
931
- if (!url && !asr) continue;
932
- out.push({
933
- contentType: String(a.contentType ?? a.content_type ?? ''),
934
- url,
935
- filename: String(a.filename ?? a.fileName ?? ''),
936
- asrText: asr,
937
- });
938
- }
939
- if (out.length) return out;
940
- }
941
- return [];
942
- }
943
-
944
- async function routeQuoteBack(root, inboundText) {
945
- const short = parseOwner(inboundText);
946
- if (!short) return;
947
- const childId = resolveShortId(root, short);
948
- if (!childId) return;
949
- const agents = root.get('agents');
950
- const child = agents?.get?.(childId) ?? null;
951
- if (!child) return; // 子会话不在(不 live)→ 静默跳过
952
- const payload =
953
- '【群里有人引用了你发到 QQ 的那段输出】\n' +
954
- String(inboundText ?? '').trim() +
955
- '\n(这是群里的引用互动,按需回应即可。)';
956
- const msg = userText(payload);
957
- if (!isInjectableMessage(msg)) return;
958
- try {
959
- const busy = (() => {
960
- try {
961
- const st = String(child.status ?? child.phase ?? '');
962
- return st !== '' && st !== 'idle';
963
- } catch { return false; }
964
- })();
965
- if (busy) await child.inject(msg); // 忙 → 插话(不唤醒、不排队)
966
- else await child.followup(msg); // 空闲 → 唤醒它来处理
967
- const w = watching.get(childId);
968
- if (w) w.quotedAt = Date.now();
969
- } catch { /* 监听里绝不抛 */ }
970
- }
971
-
972
- /**
973
- * ★ 2026-10-13 补:**重启后把 QQ 转发能力补回来**。
974
- *
975
- * 背景:`fwd`(sender + replyTarget)**不可序列化**(sender 是 live 的 bot 对象),
976
- * 所以启动恢复的名单里 `fwd` 只能是 null。现象就是"一个根因、两个症状":
977
- * · 回灌照常进父会话,但 **不再转发到 QQ**;
978
- * · 群里因此没有那条带「【子会话 xxxx】」行首的转发消息 ⇒ **引用回流也认不到路**(OWNER_RE 匹配不上)。
979
- *
980
- * 修法:**父会话一发言**(user/message 事件)就把 fwd 补回来 —— sender 取插件的 bot,
981
- * replyTarget 从 session / root 上尽力凑。补上后当场可用;下次重启会再丢,但父会话一说话又补上,
982
- * 因此只在"父会话长期静默"时转发会缺,实际影响很小。
983
- * @returns {boolean} 是否可用
984
- */
985
- function hydrateFwd(entry, root, session) {
986
- try {
987
- if (!entry || typeof entry !== 'object') return false;
988
- if (entry.fwd?.sender && entry.fwd?.replyTarget) return true;
989
- // ★ 2026-10-13:**优先用"扩展工具侧注入"的 sender/replyTarget** —— 工具 env 里一定有这两样
990
- // (`session_watch.mjs` 每次被调用都会把它们挂到 globalThis[FWD_KEY])。
991
- // 实测 `root`(插件根 ctx)上拿不到 sender ⇒ 只靠 root 是补不回来的。
992
- const injected = globalThis[FWD_KEY] ?? null;
993
- const sender = injected?.sender ?? (root && (root.bot ?? root.sender)) ?? null;
994
- const s = session ?? {};
995
- const scope = String(s.scope ?? s.peerScope ?? '') || (s.peerId ? 'group' : '');
996
- const peerId = String(s.peerId ?? s.peer ?? s.groupOpenid ?? '');
997
- const replyTarget =
998
- injected?.replyTarget ??
999
- s.replyTarget ??
1000
- (root && (root.replyTarget ?? root.lastReplyTarget)) ??
1001
- (scope && peerId ? { scope, peerId } : null);
1002
- if (!sender || !replyTarget) {
1003
- try {
1004
- root?.logger?.warn?.(
1005
- `[ext-hook:session-watch] hydrateFwd 补不上:sender=${!!sender} replyTarget=${!!replyTarget}` +
1006
- ` injected=${!!injected} rootKeys=[${root ? Object.keys(root).slice(0, 16).join(',') : '-'}]` +
1007
- ` sessionKeys=[${Object.keys(s).slice(0, 16).join(',')}]`,
1008
- );
1009
- } catch { /* ignore */ }
1010
- return false;
1011
- }
1012
- entry.fwd = { sender, replyTarget };
1013
- try { root?.logger?.info?.('[ext-hook:session-watch] 已补回 QQ 转发能力(sender + replyTarget)'); } catch { /* ignore */ }
1014
- return true;
1015
- } catch { return false; }
1016
- }
1017
-
1018
- async function handler(root, session, event) {
1019
- try {
1020
- const sid = String(session?.id ?? session?.sessionId ?? '');
1021
- if (!sid) return;
1022
- const type = String(event?.type ?? '');
1023
-
1024
- // ── 引用回流:只关心**入站 user 消息**,且只在"某个盯梢对象的父会话"里认 ──
1025
- if (type === 'user/message') {
1026
- // ★ 2026-10-14:先学"这个 QQ 对象最近在哪个会话说话"(父会话跟着 QQ 对象走的依据)。
1027
- // 必须放在路由分支**之前** —— 否则主人只发路由消息时,这张表永远学不到东西。
1028
- notePeerSeen(session, sid);
1029
- const t = textOf(event);
1030
- // ★ 2026-10-14:**通用路由优先** —— 正文里出现会话 id(`[s:xxx]` / `【会话 xxx】`)就直接投给
1031
- // 那个会话。**不限已盯梢、不限是不是父会话**(主人要的"任何已有会话都能被点名")。
1032
- if (t && parseRouteKey(t)) {
1033
- const r = await routeToSession(root, t, event);
1034
- try {
1035
- root?.logger?.info?.(
1036
- `[ext-hook:session-watch] 路由 ${r.ok ? '✅' : '✗'} ${r.reason}` +
1037
- (r.id ? ` → ${shortSessionId(r.id)}…${r.workspace ? `(${r.workspace})` : ''}` : '') +
1038
- (r.atts ? ` 附件${r.atts}个` : ''),
1039
- );
1040
- } catch { /* ignore */ }
1041
- return;
1042
- }
1043
- const pe = parentEntryOf(sid);
1044
- if (pe) {
1045
- // ★ 2026-10-13:父会话一发言,就把重启后丢失的 QQ 转发能力补回来。
1046
- // 转发一断,群里就没有带「【子会话 xxxx】」行首的转发消息 ⇒ 引用回流也认不到路。
1047
- hydrateFwd(pe, root, session);
1048
- if (t && OWNER_RE.test(t)) await routeQuoteBack(root, t);
1049
- }
1050
- return;
1051
- }
1052
-
1053
- const w = watching.get(sid);
1054
- if (!w) return;
1055
-
1056
- // 累积(对应 qqbot 的 noteGenerated)
1057
- if (type === 'assistant/message') {
1058
- const t = textOf(event);
1059
- if (t) {
1060
- w.lastText = t;
1061
- // 二/三档要"所有正文":按块收,重复的丢弃
1062
- if (Array.isArray(w.texts)) { if (w.texts[w.texts.length - 1] !== t) w.texts.push(t); }
1063
- }
1064
- return;
1065
- }
1066
- // 报错也收(二/三档要一起转发)
1067
- if (/error/i.test(type)) {
1068
- const t = textOf(event) || String(event?.data?.message ?? event?.message ?? '').trim();
1069
- if (t && Array.isArray(w.errors)) w.errors.push(t);
1070
- return;
1071
- }
1072
- if (type !== 'turn/end') return;
1073
-
1074
- // 结算:优先用累积到的那一段;没有再从会话实例兜底取
1075
- let text = w.lastText;
1076
- w.lastText = ''; // ★ 取走即清空:否则"只有工具调用、没有正文"的回合会重复回灌上一回合的正文
1077
- if (!text) text = lastAssistantText(root, sid);
1078
- w.seen = (w.seen ?? 0) + 1;
1079
- const rawReason = reasonKind(event?.data?.reason ?? event?.data?.status ?? event?.data?.stopReason);
1080
- w.lastReason = rawReason;
1081
-
1082
- // 本回合收集物(二/三档用),取走即清
1083
- const allTexts = Array.isArray(w.texts) ? w.texts.slice() : [];
1084
- const errors = Array.isArray(w.errors) ? w.errors.slice() : [];
1085
- w.texts = [];
1086
- w.errors = [];
1087
- const mode = Number(w.mode) === 2 ? 2 : (Number(w.mode) === 3 ? 3 : 1);
1088
-
1089
- // ★★ 2026-10-15:**每回合无条件落盘一行** ★★
1090
- // 实测踩到:bee798c0 重启后"不转发",而日志里连 forward-skip 都没有 ⇒ 说明它压根没
1091
- // 走到 forwardToQq(`toForward` 为空、for 循环没进)。要区分"没收到正文事件"和"收到但被过滤",
1092
- // 只能在 turn/end 这里把手上有什么如实记下来。
1093
- void swDiag('turn-end short=' + String(w.shortId ?? '?')
1094
- + ' mode=' + mode + ' rawMode=' + JSON.stringify(w.mode)
1095
- + ' texts=' + allTexts.length + ' errs=' + errors.length
1096
- + ' textLen=' + String(text ?? '').length
1097
- + ' seen=' + w.seen + ' reason=' + String(rawReason ?? '-'));
1098
-
1099
- // ── 转发到 QQ ──────────────────────────────────────────────
1100
- // 一档:只转末段;二/三档:所有正文 + 报错
1101
- const toForward = mode === 1
1102
- ? (text ? [text] : [])
1103
- : [...allTexts, ...(errors.length ? ['⚠️ 报错:\n' + errors.join('\n')] : [])];
1104
- // ★★ 2026-10-15 主人定:转发前**先刷新 target + 数被动条数**,别钉死绑定时的 msgId ★★
1105
- // 被动回复(带 msg_id)有两条硬限制:①同一 msg_id 最多回 ~4-5 条;②msg_id 会过期。
1106
- // 踩到的实例:老盯梢 bee798c0 的 replyTarget 里钉着很久以前的 msgId ⇒ 发送报
1107
- // `回复消息msg_id已过期`,md/文本两条链全挂、内容静默丢失。
1108
- // 口径(与插件 outbound.ts 的 ADAPTIVE_MAX_PASSIVE=5 对齐):
1109
- // · 每次转发前,把 fwd.replyTarget 刷新成**最新注入**的那份(带最新 msgId);
1110
- // · 同一 msgId 数着用,**到 4 条**就主动转主动(摘掉 msgId),不再等它失败;
1111
- // · 真失败(过期/超限/其它)⇒ forwardToQq 里还有一层"摘 msgId 重发"兜底。
1112
- if (toForward.length > 0) {
1113
- const injected = globalThis[FWD_KEY] ?? null;
1114
- if (injected?.sender && injected?.replyTarget) {
1115
- w.fwd = { sender: injected.sender, replyTarget: injected.replyTarget };
1116
- } else if (!w.fwd?.sender || !w.fwd?.replyTarget) {
1117
- const hadFwd = !!w.fwd;
1118
- const ok = hydrateFwd(w, root, session);
1119
- void swDiag('pre-forward hydrate short=' + String(w.shortId ?? '?')
1120
- + ' hadFwd=' + hadFwd + ' ok=' + ok + ' mode=' + mode);
1121
- }
1122
- }
1123
- for (const piece of toForward) {
1124
- const body = withOwner(w, piece);
1125
- // 去重:同一条内容不重复转发
1126
- if (body === w.lastForwarded) continue;
1127
- const how = await forwardToQq(w, body);
1128
- if (how) w.lastForwarded = body;
1129
- }
1130
-
1131
- // ── 回灌进父会话上下文(二档**不进**)──────────────────────
1132
- if (mode === 2) return;
1133
- if (!text) return; // 空回合(只有工具调用/无正文)→ 不回灌
1134
- // ★ 去重:兜底路径可能又取到"上一次已经灌过"的那段正文,内容相同就不再灌第二遍
1135
- if (text === w.lastSent) return;
1136
- w.lastSent = text;
1137
-
1138
- const agents = root.get('agents');
1139
- // ★ 2026-10-14:**父会话跟着 QQ 对象走** —— 该 QQ 对象当前所在的会话优先(/bot-new 之后自动跟过去),
1140
- // 没学到才回落到绑定时写死的那个 id(老行为,向后兼容)。
1141
- const parentId = resolveParentId(w);
1142
- const parent = agents?.get?.(parentId) ?? null;
1143
- if (!parent) return; // 父不在(不 live)→ 静默跳过,不制造错误
1144
-
1145
- const candidate = buildSettlementNotice({ sessionId: sid, label: w.label, rawReason, text });
1146
- if (!isInjectableMessage(candidate)) return; // 自检不过 → 宁可这次不回灌
1147
- try {
1148
- // ★ 2026-10-12 定案(照抄 qqbot 插件的入站模式 —— dist/features/qq-user-questions.js:646):
1149
- // 「忙时插话、空闲唤醒」
1150
- // ★ 三档(mode=3)主人要求"进上下文但**不唤醒**" ⇒ 无论忙闲都走 inject。
1151
- const busy = (() => {
1152
- try {
1153
- const st = String(parent.status ?? parent.phase ?? '');
1154
- return st !== '' && st !== 'idle';
1155
- } catch { return false; }
1156
- })();
1157
- if (mode === 3 || busy) await parent.inject(candidate); // 插话(不唤醒、不排队、不进输入框)
1158
- else await parent.followup(candidate); // 空闲 → 唤醒
1159
- w.firedAt = Date.now();
1160
- } catch { /* 注入失败 → 静默;监听里绝不抛,免得影响宿主事件链 */ }
1161
- } catch { /* 监听里绝不抛,免得影响宿主事件链 */ }
1162
- }
1163
-
1164
- function installHook(root) {
1165
- if (HOOK_DISABLED) return;
1166
-
1167
- // ① 把「当前实例的 handler」发布到 globalThis:已装好的那个监听会转发到最新实例,
1168
- // 所以改完 lib 热刷后新代码立刻接管,不必重挂监听。
1169
- globalThis[HANDLER_KEY] = (session, event) => { void handler(root, session, event); };
1170
-
1171
- // ② 监听全局只装一次。lib 带 mtime 版本号加载,改一次就换一个模块实例;
1172
- // 若各实例各自 root.on 一遍,同一个 turn/end 会被回灌多次。
1173
- if (globalThis[HOOK_KEY]) { hooked = true; return; }
1174
- try {
1175
- // 与 qqbot 的 mc_tell 同款:挂在插件根 ctx 上,事件回调 (session, event)。
1176
- // 注意:回调里通过 globalThis 取 handler,永远调用最新那一版。
1177
- root.on('session/event', (session, event) => {
1178
- const h = globalThis[HANDLER_KEY];
1179
- if (typeof h === 'function') h(session, event);
1180
- });
1181
- globalThis[HOOK_KEY] = true;
1182
- hooked = true;
1183
- } catch { hooked = false; }
1184
- }
1185
-
1186
- /**
1187
- * 登记一个"要盯着的子会话"。
1188
- *
1189
- * @param {object} opts
1190
- * · parentAgentId 父会话 id(必填)
1191
- * · childSessionId 子会话 id(必填)
1192
- * · label 标签(可选)
1193
- * · name 会话名(可选;归属行显示用,缺省取 label)
1194
- * · preset 预设名(可选;归属行显示用)
1195
- * · workspace 工作区(可选;归属行显示用,建议传目录名而非全路径)
1196
- * · mode 1=只回灌末段+转末段(默认) 2=只转所有正文+报错(不进父上下文) 3=进父上下文(不唤醒)+全转
1197
- * · sender 父会话的 sender(可选;给了才转发 QQ)
1198
- * · replyTarget 父会话所在的 QQ 目标(可选;自带最近 msgId ⇒ 被动优先)
1199
- * · peerName 父会话所在群/私聊的名字(可选,只用于显示)
1200
- * @returns 人话描述(挂成功/失败原因),不抛错。
1201
- */
1202
- export async function register(root, opts = {}) {
1203
- const parentAgentId = String(opts.parentAgentId ?? '').trim();
1204
- const childSessionId = String(opts.childSessionId ?? '').trim();
1205
- const label = String(opts.label ?? '').trim();
1206
- const mode = Number(opts.mode) === 2 ? 2 : (Number(opts.mode) === 3 ? 3 : 1);
1207
- if (!parentAgentId || !childSessionId) return '未挂(缺 parentAgentId 或 childSessionId)';
1208
- if (!root || typeof root.on !== 'function') return '未挂(root 不支持 .on)';
1209
- installHook(root);
1210
- if (HOOK_DISABLED) return '未挂(回灌钩子当前被 HOOK_DISABLED 主动关闭,属预期;恢复见 installHook 注释)';
1211
- if (!hooked) return '未挂(root.on 抛错)';
1212
- const fwd = (opts.sender && opts.replyTarget) ? { sender: opts.sender, replyTarget: opts.replyTarget } : null;
1213
- // ★ 2026-10-14:记下这条盯梢属于哪个 **QQ 对象**(scope:peerId)—— 父会话要跟着它走。
1214
- // 优先级:调用方显式给的 peerKey > replyTarget 里能抠出来的 > 空(空则退回写死的 parentAgentId)。
1215
- const pk = String(opts.peerKey ?? '').trim() || peerKeyOfTarget(opts.replyTarget);
1216
- watching.set(childSessionId, {
1217
- parentAgentId,
1218
- label,
1219
- mode,
1220
- shortId: shortSessionId(childSessionId),
1221
- /** 归属行用的三件套(主人 2026-10-12 定:会话名 / 预设名 / 工作区) */
1222
- name: String(opts.name ?? opts.label ?? '').trim(),
1223
- preset: String(opts.preset ?? '').trim(),
1224
- workspace: String(opts.workspace ?? '').trim(),
1225
- peerName: String(opts.peerName ?? ''),
1226
- peerKey: pk,
1227
- fwd,
1228
- lastText: '',
1229
- texts: [],
1230
- errors: [],
1231
- seen: 0,
1232
- firedAt: 0,
1233
- lastForwarded: '',
1234
- });
1235
- // 绑定时先按"当时那个会话"给这张表起步;**只在没记录时写**,别把已经学到的新会话覆盖回旧的。
1236
- if (pk && parentAgentId && !peerLatest.has(pk)) peerLatest.set(pk, parentAgentId);
1237
- await persist();
1238
- const modeText = mode === 2 ? '二档(全部正文+报错→QQ,不进父上下文)'
1239
- : mode === 3 ? '三档(进父上下文但不唤醒 + 全转QQ)'
1240
- : '一档(末段回灌父会话 + 同转QQ)';
1241
- return `已挂(子=${shortSessionId(childSessionId)}… → 父=${shortSessionId(parentAgentId)}…;${modeText}${fwd ? ';QQ 转发就绪' : ';⚠️ 没拿到 sender/replyTarget,QQ 转发不可用'})`;
1242
- }
1243
-
1244
- /** 改档位(已挂的盯梢可随时改) */
1245
- export async function setMode(childSessionId, mode) {
1246
- const w = watching.get(String(childSessionId ?? ''));
1247
- if (!w) return '没找到这个盯梢(先用 session_watch list 看)';
1248
- w.mode = Number(mode) === 2 ? 2 : (Number(mode) === 3 ? 3 : 1);
1249
- await persist();
1250
- return `已改为 ${w.mode} 档`;
1251
- }
1252
-
1253
- /** 取消盯梢 */
1254
- export async function unregister(childSessionId) {
1255
- const ok = watching.delete(String(childSessionId ?? ''));
1256
- if (ok) await persist();
1257
- return ok ? '已取消盯梢' : '没找到这个盯梢';
1258
- }
1259
-
1260
- /** 给别的工具(如 session_watch 状态查询)读当前盯着的清单 */
1261
- /**
1262
- * ★ 某个路由短 id 对应的**回灌挡位**(读内存名单;没绑过返回 0)。
1263
- *
1264
- * 入站扩展用它判断"这条路由消息要不要在父上下文里彻底消失":
1265
- * 挡位 2(二档)= 双向隔绝 —— 子会话的正文只去 QQ、**不进父上下文**(原有语义),
1266
- * 那么反向也一样:**用户发进群的路由消息也不该落进父上下文**(2026-10-14 主人定)。
1267
- * 没绑过的(纯通用路由)返回 0 ⇒ **不进隔绝**,保持原样投递 + 照常进上下文。
1268
- */
1269
- export function modeOfRoute(key) {
1270
- try {
1271
- ensureLoaded();
1272
- const k = String(key ?? '').trim();
1273
- if (!k) return 0;
1274
- for (const [sid, w] of watching.entries()) {
1275
- const short = shortSessionId(sid); // 例:fc871e99
1276
- if (short === k || sid === k || sid === `session-${k}`) return Number(w?.mode ?? 1) || 1;
1277
- }
1278
- } catch { /* ignore */ }
1279
- return 0;
1280
- }
1281
-
1282
- /**
1283
- * 供工具/命令展示:这条盯梢**当前**会把回灌投给谁(= 跟着 QQ 对象动态解析之后的结果)。
1284
- * 与 `parentAgentId`(绑定时写死的那个)不同:发过 `/bot-new` 之后这两个会不一样。
1285
- */
1286
- export function effectiveParentOf(childSessionId) {
1287
- ensureLoaded();
1288
- const w = watching.get(String(childSessionId ?? ''));
1289
- return w ? resolveParentId(w) : '';
1290
- }
1291
-
1292
- export function listWatching() { ensureLoaded(); // ★ 先保证存档已读回内存(重启后第一次调它就能看到完整名单)
1293
- return [...watching.entries()].map(([sid, w]) => ({
1294
- childSessionId: sid,
1295
- shortId: shortSessionId(sid),
1296
- parentAgentId: w.parentAgentId,
1297
- parentShortId: shortSessionId(w.parentAgentId),
1298
- /** QQ 对象键(scope:peerId);父会话会跟着它动态解析 */
1299
- peerKey: w.peerKey ?? '',
1300
- /** 当前实际会投给的父会话(发过 /bot-new 后会与 parentAgentId 不同) */
1301
- effectiveParentShortId: shortSessionId(resolveParentId(w)),
1302
- label: w.label,
1303
- mode: w.mode ?? 1,
1304
- /** 归属行三件套(会随转发消息发到 QQ) */
1305
- name: w.name ?? '',
1306
- preset: w.preset ?? '',
1307
- workspace: w.workspace ?? '',
1308
- peerName: w.peerName ?? '',
1309
- qqReady: !!w.fwd,
1310
- hasText: !!w.lastText,
1311
- turnsSeen: w.seen ?? 0,
1312
- lastFiredAt: w.firedAt ?? 0,
1313
- quotedAt: w.quotedAt ?? 0,
1314
- }));
1315
- }
1
+ /**
2
+ * session_watch_lib.mjs — 「回合结束回灌」的共用实现(放在 tools/lib/ 下,不被当工具扫描)
3
+ *
4
+ * 口径**照抄 qqbot 的 passive 收尾**(src/transport/outbound.ts:80-211):
5
+ * · 回合内累积 `assistant/message` 的正文(= 它的 noteGenerated(sessionKey, msgId, text))
6
+ * · `turn/end` 时结算(它的注释原文:「assistant/message 用完即清,turn/end 兜底清」)
7
+ * · 取**最后一个正文块**的文本(它收尾时也是"把最后一块复制一份")
8
+ *
9
+ * ★ 2026-10-12 主人定案(回灌模式三档 + 转发到 QQ + 引用回流):
10
+ * **一档(mode=1,默认)**:只把**末段正文**回灌给父会话(原行为),**同时**转发到父会话所在的 QQ。
11
+ * **二档(mode=2)**:本回合的**所有正文块 + 报错**都转发到 QQ,但**不进父会话上下文**。
12
+ * **三档(mode=3)**:所有正文 + 报错**进**父会话上下文(**只插话、不唤醒**),同时也转发到 QQ。
13
+ *
14
+ * ★ 转发到 QQ 的三条口径:
15
+ * ① **行首归属**:每条转发消息的第一行是 `【子会话 xxxx】`(xxxx=会话短 id)。
16
+ * 它**短且在最前**是硬要求 —— QQ 入站引用块只带被引原文**前 60 字**(inbound 的 QUOTE_KEEP),
17
+ * 归属跑出这 60 字就再也认不出来了(见下面的"引用回流")。
18
+ * ② **markdown + 失败降级**:直接走 `sender.sendMarkdown(replyTarget, text)` ——
19
+ * 插件自带的 markdown→纯文本降级链(`send_md` 工具用的就是它),失败再退回 `sender.sendText`。
20
+ * ③ **被动优先**:`replyTarget` 自带该会话最近的 `msgId`,带它发即"被动回复"
21
+ * (不吃主动配额、QQ 也不吞);插件侧在被动失败时会自动去掉 msgId 转主动。
22
+ * ⚠️ 这两件事都在**插件**里做好了,本库直接用 `sender` + `replyTarget` 即可,不重复造。
23
+ *
24
+ * ★ 引用回流(主人 2026-10-12 明确口径:**靠行首会话信息判断,不依赖台账**):
25
+ * 群里有人**引用**那条转发消息时,入站引用块会把被引原文的前 60 字带进来,
26
+ * 归属行就在里面 ⇒ 本库从入站 user 消息里正则认出 `【子会话 xxxx】`
27
+ * → 把这条引用的原文**插话**给对应子会话(忙时 inject、空闲 followup)。
28
+ * **不需要 QQ 的 msg_id**,也**不需要维护任何 msg_id→会话 的映射表**。
29
+ * 短 id → 完整会话 id 是**当场**在会话注册表里查的(见 resolveShortId)。
30
+ *
31
+ * 本库只做三件事:挂监听、结算回灌/转发、认引用回流。
32
+ *
33
+ * ★ 2026-10-12 定案(主人):回灌**模拟用户消息**(source.kind='user')+ **唤醒**父会话(一档)。
34
+ * `followup` 就是 `inject` 的唤醒档(inject=next-step 不唤醒;followup=next-turn 唤醒),
35
+ * 所以"注入 + 唤醒"用 followup。
36
+ * 原因(实测结论):`inject` 落 `agent/inbox/spliced **target=next-step**` —— 排队到下次组包、
37
+ * **不产生回合**,因此既没有 turn 触发节点、**UI 上也什么都没有**。
38
+ * 而 `followup` 落 `target=next-turn` ⇒ 产生回合 ⇒ 被渲染成 `TurnTriggerNodeView`(那个「白框」)。
39
+ * 代价:回灌会**唤醒父会话跑一轮**(烧 token),故正文里加了一行"无需回复"提示。
40
+ * → 三档(mode=3)要的是"进上下文但**不唤醒**",所以那一档**强制走 inject**。
41
+ *
42
+ * ⚠️ 回灌消息的形状**必须**对齐宿主「子会话结算通知」(createSettlementMessage):
43
+ * { id, role:'user', content:[摘要行, 结尾正文引导语, ...正文块],
44
+ * source:{ kind:'subagent-settled', form:'notice', summary, senderSessionId } }
45
+ *
46
+ * ⚠️ 注入前必须过 isInjectableMessage() 自检(fail-closed)。宿主的顺序是
47
+ * **先 append 落盘、后读 `msg.source.kind`**:形状不合法时坏记录已经写进
48
+ * `agent/inbox/spliced.data.inserted[]`,之后投影抛错 —— 会话文件从此无法加载。
49
+ * 事故实例:会话 9643a885 的 seq 4222 曾被写成 `inserted: ["<字符串>"]`。
50
+ *
51
+ * 用法:
52
+ * import { register } from './lib/session_watch_lib.mjs';
53
+ * await register(root, { parentAgentId, childSessionId, label, mode, sender, replyTarget });
54
+ */
55
+ /**
56
+ * 版本标记:供调用方打印,用来确认**热刷后加载到的到底是哪一版**。
57
+ * 改动本文件时顺手把这个号 +1(或换日期),排查"改了不生效"时一眼就能看出来。
58
+ */
59
+ export const __LIB_VERSION__ = 'lib-v14-20261014-通用路由+扫盘解析+会话列表+父会话跟QQ对象走+二档路由隔绝';
60
+
61
+ // ── ★ 2026-10-13 持久化改造(主人指示:**以本地存档为准,别只靠内存**)──────────────
62
+ // 本文件的风格是"用到时动态 import";这里用**顶层 await** 一次性取到同步版 fs,
63
+ // 后面的 ensureLoaded()(同步读存档)才能被同步函数(如 listWatching)直接调用。
64
+ const { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } = await import('node:fs');
65
+ const { dirname, join } = await import('node:path');
66
+ const { fileURLToPath } = await import('node:url');
67
+
68
+ /**
69
+ * 盯梢名单。**放在 globalThis 上**,不是模块局部变量。
70
+ *
71
+ * 原因:`tools/lib/` 的 import 带了 `?v=<mtime>` 版本号(为让热刷生效),
72
+ * 于是每改一次本文件就会产生一个**新的模块实例**。若名单是模块局部的,
73
+ * 改一次 lib 就把已登记的盯梢对象全丢了。放 globalThis 上跨实例共享。
74
+ */
75
+ const WATCHING_KEY = Symbol.for('dsh-qqbot.session-watch.watching');
76
+ /**
77
+ * ★ 2026-10-13:**扩展工具侧注入的 sender/replyTarget**(跨模块实例共享)。
78
+ * 工具 env 里**一定有**这两样(扩展工具 env = `{cwd, manager, sender, replyTarget, exec, ctx, logger}`),
79
+ * 而插件根 ctx(handler 拿到的 root)上实测**拿不到** sender ⇒ 单靠 root 补不回 QQ 转发。
80
+ * 所以让扩展工具每次被调用时顺手写进来,handler 侧再读它去补 fwd。
81
+ */
82
+ const FWD_KEY = Symbol.for('dsh-qqbot.session-watch.fwd');
83
+
84
+ /**
85
+ * 供扩展工具调用:把本次 env 的 sender/replyTarget 交给回灌库。
86
+ * 调一次之后,回灌库在"父会话发言"时就能把 QQ 转发能力补回来(重启后尤其需要)。
87
+ * @returns {boolean} 是否记住
88
+ */
89
+ export function rememberFwd(sender, replyTarget) {
90
+ try {
91
+ if (sender && replyTarget) {
92
+ globalThis[FWD_KEY] = { sender, replyTarget };
93
+ return true;
94
+ }
95
+ return false;
96
+ } catch { return false; }
97
+ }
98
+ const watching = (globalThis[WATCHING_KEY] ??= new Map()); // childSessionId -> entry
99
+
100
+ /**
101
+ * ★★ 2026-10-14:**父会话跟着「QQ 对象」走**(主人定:绑的应该是 QQ 对象,不是那一刻的会话 id)
102
+ *
103
+ * 病根:原来 `parentAgentId` 是绑定时写死的 session id,回灌直接 `agents.get(那个 id)`。
104
+ * 在 QQ 里发 `/bot-new` 会**新开一个会话**(新 id),名单里那条记录却还指着旧会话
105
+ * ⇒ 回灌继续落进旧会话;而"转发到 QQ"那一路用的是 openid、照旧正常 ⇒ 表面上完全看不出错。
106
+ *
107
+ * 修法(不需要插件内部 API):记一张 `peerKey = scope:peerId`(QQ 对象)→ **最近一次为该对象发言的
108
+ * 会话 id** 的表;回灌前先按 peerKey 取最新会话,取不到才回落到写死的旧 id。
109
+ * `/bot-new` 之后该对象的下一条消息必然落到新会话 ⇒ 这张表立刻学到新 id ⇒ 回灌自动跟过去。
110
+ *
111
+ * 自愈:老记录(没有 peerKey)在"它的父会话下一次发言"时自动补上 peerKey —— 与 fwd 补回同一套路数。
112
+ */
113
+ const PEER_KEY = Symbol.for('dsh-qqbot.session-watch.peerLatest');
114
+ const peerLatest = (globalThis[PEER_KEY] ??= new Map()); // peerKey -> sessionId
115
+
116
+ /** 从**会话对象**里取 QQ 对象键(scope:peerId)。刻意不用 `o.id` —— 那是会话 id,不是 peer */
117
+ function peerKeyOfSession(s) {
118
+ try {
119
+ if (!s) return '';
120
+ const peerId = String(s.peerId ?? s.groupOpenid ?? s.groupId ?? '');
121
+ if (!peerId) return '';
122
+ const scope = String(s.scope ?? s.peerScope ?? '') || 'group';
123
+ return scope + ':' + peerId;
124
+ } catch { return ''; }
125
+ }
126
+
127
+ /** 从 **replyTarget / peer 视图**里取 QQ 对象键 */
128
+ function peerKeyOfTarget(rt) {
129
+ try {
130
+ if (!rt) return '';
131
+ const id = String(rt.peerId ?? rt.targetId ?? rt.groupOpenid ?? rt.openid ?? rt.groupId ?? rt.id ?? '');
132
+ if (!id) return '';
133
+ const scope = String(rt.scope ?? rt.kind ?? '') || 'group';
134
+ return scope + ':' + id;
135
+ } catch { return ''; }
136
+ }
137
+
138
+ /** 学到"这个 QQ 对象最近在哪个会话里说话",顺手给老盯梢补 peerKey(自愈) */
139
+ export function notePeerSeen(session, sid) {
140
+ try {
141
+ const pk = peerKeyOfSession(session);
142
+ if (!pk || !sid) return false;
143
+ let changed = peerLatest.get(pk) !== sid;
144
+ if (changed) peerLatest.set(pk, sid);
145
+ for (const w of watching.values()) {
146
+ if (!w.peerKey && w.parentAgentId === sid) { w.peerKey = pk; changed = true; }
147
+ }
148
+ if (changed) void persist(); // 落盘失败静默,不影响监听
149
+ return changed;
150
+ } catch { return false; }
151
+ }
152
+
153
+ /** 回灌该投给谁:优先"该 QQ 对象当前所在的会话",其次绑定时写死的父会话(老行为) */
154
+ function resolveParentId(w) {
155
+ try {
156
+ const pk = String(w?.peerKey ?? '');
157
+ const latest = pk ? String(peerLatest.get(pk) ?? '') : '';
158
+ return latest || String(w?.parentAgentId ?? '');
159
+ } catch { return String(w?.parentAgentId ?? ''); }
160
+ }
161
+
162
+ /**
163
+ * 默认存档路径:`{dataRoot}/.qqbot-extensions/tools/data/session-watch-watching.json`
164
+ * (**与 `vote.json` 同一个 data 目录** —— 对齐既有约定:扩展各类的存档都放
165
+ * `{数据根}/.qqbot-extensions/<类型>/data/<名字>.json`)。
166
+ * 本文件在 `.../tools/lib/` ⇒ `../data/` 正好是 `tools/data/`。
167
+ * 为什么要兜底:`setStateFile()` 此前**全项目无人调用** ⇒ `stateFileOf()` 恒为 '' ⇒
168
+ * `persist()` 里 `if (!file) return` 直接空转 ⇒ **名单从来没落过盘**(重启自然恢复不了)。
169
+ */
170
+ const DEFAULT_STATE_FILE = (() => {
171
+ try { return fileURLToPath(new URL('../data/session-watch-watching.json', import.meta.url)); }
172
+ catch { return ''; }
173
+ })();
174
+
175
+ let loadedOnce = false;
176
+
177
+ /**
178
+ * ★ 持久化读回(主人 2026-10-13 指示:**以本地存档为准,不要只靠内存**)。
179
+ * 幂等:只从文件读一次;此后内存是运行期缓存,所有写操作都会 persist() 回文件。
180
+ * 同步实现 ⇒ 可被 listWatching() / handler() 这类同步路径直接调用。
181
+ * @returns 读回后内存里的条目数
182
+ */
183
+ export function ensureLoaded() {
184
+ if (loadedOnce) return watching.size;
185
+ loadedOnce = true;
186
+ try {
187
+ const file = stateFileOf();
188
+ if (!file) return watching.size;
189
+ const j = JSON.parse(readFileSync(file, 'utf8'));
190
+ const rows = Array.isArray(j?.rows) ? j.rows : [];
191
+ // ★ 2026-10-14:读回"QQ 对象 → 最近发言会话"表(父会话跟着 QQ 对象走的依据)
192
+ try { for (const [k, v] of Object.entries(j?.peers ?? {})) if (k && v) peerLatest.set(String(k), String(v)); } catch { /* ignore */ }
193
+ for (const r of rows) {
194
+ const child = String(r?.child ?? '').trim();
195
+ const parent = String(r?.parent ?? '').trim();
196
+ if (!child || !parent) continue;
197
+ if (watching.has(child)) continue;
198
+ watching.set(child, {
199
+ parentAgentId: parent,
200
+ label: String(r?.label ?? ''),
201
+ mode: Number(r?.mode) === 2 ? 2 : (Number(r?.mode) === 3 ? 3 : 1),
202
+ shortId: shortSessionId(child),
203
+ name: String(r?.name ?? r?.label ?? ''),
204
+ preset: String(r?.preset ?? ''),
205
+ workspace: String(r?.workspace ?? ''),
206
+ peerName: String(r?.peerName ?? ''),
207
+ peerKey: String(r?.peerKey ?? ''),
208
+ // ⚠️ 重启后拿不到 sender/replyTarget ⇒ 先恢复"回灌父会话",
209
+ // QQ 转发等下次 register(或主人重挂)时补上 ⇒ 这里如实置空、不假装就绪。
210
+ fwd: null,
211
+ lastText: '', texts: [], errors: [], seen: 0, firedAt: 0, lastForwarded: '',
212
+ });
213
+ }
214
+ } catch { /* 读不到就当空名单 */ }
215
+ return watching.size;
216
+ }
217
+
218
+ /**
219
+ * ★ 启动恢复(给启动钩子用):读回存档 + **重装监听器**。
220
+ * 名单以文件为准;而监听器(`root.on('session/event')`)是内存态、重启必丢 ⇒ 只能靠这里重装。
221
+ */
222
+ export async function rehydrate(root) {
223
+ const n = ensureLoaded();
224
+ try { installHook(root); } catch { /* 装不上就只恢复名单 */ }
225
+ // ★ 2026-10-13:顺手把 QQ 转发能力也补上 —— 只要 `session_watch` 工具刚把 sender/replyTarget
226
+ // 注入过(rememberFwd),这里就能立刻补回,**不必等父会话下一次发言**。
227
+ let fwdFixed = 0;
228
+ try {
229
+ for (const [, w] of watching) if (hydrateFwd(w, root, null)) fwdFixed += 1;
230
+ } catch { /* ignore */ }
231
+ return { restored: n, hooked, fwdFixed };
232
+ }
233
+
234
+ /**
235
+ * 盯梢名单落盘(2026-10-12 新增)。
236
+ *
237
+ * 为什么要:名单原本只在内存里,**dsh 一重启,之前 attach 的盯梢全没了**。
238
+ * 落盘后由启动钩子(`.qqbot-extensions/hooks/`)在宿主启动时读回来重新登记 ——
239
+ * 这正是主人要的"让用户写一些在运行 dsh 时启动的东西"的第一个用例。
240
+ */
241
+ const STATE_KEY = Symbol.for('dsh-qqbot.session-watch.stateFile');
242
+ // ★ 兜底默认路径:没人调 setStateFile() 时也能落盘/读回(见上面 DEFAULT_STATE_FILE 的说明)
243
+ const stateFileOf = () => String(globalThis[STATE_KEY] || DEFAULT_STATE_FILE || '');
244
+
245
+ /** 记下状态文件路径(由 register 的调用方给;没给就不落盘) */
246
+ export function setStateFile(p) {
247
+ try { globalThis[STATE_KEY] = String(p || ''); } catch { /* ignore */ }
248
+ }
249
+
250
+ /** 把当前名单落盘(静默失败:落不了盘只影响"重启后自动恢复",不影响回灌本身) */
251
+ async function persist() {
252
+ const file = stateFileOf();
253
+ if (!file) return;
254
+ try {
255
+ const { writeFileSync, mkdirSync } = await import('node:fs');
256
+ const { dirname } = await import('node:path');
257
+ mkdirSync(dirname(file), { recursive: true });
258
+ const rows = [...watching.entries()].map(([child, w]) => ({
259
+ child,
260
+ parent: w.parentAgentId,
261
+ label: w.label ?? '',
262
+ name: w.name ?? '',
263
+ preset: w.preset ?? '',
264
+ workspace: w.workspace ?? '',
265
+ mode: w.mode ?? 1,
266
+ peerName: w.peerName ?? '',
267
+ peerKey: w.peerKey ?? '',
268
+ }));
269
+ // ★ 2026-10-14:把"QQ 对象 → 最近发言会话"表一起落盘(父会话跟着 QQ 对象走的依据)
270
+ const peers = {};
271
+ for (const [k, v] of peerLatest.entries()) if (k && v) peers[k] = v;
272
+ writeFileSync(file, JSON.stringify({ v: 1, at: Date.now(), rows, peers }, null, 2), 'utf8');
273
+ } catch { /* ignore */ }
274
+ }
275
+
276
+ /** 读回落盘的名单(给启动钩子用;返回原始行数组) */
277
+ export async function loadPersisted() {
278
+ const file = stateFileOf();
279
+ if (!file) return [];
280
+ try {
281
+ const { readFileSync } = await import('node:fs');
282
+ const j = JSON.parse(readFileSync(file, 'utf8'));
283
+ return Array.isArray(j?.rows) ? j.rows : [];
284
+ } catch { return []; }
285
+ }
286
+
287
+ /** 回灌钩子总开关。false = 正常挂 `session/event` 监听。 */
288
+ const HOOK_DISABLED = false;
289
+
290
+ /** 监听只装一次(跨模块实例去重);handler 指针让新实例能立刻接管旧监听。 */
291
+ const HOOK_KEY = Symbol.for('dsh-qqbot.session-watch.hook');
292
+ const HANDLER_KEY = Symbol.for('dsh-qqbot.session-watch.handler');
293
+ let hooked = false;
294
+
295
+ /**
296
+ * turn/end 的 data.reason → 人话。
297
+ * 口径来自 webui 的两条文案(dsh-client-ui-chat/lib/client.js):
298
+ * "message.turnProcess.worked" = 已完成 ← 正常跑完
299
+ * "message.stopped" = 已停止 ← 被停止/中断
300
+ * 宿主在 index.js:912 把 event.data.reason 记进 inflight.endReason,webui 据此显示。
301
+ */
302
+ function reasonText(reason) {
303
+ const r = String(reason ?? '').toLowerCase();
304
+ if (!r) return '结束';
305
+ if (/stop|abort|cancel|interrupt|halt/.test(r)) return '已停止';
306
+ if (/complet|done|finish|success|ok/.test(r)) return '已完成';
307
+ if (/error|fail/.test(r)) return '出错';
308
+ return r; // 未知取值就原样带出来,便于以后补映射
309
+ }
310
+
311
+ /**
312
+ * `notice` 摘要行的长度上限,与宿主 `dsh-llm` 的 CONTEXT_SUMMARY_MAX_CHARS 保持一致。
313
+ * 宿主原文注释:producer 的一行说明会写进持久日志,所以要限长。
314
+ */
315
+ const CONTEXT_SUMMARY_MAX_CHARS = 120;
316
+
317
+ /** 把摘要行压到上限内(超出用省略号),口径照抄宿主 dsh-llm 的 boundContextSummary()。 */
318
+ function boundContextSummary(summary) {
319
+ const t = String(summary ?? '');
320
+ return t.length <= CONTEXT_SUMMARY_MAX_CHARS ? t : `${t.slice(0, CONTEXT_SUMMARY_MAX_CHARS - 1)}…`;
321
+ }
322
+
323
+ /**
324
+ * 取会话短 id 用于显示。
325
+ * ⚠️ 子会话 id 形如 `session-f147236a-…`,直接 slice(0,8) 只会得到无意义的 `session-`。
326
+ * 所以先剥掉 `session-` 前缀再截断。
327
+ */
328
+ export function shortSessionId(id) {
329
+ const s = String(id ?? '');
330
+ return (s.startsWith('session-') ? s.slice(8) : s).slice(0, 8);
331
+ }
332
+
333
+ /**
334
+ * 行首归属标记(2026-10-12 主人定:除了短 id,还要**会话名 / 预设名 / 工作区**)。
335
+ *
336
+ * ⚠️ 排版有硬约束:QQ 入站引用块只带被引原文**前 60 字**,而引用回流就靠这一行认路。
337
+ * 所以顺序是**路由键打头、其余信息跟在后面** —— 即使后面被截掉,`【子会话 xxxx` 也稳稳留在前 15 字内。
338
+ * 路由键后面的 `】` **不保证存在**(可能正好被截断),因此解析正则**不要求右括号**。
339
+ *
340
+ * 例:`【子会话 87c87c3b · 回灌转发自测 · standard · 鲸鱼娘】`(约 40 字,安全)
341
+ */
342
+ export function ownerLine(parts) {
343
+ const p = (typeof parts === 'string') ? { shortId: parts } : (parts ?? {});
344
+ const seg = [`【子会话 ${String(p.shortId ?? '').slice(0, 8)}`];
345
+ for (const v of [p.name, p.preset, p.workspace]) {
346
+ const s = String(v ?? '').trim();
347
+ if (s) seg.push(s.replace(/[·】\n]/g, ' ').slice(0, 24)); // 别让分隔符/换行混进来
348
+ }
349
+ return seg.join(' · ') + '】';
350
+ }
351
+
352
+ /**
353
+ * 认出归属标记(引用回流的路由键)。
354
+ * **故意不要求右括号** —— 引用块只带前 60 字,归属行尾可能被截掉。
355
+ * 同时容忍中间的空格与全角/半角差异。
356
+ */
357
+ const OWNER_RE = /【\s*子会话\s*([0-9a-fA-F]{4,12})/;
358
+
359
+ /** 从一段文本里抽归属短 id(找不到返回 '') */
360
+ export function parseOwner(text) {
361
+ const m = OWNER_RE.exec(String(text ?? ''));
362
+ return m ? m[1].toLowerCase() : '';
363
+ }
364
+
365
+ /**
366
+ * 短 id → 完整会话 id。**当场查**,不依赖任何持久台账(主人 2026-10-12 明确口径)。
367
+ * 会话注册表的 API 形状随版本变,这里逐种试,全部失败就返回 ''。
368
+ */
369
+ // ── ★ 2026-10-14 主人需求:**通用路由**(正文里带会话 id ⇒ 投递到那个会话)─────────────
370
+ /**
371
+ * 认两种写法(**不要求行首**,写在句子中间也认):
372
+ * `[s:xxxxxxxx]` ← 推荐;短 id(uuid 前 8 位)或完整 uuid 都行
373
+ * `【会话 xxxxxxxx】` ← 兼容"直接复制模板再改"
374
+ *
375
+ * 与 `routeQuoteBack`(引用回流)的分工:
376
+ * · `routeQuoteBack` 只认 `【子会话 xxxx】`,且**必须是已盯梢条目的父会话在说话** —— 语义是"回";
377
+ * · 本组函数认**任意 id**、**不需要绑定**、也不用先盯梢 —— 语义是"去"。
378
+ */
379
+ // ★ 2026-11-18:**同时认全角方括号**。
380
+ // 插件 1.13.16 起把消息正文里"形似发送者标签"的方括号降级成全角(防提示词注入伪造),
381
+ // `[s:6df40d2a]` 一度被一起转义成 `[s:6df40d2a]` ⇒ 路由永远匹配不到。
382
+ // 插件侧已把转义判定收窄(只转带 openid/群昵称/短号特征的),这里再放宽一层做双保险。
383
+ const ROUTE_RE = /(?:[\[[]s:|【\s*会话\s*)([0-9a-zA-Z][0-9a-zA-Z-]{2,63})\s*[\]]]?】?/;
384
+
385
+ /** 从正文里抽路由目标 key(返回 '' = 这不是一条路由消息) */
386
+ export function parseRouteKey(text) {
387
+ const m = ROUTE_RE.exec(String(text ?? ''));
388
+ return m ? m[1] : '';
389
+ }
390
+
391
+ /** 剥掉路由标记 —— 送进目标会话的是"去掉标记后的正文" */
392
+ export function stripRouteMark(text) {
393
+ return String(text ?? '')
394
+ .replace(new RegExp(ROUTE_RE.source, 'g'), ' ')
395
+ .replace(/[ \t]{2,}/g, ' ')
396
+ .trim();
397
+ }
398
+
399
+ /** `~/.dsh/sessions` 根目录(Windows 用 USERPROFILE,其余用 HOME) */
400
+ function sessionsRootDir() {
401
+ const home = String(process.env.USERPROFILE || process.env.HOME || '').trim();
402
+ return home ? join(home, '.dsh', 'sessions') : '';
403
+ }
404
+
405
+ /**
406
+ * **扫盘**把短 id 解析成完整会话 id —— **不依赖对方是否 live**(这是"任何已有会话"的关键)。
407
+ * 目录形状:`~/.dsh/sessions/<工作区转义名>/<uuid>/`。
408
+ * @returns {{id: string, workspace: string}} 找不到时 id 为 ''
409
+ */
410
+ export function findSessionOnDisk(key) {
411
+ const want = String(key ?? '').toLowerCase().trim();
412
+ if (!want) return { id: '', workspace: '' };
413
+ // 已经是完整 uuid ⇒ 直接认
414
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(want)) {
415
+ return { id: want, workspace: '' };
416
+ }
417
+ if (want.length < 4) return { id: '', workspace: '' };
418
+ const root = sessionsRootDir();
419
+ if (!root) return { id: '', workspace: '' };
420
+ try {
421
+ for (const ws of readdirSync(root)) {
422
+ let entries = [];
423
+ try { entries = readdirSync(join(root, ws)); } catch { continue; }
424
+ for (const d of entries) {
425
+ const raw = String(d).toLowerCase();
426
+ // ⚠️ 会话目录名**可能带前缀**(子会话是 `session-<uuid>`)⇒ 两边都过 shortSessionId 再比,
427
+ // 否则像 `cf871e99` 这种短 id 会解析失败(本轮实测踩到)。
428
+ const sh = shortSessionId(String(d)).toLowerCase();
429
+ if (sh.startsWith(want) || raw.startsWith(want)) return { id: String(d), workspace: String(ws) };
430
+ }
431
+ }
432
+ } catch { /* ignore */ }
433
+ return { id: '', workspace: '' };
434
+ }
435
+
436
+ /**
437
+ * 列会话目录(按 mtime 从新到旧)—— 给「/会话列表」命令用。
438
+ * @param {string} [workspaceDir] 传了就只列该工作区;不传列全部
439
+ */
440
+ export function listSessionDirs(workspaceDir) {
441
+ const root = sessionsRootDir();
442
+ if (!root) return [];
443
+ const out = [];
444
+ const pushWs = (ws) => {
445
+ const wsDir = join(root, ws);
446
+ let entries = [];
447
+ try { entries = readdirSync(wsDir); } catch { return; }
448
+ for (const d of entries) {
449
+ const dir = join(wsDir, d);
450
+ let mtime = 0;
451
+ try { mtime = statSync(dir).mtimeMs; } catch { /* ignore */ }
452
+ out.push({ id: String(d), short: shortSessionId(String(d)), workspace: String(ws), mtime });
453
+ }
454
+ };
455
+ try {
456
+ if (workspaceDir) pushWs(workspaceDir);
457
+ else for (const ws of readdirSync(root)) pushWs(ws);
458
+ } catch { /* ignore */ }
459
+ return out.sort((a, b) => (b.mtime || 0) - (a.mtime || 0));
460
+ }
461
+
462
+ /** 列出 `~/.dsh/sessions` 下的工作区转义目录名(给向导第一步用) */
463
+ export function listWorkspaceDirs() {
464
+ const root = sessionsRootDir();
465
+ if (!root) return [];
466
+ try { return readdirSync(root).filter((d) => !String(d).startsWith('.')); } catch { return []; }
467
+ }
468
+
469
+ export function resolveShortId(root, short) {
470
+ const want = String(short ?? '').toLowerCase();
471
+ if (!want) return '';
472
+ const hit = (id) => {
473
+ const s = String(id ?? '');
474
+ return s && shortSessionId(s).toLowerCase().startsWith(want) ? s : '';
475
+ };
476
+ try {
477
+ // ① 最快的一条:agents 服务上按 id 前缀找(若提供了 list)
478
+ const svc = (k) => { try { return root?.get?.(k); } catch { return undefined; } };
479
+ for (const key of ['sessions', 'agents']) {
480
+ const s = svc(key);
481
+ if (!s) continue;
482
+ const bags = [];
483
+ if (typeof s.list === 'function') { try { bags.push(s.list()); } catch { /* ignore */ } }
484
+ if (typeof s.values === 'function') { try { bags.push([...s.values()]); } catch { /* ignore */ } }
485
+ if (typeof s.all === 'function') { try { bags.push(s.all()); } catch { /* ignore */ } }
486
+ if (Array.isArray(s)) bags.push(s);
487
+ for (const bag of bags) {
488
+ const arr = Array.isArray(bag) ? bag : (bag && typeof bag === 'object' ? Object.values(bag) : []);
489
+ for (const it of arr) {
490
+ const id = String(it?.id ?? it?.sessionId ?? it ?? '');
491
+ const got = hit(id);
492
+ if (got) return got;
493
+ }
494
+ }
495
+ }
496
+ } catch { /* ignore */ }
497
+ return '';
498
+ }
499
+
500
+ /**
501
+ * 把 `turn/end` 的 reason 归一成字符串。
502
+ *
503
+ * ⚠️ 2026-10-12 实测:`event.data.reason` **不是字符串而是对象**,形如
504
+ * `{kind:'completed'}` 或 `{kind:'aborted', reason:{kind:'user'}}`。
505
+ * 旧代码直接 `String(reason)` ⇒ 摘要行里出现 `回合[object object](reason=[object Object])`。
506
+ * 本函数优先取最外层的 `kind`,没有就下钻内层 `reason`,都不是才退回 String()。
507
+ */
508
+ export function reasonKind(value) {
509
+ if (value === null || value === undefined) return '';
510
+ if (typeof value === 'string') return value;
511
+ if (typeof value === 'object') {
512
+ if (typeof value.kind === 'string' && value.kind) return value.kind;
513
+ if (value.reason !== undefined && value.reason !== value) return reasonKind(value.reason);
514
+ if (typeof value.status === 'string' && value.status) return value.status;
515
+ if (typeof value.stopReason === 'string' && value.stopReason) return value.stopReason;
516
+ }
517
+ return String(value);
518
+ }
519
+
520
+ /**
521
+ * 把各种可能的 content 形状压成纯文本。
522
+ *
523
+ * ★ 2026-10-12 修(主人实测):**只取 `type === 'text'` 的正文块**。
524
+ * 早先的过滤条件是 `x.type === 'text' || typeof x.text === 'string'` ——
525
+ * 而 **reasoning(思考)块同样带 `.text` 字符串**,于是思考被一起并进来,
526
+ * 回灌的"结尾正文"里冒出一整段英文思考(子会话 3bee83ac 那次实测)。
527
+ * reasoning / tool-call 等块一律丢弃。
528
+ */
529
+ function asText(c) {
530
+ if (typeof c === 'string') return c.trim();
531
+ if (Array.isArray(c)) {
532
+ return c
533
+ .filter((x) => x && x.type === 'text' && typeof x.text === 'string')
534
+ .map((x) => String(x.text))
535
+ .join('\n')
536
+ .trim();
537
+ }
538
+ if (c && typeof c === 'object') {
539
+ if (c.type === 'reasoning') return ''; // 思考块不算正文
540
+ if (typeof c.text === 'string') return String(c.text).trim();
541
+ if (Array.isArray(c.blocks)) return asText(c.blocks); // 有些版本正文藏在 blocks 里
542
+ }
543
+ return '';
544
+ }
545
+
546
+ /** 从事件里尽力抽正文(assistant/message 的形状随版本变,逐层试) */
547
+ function textOf(ev) {
548
+ const cands = [
549
+ ev?.data?.message?.content,
550
+ ev?.data?.content,
551
+ ev?.message?.content,
552
+ ev?.data?.text,
553
+ ev?.text,
554
+ ev?.data?.message?.text,
555
+ ];
556
+ for (const c of cands) {
557
+ const t = asText(c);
558
+ if (t) return t;
559
+ }
560
+ return '';
561
+ }
562
+
563
+ /** 兜底:直接从会话实例取"最后一条助手消息"的正文 */
564
+ function lastAssistantText(root, sid) {
565
+ try {
566
+ const sess = root.get('sessions')?.get?.(sid);
567
+ const msgs = sess?.deriveMessages?.() ?? [];
568
+ for (let i = msgs.length - 1; i >= 0; i -= 1) {
569
+ const m = msgs[i];
570
+ const role = String(m?.role ?? m?.type ?? '');
571
+ if (role.includes('assistant')) {
572
+ const t = asText(m?.content);
573
+ if (t) return t;
574
+ }
575
+ }
576
+ } catch { /* ignore */ }
577
+ return '';
578
+ }
579
+
580
+ /**
581
+ * 注入前的形状自检(fail-closed)。
582
+ *
583
+ * 复刻宿主 v4 的准入条件(dsh-session-persistence-jsonl/lib/worker.cjs):
584
+ * ① `agent/inbox/spliced` 的 `inserted[]` 每项必须 `isSessionFormatJsonObject`;
585
+ * ② 每项的 `source` 必须是对象、`kind` 为非空字符串、且 !== 'plugin'
586
+ * (源码原文:`format v4 message requires a producer-owned source kind`)。
587
+ *
588
+ * 为什么必须自检而不是交给 inject():宿主是**先 append 落盘、后读 source.kind** 的顺序。
589
+ * 传进非对象时,坏记录已经写进 `inserted[]`,之后投影抛错 —— 文件从此无法加载。
590
+ * 事故实例:会话 9643a885 的 seq 4222 被写成 `inserted: ["<字符串>"]`,整个会话读不出来。
591
+ */
592
+ export function isInjectableMessage(m) {
593
+ if (!m || typeof m !== 'object' || Array.isArray(m)) return false;
594
+ if (typeof m.role !== 'string' || !m.role) return false;
595
+ if (!Array.isArray(m.content) || m.content.length === 0) return false;
596
+ const src = m.source;
597
+ if (!src || typeof src !== 'object' || Array.isArray(src)) return false;
598
+ if (typeof src.kind !== 'string' || !src.kind || src.kind === 'plugin') return false;
599
+ return true;
600
+ }
601
+
602
+ /** 造一条纯文本 user 消息(供 inject / followup 用;形状已过 isInjectableMessage) */
603
+ function userText(text) {
604
+ return {
605
+ id: (globalThis.crypto?.randomUUID?.() ?? ('inj-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8))),
606
+ role: 'user',
607
+ content: [{ type: 'text', text: String(text ?? '') }],
608
+ source: { kind: 'user' },
609
+ };
610
+ }
611
+
612
+ /**
613
+ * 构造一条「子会话结算通知」形状的回灌消息(纯函数,便于单测)。
614
+ *
615
+ * 形状**对齐宿主** dsh-subagent/lib/index.js 的 `createSettlementMessage()`:
616
+ * source : { kind:'subagent-settled', form:'notice', summary, senderSessionId }
617
+ * content: [ 摘要行, 结尾正文引导语, ...正文块 ],role 由 createUserMessage 固定为 'user'
618
+ *
619
+ * 采用宿主形状的三个理由:
620
+ * ① kind 是宿主自有的 producer-owned 值,不再冒充真人 user 发言;
621
+ * ② senderSessionId 明确归属到具体子会话,UI 侧归进**子任务**那条通道而不是混进
622
+ * 用户真实发言流里 —— 这与上一轮「回灌插错位置」是同一类隐患;
623
+ * ③ summary 与宿主同口径(dsh-llm CONTEXT_SUMMARY_MAX_CHARS = 120)。
624
+ *
625
+ * @param {{sessionId?: string, label?: string, rawReason?: string, text?: string}} input
626
+ * @returns 可直接交给 agent.inject() 的完整消息对象
627
+ */
628
+ export function buildSettlementNotice(input = {}) {
629
+ const sid = String(input.sessionId ?? '');
630
+ const label = String(input.label ?? '');
631
+ const rawReason = String(input.rawReason ?? '');
632
+ const stage = reasonText(rawReason);
633
+ const summary = boundContextSummary(
634
+ `子会话${label ? '「' + label + '」' : ''} ${shortSessionId(sid)}… 回合${stage}` +
635
+ `${rawReason && rawReason !== stage ? '(reason=' + rawReason + ')' : ''}`,
636
+ );
637
+ return {
638
+ id: (globalThis.crypto?.randomUUID?.() ?? ('inj-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8))),
639
+ role: 'user',
640
+ content: [
641
+ // ★ 主人 2026-10-12 定:模拟用户消息的**首行直接给出源会话 id**(完整 id)。
642
+ { type: 'text', text: '【来自会话 ' + sid + '】' },
643
+ { type: 'text', text: summary },
644
+ { type: 'text', text: '它的结尾正文:' },
645
+ { type: 'text', text: String(input.text ?? '') },
646
+ { type: 'text', text: '(这是子会话的自动回灌,父会话无需回复。)' },
647
+ ],
648
+ // ★ 2026-10-12 主人定案:回灌**一律模拟用户消息**(source.kind='user'),
649
+ // 不再伪装成子会话结算通知 / 系统消息 / 开发者消息。
650
+ source: { kind: 'user' },
651
+ };
652
+ }
653
+
654
+ // ─────────────────────────── 转发到 QQ ───────────────────────────
655
+
656
+ /**
657
+ * 往「父会话所在的 QQ」发一条消息。
658
+ *
659
+ * 链路(**全部复用插件已有的能力**,本库不自己重写降级/被动逻辑):
660
+ * · `sender.sendMarkdown(replyTarget, text)` —— replyTarget 自带最近 msgId ⇒ 被动回复;
661
+ * 插件的 sendMarkdown 自带 markdown → 纯文本的降级链。
662
+ * · 失败再退 `sender.sendText(replyTarget, text)`(纯文本兜底)。
663
+ *
664
+ * @returns 人话结果('' = 没配 sender,静默不发)
665
+ */
666
+ async function forwardToQq(entry, text) {
667
+ const fwd = entry?.fwd;
668
+ const body = String(text ?? '').trim();
669
+ // ★ 2026-10-15:**不再静默**。之前三个条件任一不满足就 `return ''`,日志里一个字都没有,
670
+ // "重启后那段时间子会话内容悄悄没转发"因此无从定位(主人实测踩到)。
671
+ if (!fwd?.sender || !fwd?.replyTarget || !body) {
672
+ void swDiag('forward-skip short=' + String(entry?.shortId ?? '?')
673
+ + ' fwd=' + (fwd ? 'obj' : String(fwd))
674
+ + ' sender=' + !!fwd?.sender + ' replyTarget=' + !!fwd?.replyTarget
675
+ + ' bodyLen=' + body.length);
676
+ return '';
677
+ }
678
+ const target = fwd.replyTarget;
679
+
680
+ /**
681
+ * ★★ 2026-10-15:**摘掉 msgId 的"主动版" target** ★★
682
+ * 实测真凶:`fwd.replyTarget` 里钉着**绑定那一刻的 msgId**(为走"被动回复"),
683
+ * 而 QQ 的被动回复 **msg_id 会过期** ⇒ 老盯梢(如 bee798c0)发送时报
684
+ * `API Error: 回复消息msg_id已过期`,markdown/纯文本两条降级链**都**因此失败,
685
+ * 内容静默丢失。新建的盯梢 msgId 新鲜 ⇒ 正常。
686
+ * ⇒ 发送失败时摘掉 msgId 再发一次 = 转"主动发送"(会耗主动配额,但总比丢消息好)。
687
+ */
688
+ const activeTarget = (() => {
689
+ try {
690
+ if (!target || typeof target !== 'object') return null;
691
+ const t = { ...target };
692
+ let touched = false;
693
+ for (const k of ['msgId', 'msg_id', 'messageId', 'referenceMessageId']) {
694
+ if (k in t) { delete t[k]; touched = true; }
695
+ }
696
+ return touched ? t : null;
697
+ } catch { return null; }
698
+ })();
699
+
700
+ /**
701
+ * ★ 2026-10-15 主人定:**同一 msgId 用满 4 条就直接转主动**(不等它失败)。
702
+ * 被动回复有两条硬限制:①同一 msg_id 最多 ~4-5 条;②msg_id 会过期。
703
+ * 插件的 outbound.ts 对"AI 正文"有 ADAPTIVE_MAX_PASSIVE=5 的同类计数,但**转发这条路没有**,
704
+ * 所以这里自己数:同一 msgId 发到第 4 条起就摘掉它走主动。
705
+ */
706
+ const _midOf = (t) => String(t?.msgId ?? t?.msg_id ?? t?.messageId ?? '');
707
+ const passiveMid = _midOf(target);
708
+ const counts = (entry.__fwdPassiveCounts ??= new Map());
709
+ const used = passiveMid ? (counts.get(passiveMid) ?? 0) : 0;
710
+ const PASSIVE_LIMIT = 4;
711
+ const skipPassive = !passiveMid || used >= PASSIVE_LIMIT;
712
+ if (skipPassive) {
713
+ void swDiag('forward-passive-skip short=' + String(entry?.shortId ?? '?')
714
+ + ' mid=' + (passiveMid ? passiveMid.slice(0, 12) : '-') + ' used=' + used);
715
+ }
716
+
717
+ const trySend = async (tg) => {
718
+ try {
719
+ if (typeof fwd.sender.sendMarkdown === 'function') {
720
+ await fwd.sender.sendMarkdown(tg, body);
721
+ return 'md';
722
+ }
723
+ } catch (e) {
724
+ const em = String(e?.message ?? e);
725
+ try {
726
+ if (typeof fwd.sender.sendText === 'function') {
727
+ await fwd.sender.sendText(tg, body);
728
+ return 'text';
729
+ }
730
+ } catch (e2) { throw new Error(em + ' | text:' + String(e2?.message ?? e2)); }
731
+ throw new Error(em);
732
+ }
733
+ try {
734
+ if (typeof fwd.sender.sendText === 'function') {
735
+ await fwd.sender.sendText(tg, body);
736
+ return 'text';
737
+ }
738
+ } catch (e) { throw new Error(String(e?.message ?? e)); }
739
+ return '';
740
+ };
741
+
742
+ // ① 先按原样(被动回复,省主动配额)
743
+ try {
744
+ // ★ 同一 msgId 用满 4 条 ⇒ 直接跳过被动、走下面的主动分支(不再等它失败)
745
+ if (skipPassive) throw new Error('skip-passive: mid=' + (passiveMid || '-') + ' used=' + used);
746
+ const how = await trySend(target);
747
+ if (how) {
748
+ if (passiveMid) counts.set(passiveMid, used + 1);
749
+ void swDiag('forward-ok(' + how + ') short=' + String(entry?.shortId ?? '?') + ' len=' + body.length
750
+ + ' passive=' + (passiveMid ? passiveMid.slice(0, 12) + '#' + (used + 1) : '-'));
751
+ return how;
752
+ }
753
+ } catch (e1) {
754
+ void swDiag('forward-passive-fail short=' + String(entry?.shortId ?? '?')
755
+ + ' err=' + String(e1?.message ?? e1));
756
+ // ② 失败 ⇒ 摘掉 msgId 重发(主动)。这是"msg_id 过期"的正解。
757
+ if (activeTarget) {
758
+ try {
759
+ const how2 = await trySend(activeTarget);
760
+ if (how2) {
761
+ void swDiag('forward-ok-active(' + how2 + ') short=' + String(entry?.shortId ?? '?')
762
+ + ' len=' + body.length + '(被动失败后转主动)');
763
+ return how2 + '-active';
764
+ }
765
+ } catch (e2) {
766
+ void swDiag('forward-active-fail short=' + String(entry?.shortId ?? '?')
767
+ + ' err=' + String(e2?.message ?? e2));
768
+ }
769
+ } else {
770
+ void swDiag('forward-active-skip short=' + String(entry?.shortId ?? '?')
771
+ + '(target 上没有 msgId 可摘,或 target 形状异常)');
772
+ }
773
+ }
774
+ void swDiag('forward-fail short=' + String(entry?.shortId ?? '?') + ' senderKeys='
775
+ + (fwd?.sender ? Object.keys(fwd.sender).slice(0, 10).join(',') : '-'));
776
+ return '';
777
+ }
778
+
779
+ /**
780
+ * ★ 2026-10-15:诊断**落盘**。route-isolate 文件头留过教训:
781
+ * "一开始只往 logger 写,而**从来没人注入过 logger** ⇒ 真机上完全静默、无法定位。"
782
+ * 本库涉及"转发到 QQ",静默一次就是一条内容永久丢失,必须能事后追。
783
+ */
784
+ // ★ 2026-10-24 修复(issue #17): 原来写死 Windows 路径(D:/…) —— Linux/容器/手机上会被当成
785
+ // 相对路径,在家目录里生成一个叫 "D:" 的畸形目录,日志全丢。改成跟着本文件走。
786
+ const SW_DIAG_FILE = fileURLToPath(new URL('../../data/session-watch-diag.log', import.meta.url));
787
+
788
+ async function swDiag(line) {
789
+ try {
790
+ const { appendFile, mkdir } = await import('node:fs/promises');
791
+ const { dirname } = await import('node:path');
792
+ await mkdir(dirname(SW_DIAG_FILE), { recursive: true });
793
+ await appendFile(SW_DIAG_FILE, new Date().toISOString() + ' ' + line + '\n');
794
+ } catch { /* 诊断失败不影响主链 */ }
795
+ }
796
+
797
+ /**
798
+ * 转发到 QQ 之前,把「只给插件自己看的标记」洗掉(主人 2026-10-12 要求:"剥掉 @")。
799
+ *
800
+ * 为什么必须洗:子会话继承的是同一个人设,所以它写正文时会带上本插件的出站约定标记。
801
+ * 而我们是用 `sender.sendMarkdown()` **直发**的,插件那层出站解析并不参与 ⇒ 这些标记会
802
+ * 原样变成裸文本出现在群里。实测踩到的两条:
803
+ * · `[rf:1012ad]` —— 引用标记,本来是给插件出站解析用的,转发后就是一行看不懂的裸文本;
804
+ * · `<@E9020753…>` —— **QQ 提及语法,会真的在群里 @ 到人**(子会话回主人一句就被 @ 一下)。
805
+ * 只洗这三类,别的(正文、换行、markdown)一律不动。
806
+ */
807
+ export function sanitizeForQq(text) {
808
+ return String(text ?? '')
809
+ .replace(/\[\s*rf\s*:[^\]]*\]/gi, '') // [rf:1012ad] 引用标记
810
+ .replace(/<@[^>\s]{2,}>/g, '') // <@openid> 提及语法(会真 @ 到人)
811
+ .replace(/^\s*@[^\s@]{1,24}\s+/gm, '') // 行首零散的 @某人(只吃行首那一下)
812
+ .replace(/[ \t]{2,}/g, ' ') // 洗掉留下的多余空格
813
+ .replace(/\n{3,}/g, '\n\n')
814
+ .trim();
815
+ }
816
+
817
+ /** 给转发消息套上行首归属(**路由键在最前**,会话名/预设/工作区跟在后面,引用回流就靠它认路) */
818
+ function withOwner(entry, text) {
819
+ return ownerLine({
820
+ shortId: entry?.shortId,
821
+ name: entry?.name,
822
+ preset: entry?.preset,
823
+ workspace: entry?.workspace,
824
+ }) + '\n' + sanitizeForQq(text);
825
+ }
826
+
827
+ // ─────────────────────────── 事件处理 ───────────────────────────
828
+
829
+ /** 该会话是不是某个盯梢对象的父会话(引用回流只从父会话的入站消息里认) */
830
+ function parentEntryOf(sid) {
831
+ for (const [, w] of watching) if (w.parentAgentId === sid) return w;
832
+ return null;
833
+ }
834
+
835
+ /**
836
+ * 引用回流:入站消息里认出 `【子会话 xxxx】` → 把这段引用**插话**给对应子会话。
837
+ *
838
+ * 主人 2026-10-12 口径:**只靠行首的会话信息判断,不依赖台账**。
839
+ * 短 id → 完整 id 用 resolveShortId 当场查;查不到就静默放弃(绝不猜)。
840
+ */
841
+ /**
842
+ * ★ 2026-10-14 主人需求:**通用路由** —— 把群里这条消息投递给"正文里点名的那个会话"。
843
+ *
844
+ * 流程:解析 key → 找会话(**先 live、后扫盘**)→ 投递(忙 `inject` 插话 / 闲 `followup` 唤醒)。
845
+ * 与 `routeQuoteBack` 的区别:**不限"已盯梢"、不限"父会话在说话"、认任意 id**。
846
+ *
847
+ * ★ 附件(2026-10-14 补):QQ 里**引用图片/文件**时,图**不在正文里** —— 它在入站事件的
848
+ * `attachments`(`{contentType,url,filename,asrText}`,见插件 `transport/inbound.ts`)。
849
+ * 只取文本会把图丢掉,所以这里额外把附件 URL/语音转写一并拼进载荷。
850
+ * @returns {Promise<{ok: boolean, reason: string, id?: string, workspace?: string, atts?: number}>}
851
+ */
852
+ /**
853
+ * ★ 对外导出(2026-10-14):入站扩展要**在钩子之前**自己投递 —— 因为"二档路由隔绝"会把这条消息
854
+ * 在早挂点就 annihilate 掉,一旦消灭成功,`session/event` 的 `user/message` 就永远不会发生,
855
+ * 原来那条投递路径(本文件里的监听器)根本不会跑。所以投递逻辑必须能被扩展直接调。
856
+ */
857
+ export async function routeToSession(root, text, ev) {
858
+ try {
859
+ const key = parseRouteKey(text);
860
+ if (!key) return { ok: false, reason: 'no-key' };
861
+ const body = stripRouteMark(text);
862
+ // ① 先问宿主(快,只认 live)
863
+ let fullId = resolveShortId(root, key);
864
+ let workspace = '';
865
+ // ② live 查不到 ⇒ **扫盘**("任何已有会话"就靠这一步)
866
+ if (!fullId) {
867
+ const disk = findSessionOnDisk(key);
868
+ fullId = disk.id;
869
+ workspace = disk.workspace;
870
+ }
871
+ if (!fullId) return { ok: false, reason: 'not-found', id: key };
872
+ const agents = (() => { try { return root?.get?.('agents'); } catch { return null; } })();
873
+ let target = (() => { try { return agents?.get?.(fullId) ?? null; } catch { return null; } })();
874
+ // ③ 没活着 ⇒ 试着唤醒(宿主 agents.resume;拿不到就算了,绝不硬造 agent)
875
+ if (!target && agents && typeof agents.resume === 'function') {
876
+ try { target = await agents.resume(fullId); } catch { /* ignore */ }
877
+ }
878
+ if (!target) return { ok: false, reason: 'not-live', id: fullId, workspace };
879
+ // ④ 附件(图片/文件的 URL、语音转写)—— 引用图片时图就在这里
880
+ const atts = attachmentsOf(ev);
881
+ if (!body && !atts.length) return { ok: false, reason: 'empty-body', id: fullId, workspace };
882
+ const lines = ['【群里有人把这条消息路由给你】'];
883
+ if (body) lines.push(body);
884
+ if (atts.length) {
885
+ lines.push('');
886
+ lines.push('(随消息一起来的附件:)');
887
+ for (const a of atts) {
888
+ const kind = String(a?.contentType ?? '');
889
+ const url = String(a?.url ?? '');
890
+ const name = String(a?.filename ?? '');
891
+ const asr = String(a?.asrText ?? '');
892
+ const tag = /image/i.test(kind) ? '图片' : (/video/i.test(kind) ? '视频' : (/audio|voice/i.test(kind) ? '语音' : (/file|application/i.test(kind) ? '文件' : '附件')));
893
+ let line = `- ${tag}`;
894
+ if (name) line += `:${name}`;
895
+ if (url) line += `\n ${url}`;
896
+ if (asr) line += `\n (语音转写)${asr}`;
897
+ lines.push(line);
898
+ }
899
+ }
900
+ lines.push('(这是跨会话路由,按需回应即可。)');
901
+ const msg = userText(lines.join('\n'));
902
+ if (!isInjectableMessage(msg)) return { ok: false, reason: 'bad-shape', id: fullId, workspace };
903
+ const busy = (() => {
904
+ try {
905
+ const st = String(target.status ?? target.phase ?? '');
906
+ return st !== '' && st !== 'idle';
907
+ } catch { return false; }
908
+ })();
909
+ if (busy) await target.inject(msg);
910
+ else await target.followup(msg);
911
+ return { ok: true, reason: busy ? 'inject' : 'followup', id: fullId, workspace, atts: atts.length };
912
+ } catch (e) {
913
+ return { ok: false, reason: 'error:' + (e instanceof Error ? e.message : String(e)) };
914
+ }
915
+ }
916
+
917
+ /**
918
+ * 从入站事件里挖附件(多路兜底,形状照插件 `transport/inbound.ts` 的 `RawAttachment`)。
919
+ * 只保留有 url / asrText 的项,避免塞一堆空对象过去。
920
+ */
921
+ export function attachmentsOf(ev) {
922
+ const cands = [
923
+ ev?.data?.message?.attachments,
924
+ ev?.data?.attachments,
925
+ ev?.message?.attachments,
926
+ ev?.attachments,
927
+ ];
928
+ for (const c of cands) {
929
+ if (!Array.isArray(c) || c.length === 0) continue;
930
+ const out = [];
931
+ for (const a of c) {
932
+ if (!a || typeof a !== 'object') continue;
933
+ const url = String(a.url ?? a.URL ?? '').trim();
934
+ const asr = String(a.asrText ?? a.asr_text ?? '').trim();
935
+ if (!url && !asr) continue;
936
+ out.push({
937
+ contentType: String(a.contentType ?? a.content_type ?? ''),
938
+ url,
939
+ filename: String(a.filename ?? a.fileName ?? ''),
940
+ asrText: asr,
941
+ });
942
+ }
943
+ if (out.length) return out;
944
+ }
945
+ return [];
946
+ }
947
+
948
+ async function routeQuoteBack(root, inboundText) {
949
+ const short = parseOwner(inboundText);
950
+ if (!short) return;
951
+ const childId = resolveShortId(root, short);
952
+ if (!childId) return;
953
+ const agents = root.get('agents');
954
+ const child = agents?.get?.(childId) ?? null;
955
+ if (!child) return; // 子会话不在(不 live)→ 静默跳过
956
+ const payload =
957
+ '【群里有人引用了你发到 QQ 的那段输出】\n' +
958
+ String(inboundText ?? '').trim() +
959
+ '\n(这是群里的引用互动,按需回应即可。)';
960
+ const msg = userText(payload);
961
+ if (!isInjectableMessage(msg)) return;
962
+ try {
963
+ const busy = (() => {
964
+ try {
965
+ const st = String(child.status ?? child.phase ?? '');
966
+ return st !== '' && st !== 'idle';
967
+ } catch { return false; }
968
+ })();
969
+ if (busy) await child.inject(msg); // 忙 → 插话(不唤醒、不排队)
970
+ else await child.followup(msg); // 空闲 → 唤醒它来处理
971
+ const w = watching.get(childId);
972
+ if (w) w.quotedAt = Date.now();
973
+ } catch { /* 监听里绝不抛 */ }
974
+ }
975
+
976
+ /**
977
+ * ★ 2026-10-13 补:**重启后把 QQ 转发能力补回来**。
978
+ *
979
+ * 背景:`fwd`(sender + replyTarget)**不可序列化**(sender 是 live 的 bot 对象),
980
+ * 所以启动恢复的名单里 `fwd` 只能是 null。现象就是"一个根因、两个症状":
981
+ * · 回灌照常进父会话,但 **不再转发到 QQ**;
982
+ * · 群里因此没有那条带「【子会话 xxxx】」行首的转发消息 ⇒ **引用回流也认不到路**(OWNER_RE 匹配不上)。
983
+ *
984
+ * 修法:**父会话一发言**(user/message 事件)就把 fwd 补回来 —— sender 取插件的 bot,
985
+ * replyTarget 从 session / root 上尽力凑。补上后当场可用;下次重启会再丢,但父会话一说话又补上,
986
+ * 因此只在"父会话长期静默"时转发会缺,实际影响很小。
987
+ * @returns {boolean} 是否可用
988
+ */
989
+ function hydrateFwd(entry, root, session) {
990
+ try {
991
+ if (!entry || typeof entry !== 'object') return false;
992
+ if (entry.fwd?.sender && entry.fwd?.replyTarget) return true;
993
+ // ★ 2026-10-13:**优先用"扩展工具侧注入"的 sender/replyTarget** —— 工具 env 里一定有这两样
994
+ // (`session_watch.mjs` 每次被调用都会把它们挂到 globalThis[FWD_KEY])。
995
+ // 实测 `root`(插件根 ctx)上拿不到 sender ⇒ 只靠 root 是补不回来的。
996
+ const injected = globalThis[FWD_KEY] ?? null;
997
+ const sender = injected?.sender ?? (root && (root.bot ?? root.sender)) ?? null;
998
+ const s = session ?? {};
999
+ const scope = String(s.scope ?? s.peerScope ?? '') || (s.peerId ? 'group' : '');
1000
+ const peerId = String(s.peerId ?? s.peer ?? s.groupOpenid ?? '');
1001
+ const replyTarget =
1002
+ injected?.replyTarget ??
1003
+ s.replyTarget ??
1004
+ (root && (root.replyTarget ?? root.lastReplyTarget)) ??
1005
+ (scope && peerId ? { scope, peerId } : null);
1006
+ if (!sender || !replyTarget) {
1007
+ try {
1008
+ root?.logger?.warn?.(
1009
+ `[ext-hook:session-watch] hydrateFwd 补不上:sender=${!!sender} replyTarget=${!!replyTarget}` +
1010
+ ` injected=${!!injected} rootKeys=[${root ? Object.keys(root).slice(0, 16).join(',') : '-'}]` +
1011
+ ` sessionKeys=[${Object.keys(s).slice(0, 16).join(',')}]`,
1012
+ );
1013
+ } catch { /* ignore */ }
1014
+ return false;
1015
+ }
1016
+ entry.fwd = { sender, replyTarget };
1017
+ try { root?.logger?.info?.('[ext-hook:session-watch] 已补回 QQ 转发能力(sender + replyTarget)'); } catch { /* ignore */ }
1018
+ return true;
1019
+ } catch { return false; }
1020
+ }
1021
+
1022
+ async function handler(root, session, event) {
1023
+ try {
1024
+ const sid = String(session?.id ?? session?.sessionId ?? '');
1025
+ if (!sid) return;
1026
+ const type = String(event?.type ?? '');
1027
+
1028
+ // ── 引用回流:只关心**入站 user 消息**,且只在"某个盯梢对象的父会话"里认 ──
1029
+ if (type === 'user/message') {
1030
+ // ★ 2026-10-14:先学"这个 QQ 对象最近在哪个会话说话"(父会话跟着 QQ 对象走的依据)。
1031
+ // 必须放在路由分支**之前** —— 否则主人只发路由消息时,这张表永远学不到东西。
1032
+ notePeerSeen(session, sid);
1033
+ const t = textOf(event);
1034
+ // ★ 2026-10-14:**通用路由优先** —— 正文里出现会话 id(`[s:xxx]` / `【会话 xxx】`)就直接投给
1035
+ // 那个会话。**不限已盯梢、不限是不是父会话**(主人要的"任何已有会话都能被点名")。
1036
+ if (t && parseRouteKey(t)) {
1037
+ const r = await routeToSession(root, t, event);
1038
+ try {
1039
+ root?.logger?.info?.(
1040
+ `[ext-hook:session-watch] 路由 ${r.ok ? '✅' : '✗'} ${r.reason}` +
1041
+ (r.id ? ` → ${shortSessionId(r.id)}…${r.workspace ? `(${r.workspace})` : ''}` : '') +
1042
+ (r.atts ? ` 附件${r.atts}个` : ''),
1043
+ );
1044
+ } catch { /* ignore */ }
1045
+ return;
1046
+ }
1047
+ const pe = parentEntryOf(sid);
1048
+ if (pe) {
1049
+ // ★ 2026-10-13:父会话一发言,就把重启后丢失的 QQ 转发能力补回来。
1050
+ // 转发一断,群里就没有带「【子会话 xxxx】」行首的转发消息 ⇒ 引用回流也认不到路。
1051
+ hydrateFwd(pe, root, session);
1052
+ if (t && OWNER_RE.test(t)) await routeQuoteBack(root, t);
1053
+ }
1054
+ return;
1055
+ }
1056
+
1057
+ const w = watching.get(sid);
1058
+ if (!w) return;
1059
+
1060
+ // 累积(对应 qqbot 的 noteGenerated)
1061
+ if (type === 'assistant/message') {
1062
+ const t = textOf(event);
1063
+ if (t) {
1064
+ w.lastText = t;
1065
+ // 二/三档要"所有正文":按块收,重复的丢弃
1066
+ if (Array.isArray(w.texts)) { if (w.texts[w.texts.length - 1] !== t) w.texts.push(t); }
1067
+ }
1068
+ return;
1069
+ }
1070
+ // 报错也收(二/三档要一起转发)
1071
+ if (/error/i.test(type)) {
1072
+ const t = textOf(event) || String(event?.data?.message ?? event?.message ?? '').trim();
1073
+ if (t && Array.isArray(w.errors)) w.errors.push(t);
1074
+ return;
1075
+ }
1076
+ if (type !== 'turn/end') return;
1077
+
1078
+ // 结算:优先用累积到的那一段;没有再从会话实例兜底取
1079
+ let text = w.lastText;
1080
+ w.lastText = ''; // ★ 取走即清空:否则"只有工具调用、没有正文"的回合会重复回灌上一回合的正文
1081
+ if (!text) text = lastAssistantText(root, sid);
1082
+ w.seen = (w.seen ?? 0) + 1;
1083
+ const rawReason = reasonKind(event?.data?.reason ?? event?.data?.status ?? event?.data?.stopReason);
1084
+ w.lastReason = rawReason;
1085
+
1086
+ // 本回合收集物(二/三档用),取走即清
1087
+ const allTexts = Array.isArray(w.texts) ? w.texts.slice() : [];
1088
+ const errors = Array.isArray(w.errors) ? w.errors.slice() : [];
1089
+ w.texts = [];
1090
+ w.errors = [];
1091
+ const mode = Number(w.mode) === 2 ? 2 : (Number(w.mode) === 3 ? 3 : 1);
1092
+
1093
+ // ★★ 2026-10-15:**每回合无条件落盘一行** ★★
1094
+ // 实测踩到:bee798c0 重启后"不转发",而日志里连 forward-skip 都没有 ⇒ 说明它压根没
1095
+ // 走到 forwardToQq(`toForward` 为空、for 循环没进)。要区分"没收到正文事件"和"收到但被过滤",
1096
+ // 只能在 turn/end 这里把手上有什么如实记下来。
1097
+ void swDiag('turn-end short=' + String(w.shortId ?? '?')
1098
+ + ' mode=' + mode + ' rawMode=' + JSON.stringify(w.mode)
1099
+ + ' texts=' + allTexts.length + ' errs=' + errors.length
1100
+ + ' textLen=' + String(text ?? '').length
1101
+ + ' seen=' + w.seen + ' reason=' + String(rawReason ?? '-'));
1102
+
1103
+ // ── 转发到 QQ ──────────────────────────────────────────────
1104
+ // 一档:只转末段;二/三档:所有正文 + 报错
1105
+ const toForward = mode === 1
1106
+ ? (text ? [text] : [])
1107
+ : [...allTexts, ...(errors.length ? ['⚠️ 报错:\n' + errors.join('\n')] : [])];
1108
+ // ★★ 2026-10-15 主人定:转发前**先刷新 target + 数被动条数**,别钉死绑定时的 msgId ★★
1109
+ // 被动回复(带 msg_id)有两条硬限制:①同一 msg_id 最多回 ~4-5 条;②msg_id 会过期。
1110
+ // 踩到的实例:老盯梢 bee798c0 的 replyTarget 里钉着很久以前的 msgId ⇒ 发送报
1111
+ // `回复消息msg_id已过期`,md/文本两条链全挂、内容静默丢失。
1112
+ // 口径(与插件 outbound.ts 的 ADAPTIVE_MAX_PASSIVE=5 对齐):
1113
+ // · 每次转发前,把 fwd.replyTarget 刷新成**最新注入**的那份(带最新 msgId);
1114
+ // · 同一 msgId 数着用,**到 4 条**就主动转主动(摘掉 msgId),不再等它失败;
1115
+ // · 真失败(过期/超限/其它)⇒ forwardToQq 里还有一层"摘 msgId 重发"兜底。
1116
+ if (toForward.length > 0) {
1117
+ const injected = globalThis[FWD_KEY] ?? null;
1118
+ if (injected?.sender && injected?.replyTarget) {
1119
+ w.fwd = { sender: injected.sender, replyTarget: injected.replyTarget };
1120
+ } else if (!w.fwd?.sender || !w.fwd?.replyTarget) {
1121
+ const hadFwd = !!w.fwd;
1122
+ const ok = hydrateFwd(w, root, session);
1123
+ void swDiag('pre-forward hydrate short=' + String(w.shortId ?? '?')
1124
+ + ' hadFwd=' + hadFwd + ' ok=' + ok + ' mode=' + mode);
1125
+ }
1126
+ }
1127
+ for (const piece of toForward) {
1128
+ const body = withOwner(w, piece);
1129
+ // 去重:同一条内容不重复转发
1130
+ if (body === w.lastForwarded) continue;
1131
+ const how = await forwardToQq(w, body);
1132
+ if (how) w.lastForwarded = body;
1133
+ }
1134
+
1135
+ // ── 回灌进父会话上下文(二档**不进**)──────────────────────
1136
+ if (mode === 2) return;
1137
+ if (!text) return; // 空回合(只有工具调用/无正文)→ 不回灌
1138
+ // ★ 去重:兜底路径可能又取到"上一次已经灌过"的那段正文,内容相同就不再灌第二遍
1139
+ if (text === w.lastSent) return;
1140
+ w.lastSent = text;
1141
+
1142
+ const agents = root.get('agents');
1143
+ // ★ 2026-10-14:**父会话跟着 QQ 对象走** —— 该 QQ 对象当前所在的会话优先(/bot-new 之后自动跟过去),
1144
+ // 没学到才回落到绑定时写死的那个 id(老行为,向后兼容)。
1145
+ const parentId = resolveParentId(w);
1146
+ const parent = agents?.get?.(parentId) ?? null;
1147
+ if (!parent) return; // 父不在(不 live)→ 静默跳过,不制造错误
1148
+
1149
+ const candidate = buildSettlementNotice({ sessionId: sid, label: w.label, rawReason, text });
1150
+ if (!isInjectableMessage(candidate)) return; // 自检不过 → 宁可这次不回灌
1151
+ try {
1152
+ // ★ 2026-10-12 定案(照抄 qqbot 插件的入站模式 —— dist/features/qq-user-questions.js:646):
1153
+ // 「忙时插话、空闲唤醒」
1154
+ // ★ 三档(mode=3)主人要求"进上下文但**不唤醒**" ⇒ 无论忙闲都走 inject。
1155
+ const busy = (() => {
1156
+ try {
1157
+ const st = String(parent.status ?? parent.phase ?? '');
1158
+ return st !== '' && st !== 'idle';
1159
+ } catch { return false; }
1160
+ })();
1161
+ if (mode === 3 || busy) await parent.inject(candidate); // 插话(不唤醒、不排队、不进输入框)
1162
+ else await parent.followup(candidate); // 空闲 → 唤醒
1163
+ w.firedAt = Date.now();
1164
+ } catch { /* 注入失败 → 静默;监听里绝不抛,免得影响宿主事件链 */ }
1165
+ } catch { /* 监听里绝不抛,免得影响宿主事件链 */ }
1166
+ }
1167
+
1168
+ function installHook(root) {
1169
+ if (HOOK_DISABLED) return;
1170
+
1171
+ // ① 把「当前实例的 handler」发布到 globalThis:已装好的那个监听会转发到最新实例,
1172
+ // 所以改完 lib 热刷后新代码立刻接管,不必重挂监听。
1173
+ globalThis[HANDLER_KEY] = (session, event) => { void handler(root, session, event); };
1174
+
1175
+ // ② 监听全局只装一次。lib 带 mtime 版本号加载,改一次就换一个模块实例;
1176
+ // 若各实例各自 root.on 一遍,同一个 turn/end 会被回灌多次。
1177
+ if (globalThis[HOOK_KEY]) { hooked = true; return; }
1178
+ try {
1179
+ // 与 qqbot 的 mc_tell 同款:挂在插件根 ctx 上,事件回调 (session, event)。
1180
+ // 注意:回调里通过 globalThis 取 handler,永远调用最新那一版。
1181
+ root.on('session/event', (session, event) => {
1182
+ const h = globalThis[HANDLER_KEY];
1183
+ if (typeof h === 'function') h(session, event);
1184
+ });
1185
+ globalThis[HOOK_KEY] = true;
1186
+ hooked = true;
1187
+ } catch { hooked = false; }
1188
+ }
1189
+
1190
+ /**
1191
+ * 登记一个"要盯着的子会话"。
1192
+ *
1193
+ * @param {object} opts
1194
+ * · parentAgentId 父会话 id(必填)
1195
+ * · childSessionId 子会话 id(必填)
1196
+ * · label 标签(可选)
1197
+ * · name 会话名(可选;归属行显示用,缺省取 label)
1198
+ * · preset 预设名(可选;归属行显示用)
1199
+ * · workspace 工作区(可选;归属行显示用,建议传目录名而非全路径)
1200
+ * · mode 1=只回灌末段+转末段(默认) 2=只转所有正文+报错(不进父上下文) 3=进父上下文(不唤醒)+全转
1201
+ * · sender 父会话的 sender(可选;给了才转发 QQ)
1202
+ * · replyTarget 父会话所在的 QQ 目标(可选;自带最近 msgId ⇒ 被动优先)
1203
+ * · peerName 父会话所在群/私聊的名字(可选,只用于显示)
1204
+ * @returns 人话描述(挂成功/失败原因),不抛错。
1205
+ */
1206
+ export async function register(root, opts = {}) {
1207
+ const parentAgentId = String(opts.parentAgentId ?? '').trim();
1208
+ const childSessionId = String(opts.childSessionId ?? '').trim();
1209
+ const label = String(opts.label ?? '').trim();
1210
+ const mode = Number(opts.mode) === 2 ? 2 : (Number(opts.mode) === 3 ? 3 : 1);
1211
+ if (!parentAgentId || !childSessionId) return '未挂(缺 parentAgentId 或 childSessionId)';
1212
+ if (!root || typeof root.on !== 'function') return '未挂(root 不支持 .on)';
1213
+ installHook(root);
1214
+ if (HOOK_DISABLED) return '未挂(回灌钩子当前被 HOOK_DISABLED 主动关闭,属预期;恢复见 installHook 注释)';
1215
+ if (!hooked) return '未挂(root.on 抛错)';
1216
+ const fwd = (opts.sender && opts.replyTarget) ? { sender: opts.sender, replyTarget: opts.replyTarget } : null;
1217
+ // ★ 2026-10-14:记下这条盯梢属于哪个 **QQ 对象**(scope:peerId)—— 父会话要跟着它走。
1218
+ // 优先级:调用方显式给的 peerKey > replyTarget 里能抠出来的 > 空(空则退回写死的 parentAgentId)。
1219
+ const pk = String(opts.peerKey ?? '').trim() || peerKeyOfTarget(opts.replyTarget);
1220
+ watching.set(childSessionId, {
1221
+ parentAgentId,
1222
+ label,
1223
+ mode,
1224
+ shortId: shortSessionId(childSessionId),
1225
+ /** 归属行用的三件套(主人 2026-10-12 定:会话名 / 预设名 / 工作区) */
1226
+ name: String(opts.name ?? opts.label ?? '').trim(),
1227
+ preset: String(opts.preset ?? '').trim(),
1228
+ workspace: String(opts.workspace ?? '').trim(),
1229
+ peerName: String(opts.peerName ?? ''),
1230
+ peerKey: pk,
1231
+ fwd,
1232
+ lastText: '',
1233
+ texts: [],
1234
+ errors: [],
1235
+ seen: 0,
1236
+ firedAt: 0,
1237
+ lastForwarded: '',
1238
+ });
1239
+ // 绑定时先按"当时那个会话"给这张表起步;**只在没记录时写**,别把已经学到的新会话覆盖回旧的。
1240
+ if (pk && parentAgentId && !peerLatest.has(pk)) peerLatest.set(pk, parentAgentId);
1241
+ await persist();
1242
+ const modeText = mode === 2 ? '二档(全部正文+报错→QQ,不进父上下文)'
1243
+ : mode === 3 ? '三档(进父上下文但不唤醒 + 全转QQ)'
1244
+ : '一档(末段回灌父会话 + 同转QQ)';
1245
+ return `已挂(子=${shortSessionId(childSessionId)}… → 父=${shortSessionId(parentAgentId)}…;${modeText}${fwd ? ';QQ 转发就绪' : ';⚠️ 没拿到 sender/replyTarget,QQ 转发不可用'})`;
1246
+ }
1247
+
1248
+ /** 改档位(已挂的盯梢可随时改) */
1249
+ export async function setMode(childSessionId, mode) {
1250
+ const w = watching.get(String(childSessionId ?? ''));
1251
+ if (!w) return '没找到这个盯梢(先用 session_watch list 看)';
1252
+ w.mode = Number(mode) === 2 ? 2 : (Number(mode) === 3 ? 3 : 1);
1253
+ await persist();
1254
+ return `已改为 ${w.mode} 档`;
1255
+ }
1256
+
1257
+ /** 取消盯梢 */
1258
+ export async function unregister(childSessionId) {
1259
+ const ok = watching.delete(String(childSessionId ?? ''));
1260
+ if (ok) await persist();
1261
+ return ok ? '已取消盯梢' : '没找到这个盯梢';
1262
+ }
1263
+
1264
+ /** 给别的工具(如 session_watch 状态查询)读当前盯着的清单 */
1265
+ /**
1266
+ * ★ 某个路由短 id 对应的**回灌挡位**(读内存名单;没绑过返回 0)。
1267
+ *
1268
+ * 入站扩展用它判断"这条路由消息要不要在父上下文里彻底消失":
1269
+ * 挡位 2(二档)= 双向隔绝 —— 子会话的正文只去 QQ、**不进父上下文**(原有语义),
1270
+ * 那么反向也一样:**用户发进群的路由消息也不该落进父上下文**(2026-10-14 主人定)。
1271
+ * 没绑过的(纯通用路由)返回 0 ⇒ **不进隔绝**,保持原样投递 + 照常进上下文。
1272
+ */
1273
+ export function modeOfRoute(key) {
1274
+ try {
1275
+ ensureLoaded();
1276
+ const k = String(key ?? '').trim();
1277
+ if (!k) return 0;
1278
+ for (const [sid, w] of watching.entries()) {
1279
+ const short = shortSessionId(sid); // 例:fc871e99
1280
+ if (short === k || sid === k || sid === `session-${k}`) return Number(w?.mode ?? 1) || 1;
1281
+ }
1282
+ } catch { /* ignore */ }
1283
+ return 0;
1284
+ }
1285
+
1286
+ /**
1287
+ * 供工具/命令展示:这条盯梢**当前**会把回灌投给谁(= 跟着 QQ 对象动态解析之后的结果)。
1288
+ * 与 `parentAgentId`(绑定时写死的那个)不同:发过 `/bot-new` 之后这两个会不一样。
1289
+ */
1290
+ export function effectiveParentOf(childSessionId) {
1291
+ ensureLoaded();
1292
+ const w = watching.get(String(childSessionId ?? ''));
1293
+ return w ? resolveParentId(w) : '';
1294
+ }
1295
+
1296
+ export function listWatching() { ensureLoaded(); // ★ 先保证存档已读回内存(重启后第一次调它就能看到完整名单)
1297
+ return [...watching.entries()].map(([sid, w]) => ({
1298
+ childSessionId: sid,
1299
+ shortId: shortSessionId(sid),
1300
+ parentAgentId: w.parentAgentId,
1301
+ parentShortId: shortSessionId(w.parentAgentId),
1302
+ /** QQ 对象键(scope:peerId);父会话会跟着它动态解析 */
1303
+ peerKey: w.peerKey ?? '',
1304
+ /** 当前实际会投给的父会话(发过 /bot-new 后会与 parentAgentId 不同) */
1305
+ effectiveParentShortId: shortSessionId(resolveParentId(w)),
1306
+ label: w.label,
1307
+ mode: w.mode ?? 1,
1308
+ /** 归属行三件套(会随转发消息发到 QQ) */
1309
+ name: w.name ?? '',
1310
+ preset: w.preset ?? '',
1311
+ workspace: w.workspace ?? '',
1312
+ peerName: w.peerName ?? '',
1313
+ qqReady: !!w.fwd,
1314
+ hasText: !!w.lastText,
1315
+ turnsSeen: w.seen ?? 0,
1316
+ lastFiredAt: w.firedAt ?? 0,
1317
+ quotedAt: w.quotedAt ?? 0,
1318
+ }));
1319
+ }