@mcviseron/dsh-qq-bridge 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,1120 +1,1304 @@
1
- /**
2
- * dsh-qq-bridge — Host half.
3
- *
4
- * One QQ conversation (a group or a private chat) owns one DSH Session. This
5
- * plugin keeps that mapping, turns every inbound QQ message into a Session
6
- * prompt, captures the assistant text of each finished turn, keeps a rolling
7
- * transcript of group chatter, and asks the bot owner before a tool needs
8
- * approval.
9
- */
10
- import { randomUUID } from 'node:crypto'
11
- import { readFileSync } from 'node:fs'
12
- import { appendFile, mkdir } from 'node:fs/promises'
13
- import { dirname, join, resolve } from 'node:path'
14
- import { HttpBridge } from './server.js'
15
- import { ConversationStore } from './store.js'
16
-
17
- export const name = 'dsh-qq-bridge'
18
-
19
- /** Fields a profile patch may override; everything else is fixed policy. */
20
- export const DEFAULT_CONFIG = {
21
- enabled: true,
22
- host: '127.0.0.1',
23
- port: 39061,
24
- panelPort: 39062,
25
- token: '',
26
- cwd: '',
27
- statePath: '',
28
- approvalTimeoutMs: 150000,
29
- approvalDefault: 'reject',
30
- contextLines: 30,
31
- argumentPreviewChars: 600,
32
- quoteContextChars: 300,
33
- historyMax: 200,
34
- autoGroup: true,
35
- autoGroupRoot: 'D:\\dsh-qqbot-temp',
36
- streamEnabled: true,
37
- streamIntervalMs: 250,
38
- autoStartBot: true,
39
- botDir: 'D:/Program/QQ-Bot-Class/dsh-bot/bot',
40
- pythonPath: 'C:/Users/25639/.conda/envs/ChatClone-BotPy/python.exe',
41
- modelProvider: '',
42
- model: '',
43
- reasoningEffort: '',
44
- }
45
-
46
- const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
47
-
48
- /** Profile config → absolute, defaulted runtime configuration. */
49
- function resolveConfig(raw) {
50
- const config = { ...DEFAULT_CONFIG, ...(raw ?? {}) }
51
- const home = typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME !== ''
52
- ? process.env.DSH_HOME
53
- : join(process.cwd(), '.dsh')
54
- const dataDir = join(home, 'qq-bridge')
55
- return {
56
- ...config,
57
- port: Number(config.port ?? DEFAULT_CONFIG.port),
58
- approvalTimeoutMs: Number(config.approvalTimeoutMs ?? DEFAULT_CONFIG.approvalTimeoutMs),
59
- contextLines: Number(config.contextLines ?? DEFAULT_CONFIG.contextLines),
60
- dataDir,
61
- cwd: resolve(config.cwd !== '' ? config.cwd : join(dataDir, 'workspace')),
62
- statePath: config.statePath !== '' ? resolve(config.statePath) : join(dataDir, 'state.json'),
63
- }
64
- }
65
-
66
- /** Text parts of one assistant message, ignoring reasoning and tool calls. */
67
- function textOf(message) {
68
- const content = message?.content
69
- if (typeof content === 'string') return content
70
- if (!Array.isArray(content)) return ''
71
- const parts = []
72
- for (const part of content) {
73
- if (part === null || typeof part !== 'object') continue
74
- if (part.type === 'text' && typeof part.text === 'string') parts.push(part.text)
75
- }
76
- return parts.join('')
77
- }
78
-
79
- /** One-line, length-bounded preview of a text or JSON blob. */
80
- function preview(value, limit) {
81
- const text = typeof value === 'string' ? value : JSON.stringify(value ?? '')
82
- const flat = text.replace(/\s+/g, ' ').trim()
83
- return flat.length > limit ? `${flat.slice(0, limit)}…` : flat
84
- }
85
-
86
- export function apply(ctx, rawConfig) {
87
- const config = resolveConfig(rawConfig)
88
- const logPath = join(dirname(config.statePath), 'bridge.log')
89
-
90
- const log = (message) => {
91
- console.log(`[dsh-qq-bridge] ${message}`)
92
- void appendFile(logPath, `${new Date().toISOString()} ${message}\n`, 'utf8').catch(() => {})
93
- }
94
-
95
- if (config.enabled === false) {
96
- log('disabled by config')
97
- return
98
- }
99
-
100
- const store = new ConversationStore(config.statePath)
101
- const bridge = new HttpBridge({ host: config.host, port: config.port, token: config.token, log })
102
- /** @type {{ sessionController?: any }} */
103
- const host = {}
104
- /** Live per-session turn capture: sessionId → { texts, tools }. */
105
- const turns = new Map()
106
- /** Recent group chatter per conversation, so a mention carries context. */
107
- const contexts = new Map()
108
- /** Truncated tool arguments per "sessionId:callId", shown in approvals. */
109
- const callArguments = new Map()
110
- /** Pending approval questions: approvalId → finish(outcome). */
111
- const approvals = new Map()
112
- /** Sessions this process already applied the model selection to. */
113
- const selected = new Set()
114
- /** Last time the bot long-polled us; approvals go to QQ only while this is fresh. */
115
- let lastPullAt = 0
116
-
117
- const ready = Promise.all([store.load(), mkdir(config.cwd, { recursive: true }), mkdir(dirname(logPath), { recursive: true })]).catch(error => {
118
- log(`state init failed: ${error instanceof Error ? error.message : String(error)}`)
119
- })
120
-
121
- const stripHints = (line) => {
122
- // the bot appends a sticker hint to the prompt; keep it out of the transcript
123
- const at = line.indexOf('(想发个表情包时')
124
- return at === -1 ? line : line.slice(0, at).trimEnd()
125
- }
126
-
127
- // Longer per-conversation history (with timestamps) the model can search.
128
- const history = new Map()
129
- const stamp = () => {
130
- const now = new Date()
131
- return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
132
- }
133
- const pushHistory = (convKey, line) => {
134
- const list = history.get(convKey) ?? []
135
- list.push(`[${stamp()}] ${stripHints(line)}`)
136
- const cap = Number.isFinite(config.historyMax) ? config.historyMax : 200
137
- if (list.length > cap) list.splice(0, list.length - cap)
138
- history.set(convKey, list)
139
- }
140
-
141
- // One workspace per QQ conversation when auto-grouping is on; falls back to cwd.
142
- const workspaceFor = async (convKey, overrides) => {
143
- const enabled = overrides?.autoGroup === undefined ? config.autoGroup === true : overrides.autoGroup === true
144
- if (!enabled) return config.cwd
145
- const root = String(overrides?.autoGroupRoot || config.autoGroupRoot || 'D:\\dsh-qqbot-temp')
146
- const name = convKey.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'qq'
147
- const dir = join(root, name)
148
- try {
149
- await mkdir(dir, { recursive: true })
150
- return dir
151
- } catch (error) {
152
- log(`workspace mkdir failed (${dir}): ${error instanceof Error ? error.message : String(error)}`)
153
- return config.cwd
154
- }
155
- }
156
-
157
- // 会话搬家:优先调用 dsh-edit-file-workspace 的 /move 路由(保留上下文),
158
- // 失败才退化成"新建会话"(丢上下文)。该路由要求请求来自回环,我们的桥就在本机。
159
- const moveSessionTo = async (sessionId, targetPath) => {
160
- let webServer
161
- try {
162
- webServer = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
163
- } catch (error) {
164
- webServer = undefined
165
- }
166
- const port = webServer && typeof webServer.port === 'number' ? webServer.port : 0
167
- if (port === 0) return { ok: false, reason: 'webServer 不可用' }
168
- try {
169
- const response = await fetch(`http://127.0.0.1:${port}/api/dsh-edit-file-workspace/move`, {
170
- method: 'POST',
171
- headers: { 'content-type': 'application/json' },
172
- body: JSON.stringify({ sessionId, path: targetPath }),
173
- })
174
- const payload = await response.json().catch(() => ({}))
175
- if (response.ok) return { ok: true, sandbox: payload?.sandbox }
176
- return { ok: false, reason: payload?.error || ('HTTP ' + response.status) }
177
- } catch (error) {
178
- return { ok: false, reason: error instanceof Error ? error.message : String(error) }
179
- }
180
- }
181
- // 提问通道:pending 表 + QQ 卡片投递(单题单选;多题/多选下一步)
182
- const questionPending = new Map()
183
- const sessionToConv = new Map()
184
- const askOnQq = async (convKey, id, question, options) => {
185
- const port = Number(config.panelPort) || 39062
186
- const response = await fetch(`http://127.0.0.1:${port}/api/question`, {
187
- method: 'POST',
188
- headers: { 'content-type': 'application/json' },
189
- body: JSON.stringify({ convKey, id, question, options }),
190
- })
191
- if (!response.ok) throw new Error(`bot question endpoint HTTP ${response.status}`)
192
- }
193
-
194
- const installQuestionChannel = () => {
195
- if (typeof ctx.on !== 'function') return () => {}
196
- const sessionToConv = new Map()
197
- const refreshMap = async () => {
198
- try {
199
- const listed = await bridge.listConversations?.()
200
- if (Array.isArray(listed?.conversations)) {
201
- for (const item of listed.conversations) {
202
- const convKey = String(item.convKey ?? item.key ?? "")
203
- const sessionId = store.sessionOf(convKey)
204
- if (sessionId !== undefined) sessionToConv.set(String(sessionId), convKey)
205
- }
206
- }
207
- } catch (error) { /* map stays as-is */ }
208
- }
209
- void refreshMap()
210
- // 官方契约:waterfall answerer 要 { global: true, prepend: true },
211
- // 回调返回 Promise<UserQuestionResult>;不是 QQ 会话就 return next()。
212
- return ctx.on('user-questions/request', (request, next) => {
213
- const agentId = String(request?.agent?.id ?? "")
214
- // store.convOf 是持久化的反查(sessionId → convKey),插件重启也不会丢
215
- const convKey = sessionToConv.get(agentId) ?? store.convOf(agentId)
216
- log(`question request: agent=${agentId} conv=${convKey ?? '-'}`)
217
- const questions = Array.isArray(request?.questions) ? request.questions : []
218
- const first = questions[0]
219
- const options = Array.isArray(first?.options) ? first.options : []
220
- if (convKey === undefined || first === undefined || options.length === 0) return next()
221
- const id = randomUUID()
222
- const labels = options.map((item) => String(item.label ?? item))
223
- return new Promise((resolve, reject) => {
224
- questionPending.set(id, {
225
- resolve: (answer) => {
226
- const index = Number(answer?.index)
227
- const picked = labels[index]
228
- questionPending.delete(id)
229
- resolve({ answers: [{ questionIndex: 0, selected: picked === undefined ? [] : [picked] }] })
230
- },
231
- })
232
- const signal = request?.signal
233
- if (signal !== undefined && typeof signal.addEventListener === "function") {
234
- signal.addEventListener("abort", () => {
235
- questionPending.delete(id)
236
- const error = new Error("ask_user_question was aborted before the user answered")
237
- error.code = "ASK_ABORTED"
238
- reject(error)
239
- })
240
- }
241
- void askOnQq(convKey, id, String(first.question ?? ""), labels).catch((error) => {
242
- questionPending.delete(id)
243
- reject(error instanceof Error ? error : new Error(String(error)))
244
- })
245
- })
246
- }, { global: true, prepend: true })
247
- }
248
- // 提示词形状的文本(机器人自己拼的判断/闲聊提示)不许进历史,否则会被当成群友发言回灌给模型
249
- const looksLikePrompt = (value) => {
250
- const text = String(value ?? '')
251
- return text.includes('【闲聊模式】') || text.includes('【群聊插话判断】')
252
- }
253
-
254
- const remember = (convKey, line) => {
255
- if (looksLikePrompt(line)) return
256
- const list = contexts.get(convKey) ?? []
257
- const stamped = `[${stamp()}] ${stripHints(line)}`
258
- list.push(stamped)
259
- if (list.length > config.contextLines) list.splice(0, list.length - config.contextLines)
260
- contexts.set(convKey, list)
261
- pushHistory(convKey, line)
262
- }
263
-
264
- /** Model-facing preamble: where the message came from and who is speaking. */
265
- const composePrompt = ({ text, convKey, senderName, isOwner, chime, quote }) => {
266
- const isGroup = convKey.startsWith('group:')
267
- const header = isGroup ? 'QQ 群聊' : 'QQ 单聊'
268
- const who = isOwner
269
- ? `${senderName || '主人'}(机器人主人本人:可以远程办公,直接读写工作目录、执行命令、查资料,做完再回答)`
270
- : `${senderName || '群友'}(普通群友:自然聊天为主;要改文件或跑命令时先说明理由,主人批准后才继续)`
271
- const recent = contexts.get(convKey) ?? []
272
- const parts = [`[${header}] ${who}:`]
273
- if (quote !== undefined) {
274
- // Structured by the bot: text / image / file / other, plus the author when known.
275
- const who = quote.author || '一条更早的消息'
276
- const kind = typeof quote.kind === 'string' ? quote.kind : 'text'
277
- if (quote.resolved === true && kind === 'image') {
278
- parts.push(`【引用了${who}发的一张图片】`, '')
279
- } else if (quote.resolved === true && kind === 'file') {
280
- parts.push(`【引用了${who}发的文件:${String(quote.text ?? '') || '(未命名)'}】`, '')
281
- } else if (quote.resolved === true && kind === 'other') {
282
- parts.push(`【引用了${who}发的一条非文本消息】`, '')
283
- } else if (quote.resolved === true) {
284
- const limit = Number.isFinite(config.quoteContextChars) ? config.quoteContextChars : 300
285
- const full = String(quote.text ?? '')
286
- const cut = full.length > limit
287
- const quoted = cut ? `${full.slice(0, limit)}…` : full
288
- parts.push(`【引用了${who}的消息】`, `“${quoted || '(空)'}”`, '')
289
- } else {
290
- const hint = quote.author ? `(可能来自${quote.author})` : ''
291
- parts.push(`【对方引用了一条我这边看不到内容的消息${hint}】`, '')
292
- }
293
- }
294
- parts.push(text)
295
- if (isGroup && recent.length > 0) {
296
- parts.push('', '最近的群聊记录(只作上下文,不必逐条回应):', ...recent)
297
- }
298
- if (chime) {
299
- parts.push('', '这条不是点名问你,是你自己决定要不要插话:觉得没必要就只回 [NO_REPLY]。')
300
- }
301
- parts.push('', isGroup && !isOwner
302
- ? '(这是群聊:像真人一样回 1~3 句口语,别用标题/列表/表格,除非对方明确要步骤。想清楚再说完,不要复述工具过程。)'
303
- : '(先直接回答,别铺垫;默认简短,需要细节时再用 Markdown 展开。)')
304
- parts.push('', '(QQ 侧支持 Markdown 渲染:标题/列表/代码块/表格都能用,表情符号可以直接用。要把本地图片或文件发给对方,先把文件写到工作目录里,再在回复里单独一行写 [[send_file: 绝对路径]],机器人会把它作为文件发出。)')
305
- return parts.join('\n')
306
- }
307
-
308
- /** Ask the bot owner, then translate the answer into an approval outcome. */
309
- const requestDecision = ({ approvalId, convKey, approvalTarget, toolName, reason, argumentPreview, signal }) => new Promise((resolveDecision) => {
310
- const settle = (outcome) => {
311
- clearTimeout(timer)
312
- signal?.removeEventListener?.('abort', onAbort)
313
- approvals.delete(approvalId)
314
- resolveDecision(outcome)
315
- }
316
- const finish = (outcome) => {
317
- if (!approvals.has(approvalId)) return
318
- settle(outcome)
319
- }
320
- const timer = setTimeout(() => {
321
- if (!approvals.has(approvalId)) return
322
- bridge.push({ type: 'notice', convKey, target: approvalTarget, text: `审批超时(${toolName}),已按拒绝处理。` })
323
- log(`approval timeout: ${toolName}`)
324
- settle('rejected')
325
- }, config.approvalTimeoutMs)
326
- const onAbort = () => finish('cancelled')
327
- approvals.set(approvalId, finish)
328
- signal?.addEventListener?.('abort', onAbort, { once: true })
329
- bridge.push({
330
- type: 'approval',
331
- convKey,
332
- target: approvalTarget,
333
- approvalId,
334
- toolName,
335
- reason,
336
- argumentPreview,
337
- expiresAt: Date.now() + config.approvalTimeoutMs,
338
- })
339
- log(`approval asked: ${toolName} (${convKey})`)
340
- })
341
-
342
- /** Ask the Host for its Session list, tolerating builds without a list API. */
343
- const listSessions = async () => {
344
- const controller = host.sessionController
345
- if (controller === undefined) return { source: 'none', sessions: [] }
346
- for (const method of ['list', 'listSessions', 'listAll', 'all', 'sessions', 'query']) {
347
- const fn = controller[method]
348
- if (typeof fn !== 'function') continue
349
- try {
350
- const value = await fn.call(controller, {})
351
- const rows = Array.isArray(value) ? value : (Array.isArray(value?.sessions) ? value.sessions : [])
352
- return {
353
- source: method,
354
- sessions: rows
355
- .map(row => ({
356
- id: String(row?.sessionId ?? row?.id ?? ''),
357
- title: String(row?.title ?? row?.name ?? ''),
358
- cwd: String(row?.cwd ?? ''),
359
- }))
360
- .filter(row => row.id !== ''),
361
- }
362
- } catch (error) {
363
- return { source: method, sessions: [], error: error instanceof Error ? error.message : String(error) }
364
- }
365
- }
366
- return { source: 'unavailable', sessions: [] }
367
- }
368
-
369
- const markPull = () => { lastPullAt = Date.now() }
370
- const botIsListening = () => lastPullAt !== 0 && Date.now() - lastPullAt < 45000
371
- bridge.setOnPull(markPull)
372
-
373
- bridge.setHandlers({
374
- health: () => ({
375
- ok: true,
376
- plugin: 'dsh-qq-bridge',
377
- service: host.sessionController === undefined ? 'waiting' : 'ready',
378
- conversations: store.size(),
379
- pendingApprovals: approvals.size,
380
- }),
381
- status: () => ({
382
- ok: true,
383
- cwd: config.cwd,
384
- statePath: config.statePath,
385
- service: host.sessionController === undefined ? 'waiting' : 'ready',
386
- conversations: store.entries(),
387
- bufferedContexts: [...contexts.entries()].map(([key, lines]) => [key, lines.length]),
388
- pendingApprovals: [...approvals.keys()],
389
- cursor: bridge.cursor,
390
- }),
391
- reset: async (body) => {
392
- const convKey = typeof body?.convKey === 'string' ? body.convKey : ''
393
- if (convKey === '') return { ok: false, error: 'convKey required' }
394
- await store.unbind(convKey)
395
- contexts.delete(convKey)
396
- log(`conversation reset: ${convKey}`)
397
- return { ok: true, convKey }
398
- },
399
- /** Move one QQ conversation onto another existing Session ('' = go back). */
400
- switch: async (body) => {
401
- await ready
402
- const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
403
- const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : ''
404
- if (convKey === '') return { ok: false, error: 'convKey required' }
405
- if (sessionId === '') {
406
- const restored = await store.switchBack(convKey)
407
- if (restored === undefined) return { ok: false, error: '没有可切回的会话' }
408
- contexts.delete(convKey)
409
- log(`switched back: ${convKey} → ${restored}`)
410
- return { ok: true, convKey, sessionId: restored }
411
- }
412
- const previous = store.sessionOf(convKey)
413
- await store.switchTo(convKey, sessionId)
414
- contexts.delete(convKey)
415
- log(`switched: ${convKey} → ${sessionId} (was ${previous ?? 'none'})`)
416
- return { ok: true, convKey, sessionId, previous: previous ?? '' }
417
- },
418
- sessions: async () => {
419
- await ready
420
- return { ok: true, bound: store.entries(), returns: store.returnEntries(), host: await listSessions() }
421
- },
422
- inbound: async (body) => {
423
- await ready
424
- const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
425
- const text = typeof body?.text === 'string' ? body.text : ''
426
- const images = Array.isArray(body?.images) ? body.images : []
427
- if (convKey === '') return { ok: false, error: 'convKey required' }
428
- if (text.trim() === '' && images.length === 0) return { ok: false, error: 'text or images required' }
429
-
430
- const senderName = typeof body?.senderName === 'string' ? body.senderName : ''
431
- // quoted message resolved by the bot (see bot/main.py _resolve_quote)
432
- const quote = body?.quote !== null && typeof body?.quote === 'object' ? body.quote : undefined
433
- const quoteMark = quote !== undefined && quote.resolved === true
434
- ? ` ↩[${quote.author || '引用'}]`
435
- : ''
436
- const label = (text.trim() === '' ? '[图片]' : preview(text, 200)) + quoteMark
437
-
438
- // Background group chatter: keep it as context, never start a turn for it.
439
- if (body?.contextOnly === true) {
440
- if (!looksLikePrompt(text)) remember(convKey, `${senderName || '群友'}: ${label}`)
441
- return { ok: true, buffered: true }
442
- }
443
-
444
- const sessionController = host.sessionController
445
- if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
446
-
447
- let sessionId = store.sessionOf(convKey)
448
- if (sessionId === undefined) {
449
- const created = await sessionController.create({ cwd: await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot }) })
450
- sessionId = String(created.sessionId)
451
- log(`session created: ${convKey} → ${sessionId}`)
452
- }
453
- await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
454
- sessionToConv.set(String(sessionId), convKey)
455
-
456
- // Casual chat is latency-bound: pin the session to the configured model /
457
- // reasoning effort once, without losing the Session's history.
458
- if (!selected.has(sessionId) && config.modelProvider !== '' && config.model !== '') {
459
- try {
460
- await sessionController.selectModel({
461
- sessionId,
462
- provider: config.modelProvider,
463
- model: config.model,
464
- ...(config.reasoningEffort !== '' ? { reasoningEffort: config.reasoningEffort } : {}),
465
- })
466
- log(`model pinned for ${sessionId}: ${config.modelProvider}/${config.model} effort=${config.reasoningEffort || 'default'}`)
467
- } catch (error) {
468
- log(`selectModel failed for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`)
469
- }
470
- selected.add(sessionId)
471
- }
472
-
473
- const content = [{ type: 'text', text: composePrompt({ text, convKey, senderName, isOwner: body?.isOwner === true, chime: body?.chime === true, quote }) }]
474
- for (const image of images.slice(0, 4)) {
475
- const mediaType = typeof image?.mediaType === 'string' ? image.mediaType : ''
476
- const data = typeof image?.data === 'string' ? image.data : ''
477
- if (!IMAGE_TYPES.has(mediaType) || data === '') continue
478
- content.push({ type: 'image', mediaType, data })
479
- }
480
-
481
- const controller = new AbortController()
482
- const timer = setTimeout(() => controller.abort(), 120000)
483
- try {
484
- await sessionController.prompt({
485
- requestId: randomUUID(),
486
- sessionId,
487
- mode: 'queue',
488
- content,
489
- clientTimeZone: 'Asia/Shanghai',
490
- }, controller.signal)
491
- } finally {
492
- clearTimeout(timer)
493
- }
494
- if (!looksLikePrompt(text)) remember(convKey, `${senderName || '群友'}: ${label}`)
495
- return { ok: true, sessionId, accepted: true }
496
- },
497
- rebind: async (body) => {
498
- await ready
499
- const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
500
- if (convKey === '') return { ok: false, error: 'convKey required' }
501
- const sessionController = host.sessionController
502
- if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
503
- const dir = await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot })
504
- const existing = store.sessionOf(convKey)
505
- let fallbackReason = ""
506
- if (existing !== undefined) {
507
- const moved = await moveSessionTo(existing, dir)
508
- if (moved.ok) return { ok: true, sessionId: existing, cwd: dir, moved: true, sandbox: moved.sandbox }
509
- fallbackReason = String(moved.reason || 'move failed')
510
- log(`session move failed (${convKey}): ${fallbackReason}; falling back to a new session`)
511
- }
512
- try {
513
- const created = await sessionController.create({ cwd: dir })
514
- const sessionId = String(created.sessionId)
515
- await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
516
- sessionToConv.set(String(sessionId), convKey)
517
- return { ok: true, sessionId, cwd: dir, moved: false, fallbackReason, previous: body?.previous || null }
518
- } catch (error) {
519
- return { ok: false, error: 'create failed: ' + (error instanceof Error ? error.message : String(error)) }
520
- }
521
- },
522
-
523
- answer: async (body) => {
524
- await ready
525
- const id = typeof body?.id === 'string' ? body.id : ''
526
- if (id === '') return { ok: false, error: 'id required' }
527
- const pending = questionPending.get(id)
528
- if (pending === undefined) return { ok: false, error: 'this question is no longer pending' }
529
- questionPending.delete(id)
530
- try { pending.resolve(body) } catch (error) { /* already settled */ }
531
- return { ok: true }
532
- },
533
- commands: async (body) => {
534
- await ready
535
- const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
536
- const ctxOf = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
537
- const agents = ctxOf('agents')
538
- const runtime = ctxOf('commands')
539
- if (agents === undefined || runtime === undefined) return { ok: false, error: 'agents/commands 服务不可用' }
540
- const sessionId = store.sessionOf(convKey)
541
- if (sessionId === undefined) return { ok: false, error: '这个会话还没有 DSH 会话' }
542
- const agent = typeof agents.get === 'function' ? agents.get(sessionId) : undefined
543
- if (agent === undefined) return { ok: false, error: '会话未加载(先聊一句)' }
544
- let list = []
545
- try {
546
- list = runtime.list(agent).map((item) => ({
547
- name: item.name,
548
- description: item.description || item.summary || '',
549
- source: item.source || '',
550
- }))
551
- } catch (error) {
552
- return { ok: false, error: 'list failed: ' + (error instanceof Error ? error.message : String(error)) }
553
- }
554
- return { ok: true, count: list.length, commands: list }
555
- },
556
-
557
- command: async (body) => {
558
- await ready
559
- const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
560
- const line = typeof body?.line === 'string' ? body.line.trim() : ''
561
- if (line === '') return { ok: false, error: 'line required' }
562
- const ctxOf = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
563
- const agents = ctxOf('agents')
564
- const runtime = ctxOf('commands')
565
- if (agents === undefined || runtime === undefined) return { ok: false, error: 'agents/commands 服务不可用' }
566
- const sessionId = store.sessionOf(convKey)
567
- if (sessionId === undefined) return { ok: false, error: '这个会话还没有 DSH 会话' }
568
- const agent = typeof agents.get === 'function' ? agents.get(sessionId) : undefined
569
- if (agent === undefined) return { ok: false, error: '会话未加载(先聊一句)' }
570
- try {
571
- const result = await runtime.execute(agent, line, [], new AbortController().signal)
572
- return { ok: true, handled: result !== undefined, line }
573
- } catch (error) {
574
- return { ok: false, error: 'execute failed: ' + (error instanceof Error ? error.message : String(error)) }
575
- }
576
- },
577
- permission: async (body) => {
578
- await ready
579
- const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
580
- const preset = typeof body?.preset === 'string' ? body.preset.trim() : ''
581
- let service = host.permissionPresets
582
- if (service === undefined && typeof ctx.get === 'function') service = ctx.get('permissionPresets')
583
- const names = service && Array.isArray(service.names) ? service.names.slice() : []
584
- // 该会话"当下生效"的权限值(会话投影),读不到就退回默认值
585
- const liveCurrent = () => {
586
- try {
587
- const sid = store.sessionOf(convKey)
588
- if (sid === undefined) return ''
589
- const pick = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
590
- const sessions = pick('sessions')
591
- let session = sessions && typeof sessions.get === 'function' ? sessions.get(sid) : undefined
592
- if (session === undefined) {
593
- const agents = pick('agents')
594
- session = agents && typeof agents.get === 'function' ? agents.get(sid) : undefined
595
- }
596
- if (session !== undefined && service && typeof service.current === 'function') return service.current(session)
597
- } catch (error) {
598
- return ''
599
- }
600
- return ''
601
- }
602
- if (preset === '') {
603
- return {
604
- ok: names.length > 0,
605
- names,
606
- current: liveCurrent() || (service && typeof service.defaultPreset === 'string' ? service.defaultPreset : ''),
607
- note: names.length > 0 ? '' : 'permissionPresets 服务不可用(这条 DSH 没启用权限预设)',
608
- }
609
- }
610
- if (names.length > 0 && !names.includes(preset)) {
611
- return { ok: false, error: 'unknown preset: ' + preset, names }
612
- }
613
- const sessionController = host.sessionController
614
- let sessionId = store.sessionOf(convKey)
615
- if (sessionController === undefined && sessionId === undefined) {
616
- return { ok: false, error: 'sessionController unavailable' }
617
- }
618
- if (sessionId === undefined) {
619
- // 还没聊过:先给这个 QQ 会话建 DSH 会话(自动工作区开启时自带独立目录),
620
- // 否则 /pr 没法把命令投递进去。
621
- try {
622
- const created = await sessionController.create({
623
- cwd: await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot }),
624
- })
625
- sessionId = String(created.sessionId)
626
- await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
627
- sessionToConv.set(String(sessionId), convKey)
628
- } catch (error) {
629
- return { ok: false, error: 'create session failed: ' + (error instanceof Error ? error.message : String(error)) }
630
- }
631
- }
632
- // 官方写入口:permissionPresets.set(session, name)(/permission 命令内部走的就是它)。
633
- // 之前用 sessionController.prompt 发文本,斜杠命令不会被解释,只会变成一条用户消息。
634
- let sessions = undefined
635
- try { sessions = typeof ctx.get === 'function' ? ctx.get('sessions') : undefined } catch (error) { sessions = undefined }
636
- const session = sessions && typeof sessions.get === 'function' ? sessions.get(sessionId) : undefined
637
- if (session === undefined) return { ok: false, error: '会话还没加载,先聊一句再试' }
638
- if (service === undefined || typeof service.set !== 'function') {
639
- return { ok: false, error: 'permissionPresets 服务不可用' }
640
- }
641
- try {
642
- service.set(session, preset)
643
- } catch (error) {
644
- return { ok: false, error: 'set failed: ' + (error instanceof Error ? error.message : String(error)) }
645
- }
646
- let landed = ''
647
- try { landed = typeof service.current === 'function' ? service.current(session) : '' } catch (error) { landed = '' }
648
- return { ok: true, switched: preset, current: landed, names }
649
- },
650
-
651
- judge: async (body) => {
652
- await ready
653
- const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
654
- const transcript = typeof body?.transcript === 'string' ? body.transcript.trim() : ''
655
- if (convKey === '' || transcript === '') return { ok: false, error: 'convKey/transcript required' }
656
- const sessionController = host.sessionController
657
- if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
658
-
659
- let sessionId = judgeSessions.get(convKey)
660
- try {
661
- if (sessionId === undefined) {
662
- const created = await sessionController.create({ cwd: config.cwd })
663
- sessionId = String(created.sessionId)
664
- judgeSessions.set(convKey, sessionId)
665
- log(`judge session for ${convKey}: ${sessionId}`)
666
- }
667
- } catch (error) {
668
- return { ok: false, error: `judge session failed: ${error instanceof Error ? error.message : String(error)}` }
669
- }
670
-
671
- judgeTexts.set(sessionId, [])
672
- const verdict = new Promise(resolve => {
673
- judgeWaiters.set(sessionId, resolve)
674
- setTimeout(() => {
675
- if (judgeWaiters.get(sessionId) === resolve) {
676
- judgeWaiters.delete(sessionId)
677
- resolve('')
678
- }
679
- }, 90000)
680
- })
681
-
682
- const instruction = [
683
- '【群聊插话判断器】你是一个独立判断器,不参与聊天,只做判断。',
684
- '下面是这个群里最近的消息原文(每行 发言人: 内容):',
685
- transcript,
686
- '',
687
- '判断现在是否需要一个机器人插话/回答。只输出两行:',
688
- '第一行:REPLY 或 SKIP',
689
- '第二行:一句话理由(不超过40字)',
690
- ].join('\n')
691
-
692
- try {
693
- await sessionController.prompt({
694
- requestId: randomUUID(),
695
- sessionId,
696
- mode: 'queue',
697
- content: [{ type: 'text', text: instruction }],
698
- clientTimeZone: 'Asia/Shanghai',
699
- }, new AbortController().signal)
700
- } catch (error) {
701
- judgeWaiters.delete(sessionId)
702
- return { ok: false, error: `judge prompt failed: ${error instanceof Error ? error.message : String(error)}` }
703
- }
704
-
705
- const answer = String(await verdict)
706
- const lines = answer.split('\n').map(line => line.trim()).filter(line => line !== '')
707
- const head = (lines[0] ?? '').toUpperCase()
708
- const needReply = head.startsWith('REPLY')
709
- const decisive = head.startsWith('REPLY') || head.startsWith('SKIP')
710
- return {
711
- ok: decisive,
712
- needReply,
713
- note: lines.slice(1).join(' ').slice(0, 200),
714
- raw: answer.slice(0, 200),
715
- }
716
- },
717
- approval: async (body) => {
718
- const approvalId = typeof body?.approvalId === 'string' ? body.approvalId : ''
719
- const decision = body?.decision === 'allow' ? 'allowed-once' : body?.decision === 'cancel' ? 'cancelled' : 'rejected'
720
- const finish = approvals.get(approvalId)
721
- if (finish === undefined) return { ok: false, error: 'unknown or expired approval' }
722
- finish(decision)
723
- log(`approval ${approvalId} → ${decision}`)
724
- return { ok: true, approvalId, decision }
725
- },
726
- })
727
-
728
- // Keep the QQ bot alive across DSH restarts: DSH owns its own lifecycle, so
729
- // the host half re-spawns the supervised bot whenever the panel is missing.
730
- const ensureBot = async () => {
731
- if (config.autoStartBot !== true) return
732
- try {
733
- const response = await fetch(`http://127.0.0.1:${config.panelPort ?? 39062}/health`, { signal: AbortSignal.timeout(1500) })
734
- if (response.ok) return
735
- } catch {
736
- // panel unreachable -> the supervisor is gone, start it
737
- }
738
- try {
739
- const { spawn } = await import('node:child_process')
740
- const child = spawn(config.pythonPath, ['-u', 'main.py', '--supervise'], {
741
- cwd: config.botDir,
742
- detached: true,
743
- stdio: 'ignore',
744
- windowsHide: true,
745
- })
746
- child.unref()
747
- log(`bot supervisor spawned (pid ${child.pid})`)
748
- } catch (error) {
749
- log(`bot autostart failed: ${error instanceof Error ? error.message : String(error)}`)
750
- }
751
- }
752
- ctx.effect(() => {
753
- const first = setTimeout(() => { void ensureBot() }, 8000)
754
- const ticker = setInterval(() => { void ensureBot() }, 60000)
755
- return () => { clearTimeout(first); clearInterval(ticker) }
756
- }, 'dsh-qq-bridge: keep the bot process alive')
757
-
758
- // Serve the loopback port for as long as this plugin entry stays loaded.
759
- ctx.effect(() => {
760
- // 提问通道默认关闭:DSH 的 user-questions/request 是瀑布事件,
761
- // 处理不当会让宿主 abort 并崩溃(crash-…-host.log)。稳定性验证通过后再打开。
762
- if (config.questionChannel === false) return () => {}
763
- const dispose = installQuestionChannel()
764
- return () => { try { dispose() } catch (error) { /* already gone */ } }
765
- }, 'dsh-qq-bridge: question channel')
766
-
767
- ctx.effect(() => {
768
- void bridge.start()
769
- .then(() => log(`listening on http://${config.host}:${bridge.port} (cwd: ${config.cwd})`))
770
- .catch(error => log(`listen failed: ${error instanceof Error ? error.message : String(error)}`))
771
- return () => { void bridge.stop() }
772
- }, 'dsh-qq-bridge: local http bridge')
773
-
774
- // Live token stream: the official plugin listens to the transient
775
- // 'agent/assistant-stream' event and reads frame.chunk.text, so do the same
776
- // instead of sessionController.follow() (which only yields step snapshots).
777
- const streams = new Map() // sessionId -> convKey
778
- const agentSessions = new Map() // agentId -> sessionId
779
-
780
- const startStream = (sessionId, convKey) => {
781
- if (config.streamEnabled !== true) return
782
- streams.set(sessionId, convKey)
783
- }
784
-
785
- const stopStream = (sessionId) => {
786
- streams.delete(sessionId)
787
- for (const [agentId, mapped] of agentSessions) {
788
- if (mapped === sessionId) agentSessions.delete(agentId)
789
- }
790
- }
791
-
792
- ctx.on('agent/assistant-stream', (payload) => {
793
- if (config.streamEnabled !== true || streams.size === 0) return
794
- const agentId = payload?.agent?.id
795
- const frame = payload?.frame
796
- if (typeof agentId !== 'string' || agentId === '' || frame == null) return
797
-
798
- let sessionId = agentSessions.get(agentId)
799
- if (sessionId === undefined) {
800
- const newest = [...streams.keys()].pop()
801
- if (newest === undefined) return
802
- agentSessions.set(agentId, newest)
803
- sessionId = newest
804
- }
805
- const convKey = streams.get(sessionId)
806
- if (convKey === undefined) return
807
- if (frame.type !== 'chunk') return
808
- const chunk = frame.chunk
809
- if (chunk?.type !== 'text-delta' || typeof chunk.text !== 'string' || chunk.text === '') return
810
- bridge.push({
811
- type: 'stream',
812
- convKey,
813
- turnId: turns.get(sessionId)?.turnId ?? '',
814
- text: chunk.text,
815
- final: false,
816
- })
817
- })
818
-
819
- // Independent judge sessions (Plan B): one per conversation, no shared history.
820
- const judgeTexts = new Map() // sessionId -> collected assistant text
821
- const judgeWaiters = new Map() // sessionId -> resolve(text)
822
- const judgeSessions = new Map() // convKey -> sessionId
823
-
824
- // Capture each finished turn so the bot can answer the QQ message.
825
- ctx.on('session/event', (session, event) => {
826
- const sessionId = String(session?.id ?? '')
827
- if (sessionId === '') return
828
- const convKey = store.convOf(sessionId)
829
- if (convKey === undefined) return
830
- const data = event?.data ?? {}
831
- if (judgeTexts.has(sessionId)) {
832
- if (event.type === 'assistant/message') {
833
- const t = textOf(data.message)
834
- if (t.trim() !== '') judgeTexts.get(sessionId).push(t)
835
- }
836
- if (event.type === 'turn/end') {
837
- const done = judgeWaiters.get(sessionId)
838
- if (done !== undefined) {
839
- judgeWaiters.delete(sessionId)
840
- done(judgeTexts.get(sessionId).join('\n').trim())
841
- }
842
- }
843
- return
844
- }
845
- if (event.type === 'turn/start') {
846
- turns.set(sessionId, { texts: [], tools: [], turnId: `${Date.now().toString(36)}-${sessionId.slice(-6)}` })
847
- startStream(sessionId, convKey)
848
- return
849
- }
850
- if (event.type === 'assistant/message') {
851
- const state = turns.get(sessionId)
852
- if (state === undefined) return
853
- const text = textOf(data.message)
854
- if (text.trim() !== '') state.texts.push(text)
855
- return
856
- }
857
- if (event.type === 'tool/call') {
858
- const state = turns.get(sessionId)
859
- if (state === undefined) return
860
- if (typeof data.name === 'string') state.tools.push(data.name)
861
- if (typeof data.callId === 'string') {
862
- callArguments.set(`${sessionId}:${data.callId}`, preview(data.arguments, config.argumentPreviewChars))
863
- if (callArguments.size > 200) callArguments.delete(callArguments.keys().next().value)
864
- }
865
- return
866
- }
867
- if (event.type === 'turn/end') {
868
- const state = turns.get(sessionId) ?? { texts: [], tools: [] }
869
- turns.delete(sessionId)
870
- stopStream(sessionId)
871
- bridge.push({ type: 'stream', convKey, turnId: state.turnId ?? '', text: state.texts.join('\n\n').trim(), final: true })
872
- // data.reason is an object on this host generation; never ship "[object Object]"
873
- const rawReason = data.reason
874
- const reason = typeof rawReason === 'string'
875
- ? rawReason
876
- : (rawReason && typeof rawReason === 'object' ? String(rawReason.kind ?? rawReason.type ?? '') : '')
877
- bridge.push({
878
- type: 'reply',
879
- convKey,
880
- turnId: state.turnId ?? '',
881
- text: state.texts.join('\n\n').trim(),
882
- tools: state.tools,
883
- reason,
884
- })
885
- }
886
- })
887
-
888
- // Route approvals of bridged Sessions to their owner FIRST: the Web GUI also
889
- // answers approvals, and only a prepended listener wins that waterfall.
890
- // Sessions this plugin does not own fall through with next().
891
- ctx.on('approval/request', async (request, next) => {
892
- const sessionId = String(request?.agent?.session?.id ?? '')
893
- const convKey = sessionId === '' ? undefined : store.convOf(sessionId)
894
- if (convKey === undefined) return next()
895
- if (!botIsListening()) {
896
- // Nobody is polling the bridge: never swallow the approval, let the GUI ask.
897
- log(`approval for ${convKey} handed to the GUI (bot not polling)`)
898
- return next()
899
- }
900
- const approvalTarget = store.approvalTargetOf(convKey) ?? convKey
901
- const callId = typeof request?.callId === 'string' ? request.callId : ''
902
- try {
903
- return await requestDecision({
904
- approvalId: randomUUID(),
905
- convKey,
906
- approvalTarget,
907
- toolName: String(request?.toolName ?? 'unknown'),
908
- reason: String(request?.reason ?? ''),
909
- argumentPreview: callId === '' ? '' : (callArguments.get(`${sessionId}:${callId}`) ?? ''),
910
- signal: request?.signal,
911
- })
912
- } catch (error) {
913
- log(`approval relay failed: ${error instanceof Error ? error.message : String(error)}`)
914
- return 'rejected'
915
- }
916
- }, { prepend: true })
917
-
918
- // The Session service may arrive after this entry; wait for it instead of
919
- // failing the whole profile boot when it is absent.
920
- // Model-facing retrieval over the timestamped history buffer.
921
- ctx.inject(['tools'], (scope) => {
922
- const tools = scope.tools ?? (typeof scope.get === 'function' ? scope.get('tools') : undefined)
923
- if (tools === undefined || typeof tools.register !== 'function') {
924
- log('qq_history tool unavailable (tools service missing)')
925
- return
926
- }
927
- const definition = {
928
- name: 'qq_history',
929
- description:
930
- '搜索 QQ 群聊/私聊最近的历史消息(每行带 [HH:MM] 时间戳)。' +
931
- '当对方提到你没见过的内容、或需要确认「谁在什么时候说过什么」时调用。',
932
- parameters: {
933
- type: 'object',
934
- additionalProperties: false,
935
- properties: {
936
- convKey: { type: 'string', description: '会话键,如 group:XXXX 或 c2c:XXXX;留空表示所有会话' },
937
- query: { type: 'string', description: '关键词,留空返回最近若干条' },
938
- limit: { type: 'number', description: '返回条数上限,默认 30,最大 100' },
939
- },
940
- },
941
- output: {
942
- schema: { type: 'object' },
943
- render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
944
- },
945
- async execute(args) {
946
- const limit = Math.max(1, Math.min(Number(args?.limit ?? 30) || 30, 100))
947
- const needle = typeof args?.query === 'string' ? args.query.trim() : ''
948
- const convFilter = typeof args?.convKey === 'string' ? args.convKey.trim() : ''
949
- const keys = convFilter !== '' ? [convFilter] : [...history.keys()]
950
- const lines = []
951
- for (const key of keys) {
952
- for (const line of history.get(key) ?? []) {
953
- if (needle === '' || line.includes(needle)) lines.push(`${key} ${line}`)
954
- }
955
- }
956
- return { ok: true, count: lines.slice(-limit).length, lines: lines.slice(-limit) }
957
- },
958
- }
959
- try {
960
- tools.register(definition)
961
- log('qq_history tool registered')
962
- } catch (error) {
963
- log(`qq_history registration failed: ${error instanceof Error ? error.message : String(error)}`)
964
- }
965
-
966
- // ── 群管理工具(禁言 / 踢人 / 成员索引) ──
967
- const adminCall = async (payload) => {
968
- const port = Number(config.panelPort) || 39062
969
- const response = await fetch(`http://127.0.0.1:${port}/api/admin`, {
970
- method: 'POST',
971
- headers: { 'content-type': 'application/json' },
972
- body: JSON.stringify(payload),
973
- })
974
- return await response.json().catch(() => ({}))
975
- }
976
-
977
- const readMembers = () => {
978
- try {
979
- const file = join(String(config.botDir || "."), "state", "members.json")
980
- const raw = readFileSync(file, "utf8")
981
- return JSON.parse(raw)
982
- } catch (error) {
983
- return {}
984
- }
985
- }
986
-
987
- const resolveMember = (convKey, member) => {
988
- const known = readMembers()[convKey] || {}
989
- const raw = String(member || "").trim().replace(/^@/, "").replace(/^群友/i, "").toUpperCase()
990
- if (raw === "") return undefined
991
- for (const [tail, info] of Object.entries(known)) {
992
- if (tail.toUpperCase() === raw) return info?.openid ?? info
993
- }
994
- for (const [tail, info] of Object.entries(known)) {
995
- if (raw.length >= 4 && tail.toUpperCase().includes(raw)) return info?.openid ?? info
996
- }
997
- if (/^[0-9A-F]{32}$/.test(raw)) return raw
998
- return undefined
999
- }
1000
-
1001
- const adminTools = [
1002
- {
1003
- name: "qq_members",
1004
- description: "列出本群/本会话里发过言的成员(短号 → openid)。禁言/踢人前先查这个拿短号。",
1005
- parameters: { type: "object", additionalProperties: false, properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } } },
1006
- async execute(args) {
1007
- const convKey = String(args?.convKey || "")
1008
- const all = readMembers()
1009
- const people = convKey !== "" ? { [convKey]: all[convKey] || {} } : all
1010
- const lines = []
1011
- for (const [key, members] of Object.entries(people)) {
1012
- for (const [tail, info] of Object.entries(members || {})) lines.push({ convKey: key, tail, openid: info?.openid ?? info })
1013
- }
1014
- return { ok: true, count: lines.length, members: lines }
1015
- },
1016
- },
1017
- {
1018
- name: "qq_mute",
1019
- description: "禁言群里某个成员(需要机器人是群管理员且有接口权限)。member 可以是短号(如 1B6CBB)或 @群友XXXX。",
1020
- parameters: {
1021
- type: "object", additionalProperties: false,
1022
- required: ["convKey", "member", "minutes"],
1023
- properties: {
1024
- convKey: { type: "string", description: "会话键,如 group:XXXX" },
1025
- member: { type: "string", description: "被禁言的成员:短号或 @群友XXXX" },
1026
- minutes: { type: "number", description: "禁言分钟数(720=12 小时);传 0 表示解除禁言" },
1027
- },
1028
- },
1029
- async execute(args) {
1030
- const convKey = String(args?.convKey || "")
1031
- const openid = resolveMember(convKey, args?.member)
1032
- if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1033
- const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1034
- // minutes <= 0 表示解除禁言(op=del);注意不能用 `|| 10`,否则 0 会被吞成 10
1035
- const raw = Number(args?.minutes)
1036
- const minutes = Number.isFinite(raw) ? raw : 10
1037
- const seconds = minutes <= 0 ? 0 : Math.min(Math.round(minutes * 60), 60 * 60 * 24 * 30)
1038
- const result = await adminCall({ action: "mute", group, member: openid, seconds })
1039
- return {
1040
- ok: result.ok === true,
1041
- member: args?.member,
1042
- op: seconds > 0 ? "add" : "del",
1043
- minutes: seconds / 60,
1044
- error: result.error,
1045
- }
1046
- },
1047
- },
1048
- {
1049
- name: "qq_unmute",
1050
- description: "解除某个成员的禁言(等价 op=del)。语义独立,避免把 0 分钟误当禁言时长。",
1051
- parameters: {
1052
- type: "object", additionalProperties: false,
1053
- required: ["convKey", "member"],
1054
- properties: {
1055
- convKey: { type: "string", description: "会话键,如 group:XXXX" },
1056
- member: { type: "string", description: "成员:短号或 @群友XXXX" },
1057
- },
1058
- },
1059
- async execute(args) {
1060
- const convKey = String(args?.convKey || "")
1061
- const openid = resolveMember(convKey, args?.member)
1062
- if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1063
- const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1064
- const result = await adminCall({ action: "mute", group, member: openid, seconds: 0 })
1065
- return { ok: result.ok === true, member: args?.member, op: "del", error: result.error }
1066
- },
1067
- },
1068
- {
1069
- name: "qq_mute_state",
1070
- description: "查询本群当前的禁言设置(平台原样返回),用于确认禁言/解禁是否真的生效。",
1071
- parameters: {
1072
- type: "object", additionalProperties: false,
1073
- required: ["convKey"],
1074
- properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } },
1075
- },
1076
- async execute(args) {
1077
- const convKey = String(args?.convKey || "")
1078
- const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1079
- const result = await adminCall({ action: "mute_state", group })
1080
- return { ok: result.ok === true, state: result.state, error: result.error }
1081
- },
1082
- },
1083
- {
1084
- name: "qq_kick",
1085
- description: "把某个成员移出群(需要机器人是群管理员且有接口权限)。member 可以是短号或 @群友XXXX。",
1086
- parameters: {
1087
- type: "object", additionalProperties: false,
1088
- required: ["convKey", "member"],
1089
- properties: {
1090
- convKey: { type: "string", description: "会话键,如 group:XXXX" },
1091
- member: { type: "string", description: "被移出的成员:短号或 @群友XXXX" },
1092
- blacklist: { type: "boolean", description: "是否同时拉黑,默认否" },
1093
- },
1094
- },
1095
- async execute(args) {
1096
- const convKey = String(args?.convKey || "")
1097
- const openid = resolveMember(convKey, args?.member)
1098
- if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1099
- const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1100
- const result = await adminCall({ action: "kick", group, member: openid, blacklist: args?.blacklist === true })
1101
- return { ok: result.ok === true, member: args?.member, error: result.error }
1102
- },
1103
- },
1104
- ]
1105
-
1106
- for (const tool of adminTools) {
1107
- try {
1108
- tools.register({ ...tool, output: { schema: { type: "object" }, render: (_a, value) => [{ type: "text", text: JSON.stringify(value) }] } })
1109
- log(`${tool.name} tool registered`)
1110
- } catch (error) {
1111
- log(`${tool.name} registration failed: ${error instanceof Error ? error.message : String(error)}`)
1112
- }
1113
- }
1114
- })
1115
-
1116
- ctx.inject(['sessionController'], (sctx) => {
1117
- host.sessionController = sctx.sessionController
1118
- log('sessionController attached')
1119
- })
1120
- }
1
+ /**
2
+ * dsh-qq-bridge — Host half.
3
+ *
4
+ * One QQ conversation (a group or a private chat) owns one DSH Session. This
5
+ * plugin keeps that mapping, turns every inbound QQ message into a Session
6
+ * prompt, captures the assistant text of each finished turn, keeps a rolling
7
+ * transcript of group chatter, and asks the bot owner before a tool needs
8
+ * approval.
9
+ */
10
+ import { randomUUID } from 'node:crypto'
11
+ import { readFileSync } from 'node:fs'
12
+ import { appendFile, mkdir } from 'node:fs/promises'
13
+ import { dirname, join, resolve } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+ import { Installer, readInstall, resolveSourceDir } from './install.js'
16
+ import { HttpBridge } from './server.js'
17
+ import { ConversationStore } from './store.js'
18
+
19
+ export const name = 'dsh-qq-bridge'
20
+
21
+ /** Fields a profile patch may override; everything else is fixed policy. */
22
+ export const DEFAULT_CONFIG = {
23
+ enabled: true,
24
+ host: '127.0.0.1',
25
+ port: 39061,
26
+ panelPort: 39062,
27
+ token: '',
28
+ cwd: '',
29
+ statePath: '',
30
+ approvalTimeoutMs: 150000,
31
+ approvalDefault: 'reject',
32
+ contextLines: 30,
33
+ argumentPreviewChars: 600,
34
+ quoteContextChars: 300,
35
+ historyMax: 200,
36
+ autoGroup: true,
37
+ autoGroupRoot: 'D:\\dsh-qqbot-temp',
38
+ streamEnabled: true,
39
+ streamIntervalMs: 250,
40
+ autoStartBot: true,
41
+ botDir: 'D:/Program/QQ-Bot-Class/dsh-bot/bot',
42
+ pythonPath: 'C:/Users/25639/.conda/envs/ChatClone-BotPy/python.exe',
43
+ modelProvider: '',
44
+ model: '',
45
+ reasoningEffort: '',
46
+ }
47
+
48
+ const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
49
+
50
+ /** Profile config → absolute, defaulted runtime configuration. */
51
+ function resolveConfig(raw) {
52
+ const config = { ...DEFAULT_CONFIG, ...(raw ?? {}) }
53
+ const home = typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME !== ''
54
+ ? process.env.DSH_HOME
55
+ : join(process.cwd(), '.dsh')
56
+ const dataDir = join(home, 'qq-bridge')
57
+ return {
58
+ ...config,
59
+ port: Number(config.port ?? DEFAULT_CONFIG.port),
60
+ approvalTimeoutMs: Number(config.approvalTimeoutMs ?? DEFAULT_CONFIG.approvalTimeoutMs),
61
+ contextLines: Number(config.contextLines ?? DEFAULT_CONFIG.contextLines),
62
+ dataDir,
63
+ cwd: resolve(config.cwd !== '' ? config.cwd : join(dataDir, 'workspace')),
64
+ statePath: config.statePath !== '' ? resolve(config.statePath) : join(dataDir, 'state.json'),
65
+ }
66
+ }
67
+
68
+ /** Text parts of one assistant message, ignoring reasoning and tool calls. */
69
+ function textOf(message) {
70
+ const content = message?.content
71
+ if (typeof content === 'string') return content
72
+ if (!Array.isArray(content)) return ''
73
+ const parts = []
74
+ for (const part of content) {
75
+ if (part === null || typeof part !== 'object') continue
76
+ if (part.type === 'text' && typeof part.text === 'string') parts.push(part.text)
77
+ }
78
+ return parts.join('')
79
+ }
80
+
81
+ /** One-line, length-bounded preview of a text or JSON blob. */
82
+ function preview(value, limit) {
83
+ const text = typeof value === 'string' ? value : JSON.stringify(value ?? '')
84
+ const flat = text.replace(/\s+/g, ' ').trim()
85
+ return flat.length > limit ? `${flat.slice(0, limit)}…` : flat
86
+ }
87
+
88
+ export function apply(ctx, rawConfig) {
89
+ const config = resolveConfig(rawConfig)
90
+ const logPath = join(dirname(config.statePath), 'bridge.log')
91
+
92
+ const log = (message) => {
93
+ console.log(`[dsh-qq-bridge] ${message}`)
94
+ void appendFile(logPath, `${new Date().toISOString()} ${message}\n`, 'utf8').catch(() => {})
95
+ }
96
+
97
+ if (config.enabled === false) {
98
+ log('disabled by config')
99
+ return
100
+ }
101
+
102
+ const store = new ConversationStore(config.statePath)
103
+ const bridge = new HttpBridge({ host: config.host, port: config.port, token: config.token, log })
104
+ /** @type {{ sessionController?: any }} */
105
+ const host = {}
106
+ /** Live per-session turn capture: sessionId → { texts, tools }. */
107
+ const turns = new Map()
108
+ /** Recent group chatter per conversation, so a mention carries context. */
109
+ const contexts = new Map()
110
+ /** Truncated tool arguments per "sessionId:callId", shown in approvals. */
111
+ const callArguments = new Map()
112
+ /** Pending approval questions: approvalId → finish(outcome). */
113
+ const approvals = new Map()
114
+ /** Sessions this process already applied the model selection to. */
115
+ const selected = new Set()
116
+ /** Last time the bot long-polled us; approvals go to QQ only while this is fresh. */
117
+ let lastPullAt = 0
118
+
119
+ const ready = Promise.all([store.load(), mkdir(config.cwd, { recursive: true }), mkdir(dirname(logPath), { recursive: true })]).catch(error => {
120
+ log(`state init failed: ${error instanceof Error ? error.message : String(error)}`)
121
+ })
122
+
123
+ // 一键装机器人环境:找 Python → 建 venv → 装依赖 → 复制随包代码 → 写配置 → 拉起
124
+ const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
125
+ const installer = new Installer({
126
+ dataDir: config.dataDir,
127
+ sourceDir: join(pluginRoot, 'bot'),
128
+ log,
129
+ launch: async (pythonPath, botDir) => {
130
+ const { spawn } = await import('node:child_process')
131
+ const child = spawn(pythonPath, ['-u', 'main.py', '--supervise'], {
132
+ cwd: botDir,
133
+ detached: true,
134
+ stdio: 'ignore',
135
+ windowsHide: true,
136
+ })
137
+ child.unref()
138
+ log(`bot supervisor spawned after install (pid ${child.pid})`)
139
+ return child.pid
140
+ },
141
+ })
142
+ void installer.load()
143
+
144
+ const stripHints = (line) => {
145
+ // the bot appends a sticker hint to the prompt; keep it out of the transcript
146
+ const at = line.indexOf('(想发个表情包时')
147
+ return at === -1 ? line : line.slice(0, at).trimEnd()
148
+ }
149
+
150
+ // Longer per-conversation history (with timestamps) the model can search.
151
+ const history = new Map()
152
+ const stamp = () => {
153
+ const now = new Date()
154
+ return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
155
+ }
156
+ const pushHistory = (convKey, line) => {
157
+ const list = history.get(convKey) ?? []
158
+ list.push(`[${stamp()}] ${stripHints(line)}`)
159
+ const cap = Number.isFinite(config.historyMax) ? config.historyMax : 200
160
+ if (list.length > cap) list.splice(0, list.length - cap)
161
+ history.set(convKey, list)
162
+ }
163
+
164
+ // One workspace per QQ conversation when auto-grouping is on; falls back to cwd.
165
+ const workspaceFor = async (convKey, overrides) => {
166
+ const enabled = overrides?.autoGroup === undefined ? config.autoGroup === true : overrides.autoGroup === true
167
+ if (!enabled) return config.cwd
168
+ const root = String(overrides?.autoGroupRoot || config.autoGroupRoot || 'D:\\dsh-qqbot-temp')
169
+ const name = convKey.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'qq'
170
+ const dir = join(root, name)
171
+ try {
172
+ await mkdir(dir, { recursive: true })
173
+ return dir
174
+ } catch (error) {
175
+ log(`workspace mkdir failed (${dir}): ${error instanceof Error ? error.message : String(error)}`)
176
+ return config.cwd
177
+ }
178
+ }
179
+
180
+ // 会话搬家:优先调用 dsh-edit-file-workspace 的 /move 路由(保留上下文),
181
+ // 失败才退化成"新建会话"(丢上下文)。该路由要求请求来自回环,我们的桥就在本机。
182
+ const moveSessionTo = async (sessionId, targetPath) => {
183
+ let webServer
184
+ try {
185
+ webServer = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
186
+ } catch (error) {
187
+ webServer = undefined
188
+ }
189
+ const port = webServer && typeof webServer.port === 'number' ? webServer.port : 0
190
+ if (port === 0) return { ok: false, reason: 'webServer 不可用' }
191
+ try {
192
+ const response = await fetch(`http://127.0.0.1:${port}/api/dsh-edit-file-workspace/move`, {
193
+ method: 'POST',
194
+ headers: { 'content-type': 'application/json' },
195
+ body: JSON.stringify({ sessionId, path: targetPath }),
196
+ })
197
+ const payload = await response.json().catch(() => ({}))
198
+ if (response.ok) return { ok: true, sandbox: payload?.sandbox }
199
+ return { ok: false, reason: payload?.error || ('HTTP ' + response.status) }
200
+ } catch (error) {
201
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) }
202
+ }
203
+ }
204
+ // 提问通道:pending 表 + QQ 卡片投递(单题单选;多题/多选下一步)
205
+ const questionPending = new Map()
206
+ const sessionToConv = new Map()
207
+ const askOnQq = async (convKey, id, question, options) => {
208
+ const port = Number(config.panelPort) || 39062
209
+ const response = await fetch(`http://127.0.0.1:${port}/api/question`, {
210
+ method: 'POST',
211
+ headers: { 'content-type': 'application/json' },
212
+ body: JSON.stringify({ convKey, id, question, options }),
213
+ })
214
+ if (!response.ok) throw new Error(`bot question endpoint HTTP ${response.status}`)
215
+ }
216
+
217
+ const installQuestionChannel = () => {
218
+ if (typeof ctx.on !== 'function') return () => {}
219
+ const sessionToConv = new Map()
220
+ const refreshMap = async () => {
221
+ try {
222
+ const listed = await bridge.listConversations?.()
223
+ if (Array.isArray(listed?.conversations)) {
224
+ for (const item of listed.conversations) {
225
+ const convKey = String(item.convKey ?? item.key ?? "")
226
+ const sessionId = store.sessionOf(convKey)
227
+ if (sessionId !== undefined) sessionToConv.set(String(sessionId), convKey)
228
+ }
229
+ }
230
+ } catch (error) { /* map stays as-is */ }
231
+ }
232
+ void refreshMap()
233
+ // 官方契约:waterfall answerer 要 { global: true, prepend: true },
234
+ // 回调返回 Promise<UserQuestionResult>;不是 QQ 会话就 return next()。
235
+ return ctx.on('user-questions/request', (request, next) => {
236
+ const agentId = String(request?.agent?.id ?? "")
237
+ // store.convOf 是持久化的反查(sessionId → convKey),插件重启也不会丢
238
+ const convKey = sessionToConv.get(agentId) ?? store.convOf(agentId)
239
+ log(`question request: agent=${agentId} conv=${convKey ?? '-'}`)
240
+ const questions = Array.isArray(request?.questions) ? request.questions : []
241
+ const first = questions[0]
242
+ const options = Array.isArray(first?.options) ? first.options : []
243
+ if (convKey === undefined || first === undefined || options.length === 0) return next()
244
+ const id = randomUUID()
245
+ const labels = options.map((item) => String(item.label ?? item))
246
+ return new Promise((resolve, reject) => {
247
+ // 超时兜底:QQ 那边一直没人点也不能把 ask_user_question 挂死
248
+ const timeoutMs = Number(config.approvalTimeoutMs) || 150000
249
+ const deadline = setTimeout(() => {
250
+ if (!questionPending.has(id)) return
251
+ questionPending.delete(id)
252
+ const error = new Error("ask_user_question timed out waiting for a QQ answer")
253
+ error.code = "ASK_ABORTED"
254
+ reject(error)
255
+ }, timeoutMs)
256
+ questionPending.set(id, {
257
+ deadline,
258
+ resolve: (answer) => {
259
+ const index = Number(answer?.index)
260
+ const picked = labels[index]
261
+ questionPending.delete(id)
262
+ resolve({ answers: [{ questionIndex: 0, selected: picked === undefined ? [] : [picked] }] })
263
+ },
264
+ })
265
+ const signal = request?.signal
266
+ if (signal !== undefined && typeof signal.addEventListener === "function") {
267
+ signal.addEventListener("abort", () => {
268
+ questionPending.delete(id)
269
+ const error = new Error("ask_user_question was aborted before the user answered")
270
+ error.code = "ASK_ABORTED"
271
+ reject(error)
272
+ })
273
+ }
274
+ void askOnQq(convKey, id, String(first.question ?? ""), labels).catch((error) => {
275
+ questionPending.delete(id)
276
+ reject(error instanceof Error ? error : new Error(String(error)))
277
+ })
278
+ })
279
+ }, { global: true, prepend: true })
280
+ }
281
+ // 提示词形状的文本(机器人自己拼的判断/闲聊提示)不许进历史,否则会被当成群友发言回灌给模型
282
+ const looksLikePrompt = (value) => {
283
+ const text = String(value ?? '')
284
+ return text.includes('【闲聊模式】') || text.includes('【群聊插话判断】')
285
+ }
286
+
287
+ const remember = (convKey, line) => {
288
+ if (looksLikePrompt(line)) return
289
+ const list = contexts.get(convKey) ?? []
290
+ const stamped = `[${stamp()}] ${stripHints(line)}`
291
+ list.push(stamped)
292
+ if (list.length > config.contextLines) list.splice(0, list.length - config.contextLines)
293
+ contexts.set(convKey, list)
294
+ pushHistory(convKey, line)
295
+ }
296
+
297
+ /** Model-facing preamble: where the message came from and who is speaking. */
298
+ const composePrompt = ({ text, convKey, senderName, isOwner, chime, quote, persona }) => {
299
+ const isGroup = convKey.startsWith('group:')
300
+ const header = isGroup ? 'QQ 群聊' : 'QQ 单聊'
301
+ const who = isOwner
302
+ ? `${senderName || '主人'}(机器人主人本人:可以远程办公,直接读写工作目录、执行命令、查资料,做完再回答)`
303
+ : `${senderName || '群友'}(普通群友:自然聊天为主;要改文件或跑命令时先说明理由,主人批准后才继续)`
304
+ const recent = contexts.get(convKey) ?? []
305
+ const parts = [`[${header}] ${who}:`]
306
+ if (quote !== undefined) {
307
+ // Structured by the bot: text / image / file / other, plus the author when known.
308
+ const who = quote.author || '一条更早的消息'
309
+ const kind = typeof quote.kind === 'string' ? quote.kind : 'text'
310
+ if (quote.resolved === true && kind === 'image') {
311
+ parts.push(`【引用了${who}发的一张图片】`, '')
312
+ } else if (quote.resolved === true && kind === 'file') {
313
+ parts.push(`【引用了${who}发的文件:${String(quote.text ?? '') || '(未命名)'}】`, '')
314
+ } else if (quote.resolved === true && kind === 'other') {
315
+ parts.push(`【引用了${who}发的一条非文本消息】`, '')
316
+ } else if (quote.resolved === true) {
317
+ const limit = Number.isFinite(config.quoteContextChars) ? config.quoteContextChars : 300
318
+ const full = String(quote.text ?? '')
319
+ const cut = full.length > limit
320
+ const quoted = cut ? `${full.slice(0, limit)}…` : full
321
+ parts.push(`【引用了${who}的消息】`, `“${quoted || '(空)'}”`, '')
322
+ } else {
323
+ const hint = quote.author ? `(可能来自${quote.author})` : ''
324
+ parts.push(`【对方引用了一条我这边看不到内容的消息${hint}】`, '')
325
+ }
326
+ }
327
+ parts.push(text)
328
+ if (isGroup && recent.length > 0) {
329
+ parts.push('', '最近的群聊记录(只作上下文,不必逐条回应):', ...recent)
330
+ }
331
+ if (chime) {
332
+ parts.push('', '这条不是点名问你,是你自己决定要不要插话:觉得没必要就只回 [NO_REPLY]。')
333
+ }
334
+ parts.push('', isGroup && !isOwner
335
+ ? '(这是群聊:像真人一样回 1~3 句口语。想清楚再说完,不要复述工具过程。)'
336
+ : '(先直接回答,别铺垫;默认简短,需要细节时再用 Markdown 展开。)')
337
+ parts.push('', '(QQ 侧支持 Markdown 渲染:标题/列表/代码块/表格都能用,表情符号可以直接用。要把本地图片或文件发给对方,先把文件写到工作目录里,再在回复里单独一行写 [[send_file: 绝对路径]],机器人会把它作为文件发出。)')
338
+ // 人设只在会话的第一条消息里出现一次,之后靠会话历史记住
339
+ if (typeof persona === 'string' && persona.trim() !== '') parts.push('', '人设:', persona.trim())
340
+ return parts.join('\n')
341
+ }
342
+
343
+ /** Ask the bot owner, then translate the answer into an approval outcome. */
344
+ const requestDecision = ({ approvalId, convKey, approvalTarget, toolName, reason, argumentPreview, signal }) => new Promise((resolveDecision) => {
345
+ const settle = (outcome) => {
346
+ clearTimeout(timer)
347
+ signal?.removeEventListener?.('abort', onAbort)
348
+ approvals.delete(approvalId)
349
+ resolveDecision(outcome)
350
+ }
351
+ const finish = (outcome) => {
352
+ if (!approvals.has(approvalId)) return
353
+ settle(outcome)
354
+ }
355
+ const timer = setTimeout(() => {
356
+ if (!approvals.has(approvalId)) return
357
+ bridge.push({ type: 'notice', convKey, target: approvalTarget, text: `审批超时(${toolName}),已按拒绝处理。` })
358
+ log(`approval timeout: ${toolName}`)
359
+ settle('rejected')
360
+ }, config.approvalTimeoutMs)
361
+ const onAbort = () => finish('cancelled')
362
+ approvals.set(approvalId, finish)
363
+ signal?.addEventListener?.('abort', onAbort, { once: true })
364
+ bridge.push({
365
+ type: 'approval',
366
+ convKey,
367
+ target: approvalTarget,
368
+ approvalId,
369
+ toolName,
370
+ reason,
371
+ argumentPreview,
372
+ expiresAt: Date.now() + config.approvalTimeoutMs,
373
+ })
374
+ log(`approval asked: ${toolName} (${convKey})`)
375
+ })
376
+
377
+ /** Ask the Host for its Session list, tolerating builds without a list API. */
378
+ const listSessions = async () => {
379
+ const controller = host.sessionController
380
+ if (controller === undefined) return { source: 'none', sessions: [] }
381
+ for (const method of ['list', 'listSessions', 'listAll', 'all', 'sessions', 'query']) {
382
+ const fn = controller[method]
383
+ if (typeof fn !== 'function') continue
384
+ try {
385
+ const value = await fn.call(controller, {})
386
+ const rows = Array.isArray(value) ? value : (Array.isArray(value?.sessions) ? value.sessions : [])
387
+ return {
388
+ source: method,
389
+ sessions: rows
390
+ .map(row => ({
391
+ id: String(row?.sessionId ?? row?.id ?? ''),
392
+ title: String(row?.title ?? row?.name ?? ''),
393
+ cwd: String(row?.cwd ?? ''),
394
+ }))
395
+ .filter(row => row.id !== ''),
396
+ }
397
+ } catch (error) {
398
+ return { source: method, sessions: [], error: error instanceof Error ? error.message : String(error) }
399
+ }
400
+ }
401
+ return { source: 'unavailable', sessions: [] }
402
+ }
403
+
404
+ const markPull = () => { lastPullAt = Date.now() }
405
+ const botIsListening = () => lastPullAt !== 0 && Date.now() - lastPullAt < 45000
406
+ bridge.setOnPull(markPull)
407
+
408
+ bridge.setHandlers({
409
+ health: () => ({
410
+ ok: true,
411
+ plugin: 'dsh-qq-bridge',
412
+ service: host.sessionController === undefined ? 'waiting' : 'ready',
413
+ conversations: store.size(),
414
+ pendingApprovals: approvals.size,
415
+ }),
416
+ // 设置面板的「下载 / 配置机器人」:status 查进度,start 开装
417
+ install: async (body) => {
418
+ const action = typeof body?.action === 'string' && body.action !== '' ? body.action : 'status'
419
+ if (action === 'status') return { ok: true, ...installer.state() }
420
+ if (action !== 'start') return { ok: false, error: `unknown install action: ${action}` }
421
+ installer.sourceDir = await resolveSourceDir(pluginRoot)
422
+ const started = installer.start({
423
+ appid: typeof body.appid === 'string' ? body.appid : '',
424
+ appsecret: typeof body.appsecret === 'string' ? body.appsecret : '',
425
+ autoGroupRoot: typeof body.autoGroupRoot === 'string' ? body.autoGroupRoot : '',
426
+ // 新装的机器人要连的就是这个插件,地址与令牌直接给它带上
427
+ bridgeUrl: `http://${config.host}:${config.port}`,
428
+ bridgeToken: config.token,
429
+ })
430
+ log(`install started: source=${installer.sourceDir} target=${installer.botDir}`)
431
+ return { ok: true, ...started }
432
+ },
433
+ status: () => ({
434
+ ok: true,
435
+ cwd: config.cwd,
436
+ statePath: config.statePath,
437
+ service: host.sessionController === undefined ? 'waiting' : 'ready',
438
+ conversations: store.entries(),
439
+ bufferedContexts: [...contexts.entries()].map(([key, lines]) => [key, lines.length]),
440
+ pendingApprovals: [...approvals.keys()],
441
+ cursor: bridge.cursor,
442
+ }),
443
+ reset: async (body) => {
444
+ const convKey = typeof body?.convKey === 'string' ? body.convKey : ''
445
+ if (convKey === '') return { ok: false, error: 'convKey required' }
446
+ await store.unbind(convKey)
447
+ contexts.delete(convKey)
448
+ log(`conversation reset: ${convKey}`)
449
+ return { ok: true, convKey }
450
+ },
451
+ /** Move one QQ conversation onto another existing Session ('' = go back). */
452
+ switch: async (body) => {
453
+ await ready
454
+ const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
455
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : ''
456
+ if (convKey === '') return { ok: false, error: 'convKey required' }
457
+ if (sessionId === '') {
458
+ const restored = await store.switchBack(convKey)
459
+ if (restored === undefined) return { ok: false, error: '没有可切回的会话' }
460
+ contexts.delete(convKey)
461
+ log(`switched back: ${convKey} → ${restored}`)
462
+ return { ok: true, convKey, sessionId: restored }
463
+ }
464
+ const previous = store.sessionOf(convKey)
465
+ await store.switchTo(convKey, sessionId)
466
+ contexts.delete(convKey)
467
+ log(`switched: ${convKey} → ${sessionId} (was ${previous ?? 'none'})`)
468
+ return { ok: true, convKey, sessionId, previous: previous ?? '' }
469
+ },
470
+ sessions: async () => {
471
+ await ready
472
+ return { ok: true, bound: store.entries(), returns: store.returnEntries(), host: await listSessions() }
473
+ },
474
+ inbound: async (body) => {
475
+ await ready
476
+ const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
477
+ const text = typeof body?.text === 'string' ? body.text : ''
478
+ const images = Array.isArray(body?.images) ? body.images : []
479
+ if (convKey === '') return { ok: false, error: 'convKey required' }
480
+ if (text.trim() === '' && images.length === 0) return { ok: false, error: 'text or images required' }
481
+
482
+ const senderName = typeof body?.senderName === 'string' ? body.senderName : ''
483
+ // quoted message resolved by the bot (see bot/main.py _resolve_quote)
484
+ const quote = body?.quote !== null && typeof body?.quote === 'object' ? body.quote : undefined
485
+ const quoteMark = quote !== undefined && quote.resolved === true
486
+ ? ` ↩[${quote.author || '引用'}]`
487
+ : ''
488
+ const label = (text.trim() === '' ? '[图片]' : preview(text, 200)) + quoteMark
489
+
490
+ // Background group chatter: keep it as context, never start a turn for it.
491
+ if (body?.contextOnly === true) {
492
+ if (!looksLikePrompt(text)) remember(convKey, `${senderName || '群友'}: ${label}`)
493
+ return { ok: true, buffered: true }
494
+ }
495
+
496
+ const sessionController = host.sessionController
497
+ if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
498
+
499
+ let sessionId = store.sessionOf(convKey)
500
+ let freshSession = false
501
+ if (sessionId === undefined) {
502
+ const created = await sessionController.create({ cwd: await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot }) })
503
+ sessionId = String(created.sessionId)
504
+ freshSession = true
505
+ log(`session created: ${convKey} → ${sessionId}`)
506
+ }
507
+ await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
508
+ sessionToConv.set(String(sessionId), convKey)
509
+
510
+ // Casual chat is latency-bound: pin the session to the configured model /
511
+ // reasoning effort once, without losing the Session's history.
512
+ if (!selected.has(sessionId) && config.modelProvider !== '' && config.model !== '') {
513
+ try {
514
+ await sessionController.selectModel({
515
+ sessionId,
516
+ provider: config.modelProvider,
517
+ model: config.model,
518
+ ...(config.reasoningEffort !== '' ? { reasoningEffort: config.reasoningEffort } : {}),
519
+ })
520
+ log(`model pinned for ${sessionId}: ${config.modelProvider}/${config.model} effort=${config.reasoningEffort || 'default'}`)
521
+ } catch (error) {
522
+ log(`selectModel failed for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`)
523
+ }
524
+ selected.add(sessionId)
525
+ }
526
+
527
+ // 人设随请求带过来;只有刚建的新会话才塞进提示词,之后不再重复
528
+ const persona = freshSession && typeof body?.persona === 'string' ? body.persona : ''
529
+ const content = [{ type: 'text', text: composePrompt({ text, convKey, senderName, isOwner: body?.isOwner === true, chime: body?.chime === true, quote, persona }) }]
530
+ for (const image of images.slice(0, 4)) {
531
+ const mediaType = typeof image?.mediaType === 'string' ? image.mediaType : ''
532
+ const data = typeof image?.data === 'string' ? image.data : ''
533
+ if (!IMAGE_TYPES.has(mediaType) || data === '') continue
534
+ content.push({ type: 'image', mediaType, data })
535
+ }
536
+
537
+ const controller = new AbortController()
538
+ const timer = setTimeout(() => controller.abort(), 120000)
539
+ try {
540
+ await sessionController.prompt({
541
+ requestId: randomUUID(),
542
+ sessionId,
543
+ mode: 'queue',
544
+ content,
545
+ clientTimeZone: 'Asia/Shanghai',
546
+ }, controller.signal)
547
+ } finally {
548
+ clearTimeout(timer)
549
+ }
550
+ if (!looksLikePrompt(text)) remember(convKey, `${senderName || '群友'}: ${label}`)
551
+ return { ok: true, sessionId, accepted: true }
552
+ },
553
+ rebind: async (body) => {
554
+ await ready
555
+ const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
556
+ if (convKey === '') return { ok: false, error: 'convKey required' }
557
+ const sessionController = host.sessionController
558
+ if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
559
+ const dir = await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot })
560
+ const existing = store.sessionOf(convKey)
561
+ let fallbackReason = ""
562
+ if (existing !== undefined) {
563
+ const moved = await moveSessionTo(existing, dir)
564
+ if (moved.ok) return { ok: true, sessionId: existing, cwd: dir, moved: true, sandbox: moved.sandbox }
565
+ fallbackReason = String(moved.reason || 'move failed')
566
+ log(`session move failed (${convKey}): ${fallbackReason}; falling back to a new session`)
567
+ }
568
+ try {
569
+ const created = await sessionController.create({ cwd: dir })
570
+ const sessionId = String(created.sessionId)
571
+ await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
572
+ sessionToConv.set(String(sessionId), convKey)
573
+ return { ok: true, sessionId, cwd: dir, moved: false, fallbackReason, previous: body?.previous || null }
574
+ } catch (error) {
575
+ return { ok: false, error: 'create failed: ' + (error instanceof Error ? error.message : String(error)) }
576
+ }
577
+ },
578
+
579
+ answer: async (body) => {
580
+ await ready
581
+ const id = typeof body?.id === 'string' ? body.id : ''
582
+ if (id === '') return { ok: false, error: 'id required' }
583
+ const pending = questionPending.get(id)
584
+ if (pending?.deadline) clearTimeout(pending.deadline)
585
+ if (pending === undefined) return { ok: false, error: 'this question is no longer pending' }
586
+ questionPending.delete(id)
587
+ try { pending.resolve(body) } catch (error) { /* already settled */ }
588
+ return { ok: true }
589
+ },
590
+ commands: async (body) => {
591
+ await ready
592
+ const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
593
+ const ctxOf = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
594
+ const agents = ctxOf('agents')
595
+ const runtime = ctxOf('commands')
596
+ if (agents === undefined || runtime === undefined) return { ok: false, error: 'agents/commands 服务不可用' }
597
+ const sessionId = store.sessionOf(convKey)
598
+ if (sessionId === undefined) return { ok: false, error: '这个会话还没有 DSH 会话' }
599
+ const agent = typeof agents.get === 'function' ? agents.get(sessionId) : undefined
600
+ if (agent === undefined) return { ok: false, error: '会话未加载(先聊一句)' }
601
+ let list = []
602
+ try {
603
+ list = runtime.list(agent).map((item) => ({
604
+ name: item.name,
605
+ description: item.description || item.summary || '',
606
+ source: item.source || '',
607
+ }))
608
+ } catch (error) {
609
+ return { ok: false, error: 'list failed: ' + (error instanceof Error ? error.message : String(error)) }
610
+ }
611
+ return { ok: true, count: list.length, commands: list }
612
+ },
613
+
614
+ command: async (body) => {
615
+ await ready
616
+ const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
617
+ const line = typeof body?.line === 'string' ? body.line.trim() : ''
618
+ if (line === '') return { ok: false, error: 'line required' }
619
+ const ctxOf = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
620
+ const agents = ctxOf('agents')
621
+ const runtime = ctxOf('commands')
622
+ if (agents === undefined || runtime === undefined) return { ok: false, error: 'agents/commands 服务不可用' }
623
+ const sessionId = store.sessionOf(convKey)
624
+ if (sessionId === undefined) return { ok: false, error: '这个会话还没有 DSH 会话' }
625
+ const agent = typeof agents.get === 'function' ? agents.get(sessionId) : undefined
626
+ if (agent === undefined) return { ok: false, error: '会话未加载(先聊一句)' }
627
+ try {
628
+ const result = await runtime.execute(agent, line, [], new AbortController().signal)
629
+ return { ok: true, handled: result !== undefined, line }
630
+ } catch (error) {
631
+ return { ok: false, error: 'execute failed: ' + (error instanceof Error ? error.message : String(error)) }
632
+ }
633
+ },
634
+ permission: async (body) => {
635
+ await ready
636
+ const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
637
+ const preset = typeof body?.preset === 'string' ? body.preset.trim() : ''
638
+ let service = host.permissionPresets
639
+ if (service === undefined && typeof ctx.get === 'function') service = ctx.get('permissionPresets')
640
+ const names = service && Array.isArray(service.names) ? service.names.slice() : []
641
+ // 该会话"当下生效"的权限值(会话投影),读不到就退回默认值
642
+ const liveCurrent = () => {
643
+ try {
644
+ const sid = store.sessionOf(convKey)
645
+ if (sid === undefined) return ''
646
+ const pick = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
647
+ const sessions = pick('sessions')
648
+ let session = sessions && typeof sessions.get === 'function' ? sessions.get(sid) : undefined
649
+ if (session === undefined) {
650
+ const agents = pick('agents')
651
+ session = agents && typeof agents.get === 'function' ? agents.get(sid) : undefined
652
+ }
653
+ if (session !== undefined && service && typeof service.current === 'function') return service.current(session)
654
+ } catch (error) {
655
+ return ''
656
+ }
657
+ return ''
658
+ }
659
+ if (preset === '') {
660
+ return {
661
+ ok: names.length > 0,
662
+ names,
663
+ current: liveCurrent() || (service && typeof service.defaultPreset === 'string' ? service.defaultPreset : ''),
664
+ note: names.length > 0 ? '' : 'permissionPresets 服务不可用(这条 DSH 没启用权限预设)',
665
+ }
666
+ }
667
+ if (names.length > 0 && !names.includes(preset)) {
668
+ return { ok: false, error: 'unknown preset: ' + preset, names }
669
+ }
670
+ const sessionController = host.sessionController
671
+ let sessionId = store.sessionOf(convKey)
672
+ if (sessionController === undefined && sessionId === undefined) {
673
+ return { ok: false, error: 'sessionController unavailable' }
674
+ }
675
+ if (sessionId === undefined) {
676
+ // 还没聊过:先给这个 QQ 会话建 DSH 会话(自动工作区开启时自带独立目录),
677
+ // 否则 /pr 没法把命令投递进去。
678
+ try {
679
+ const created = await sessionController.create({
680
+ cwd: await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot }),
681
+ })
682
+ sessionId = String(created.sessionId)
683
+ await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
684
+ sessionToConv.set(String(sessionId), convKey)
685
+ } catch (error) {
686
+ return { ok: false, error: 'create session failed: ' + (error instanceof Error ? error.message : String(error)) }
687
+ }
688
+ }
689
+ // 官方写入口:permissionPresets.set(session, name)(/permission 命令内部走的就是它)。
690
+ // 之前用 sessionController.prompt 发文本,斜杠命令不会被解释,只会变成一条用户消息。
691
+ let sessions = undefined
692
+ try { sessions = typeof ctx.get === 'function' ? ctx.get('sessions') : undefined } catch (error) { sessions = undefined }
693
+ const session = sessions && typeof sessions.get === 'function' ? sessions.get(sessionId) : undefined
694
+ if (session === undefined) return { ok: false, error: '会话还没加载,先聊一句再试' }
695
+ if (service === undefined || typeof service.set !== 'function') {
696
+ return { ok: false, error: 'permissionPresets 服务不可用' }
697
+ }
698
+ try {
699
+ service.set(session, preset)
700
+ } catch (error) {
701
+ return { ok: false, error: 'set failed: ' + (error instanceof Error ? error.message : String(error)) }
702
+ }
703
+ let landed = ''
704
+ try { landed = typeof service.current === 'function' ? service.current(session) : '' } catch (error) { landed = '' }
705
+ return { ok: true, switched: preset, current: landed, names }
706
+ },
707
+
708
+ judge: async (body) => {
709
+ await ready
710
+ const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
711
+ const transcript = typeof body?.transcript === 'string' ? body.transcript.trim() : ''
712
+ if (convKey === '' || transcript === '') return { ok: false, error: 'convKey/transcript required' }
713
+ const sessionController = host.sessionController
714
+ if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
715
+
716
+ let sessionId = judgeSessions.get(convKey)
717
+ try {
718
+ if (sessionId === undefined) {
719
+ const created = await sessionController.create({ cwd: config.cwd })
720
+ sessionId = String(created.sessionId)
721
+ judgeSessions.set(convKey, sessionId)
722
+ log(`judge session for ${convKey}: ${sessionId}`)
723
+ }
724
+ } catch (error) {
725
+ return { ok: false, error: `judge session failed: ${error instanceof Error ? error.message : String(error)}` }
726
+ }
727
+
728
+ judgeTexts.set(sessionId, [])
729
+ const verdict = new Promise(resolve => {
730
+ judgeWaiters.set(sessionId, resolve)
731
+ setTimeout(() => {
732
+ if (judgeWaiters.get(sessionId) === resolve) {
733
+ judgeWaiters.delete(sessionId)
734
+ resolve('')
735
+ }
736
+ }, 90000)
737
+ })
738
+
739
+ const threshold = Number.isFinite(Number(body?.threshold)) ? Number(body.threshold) : 2
740
+ const hint = typeof body?.hint === 'string' ? body.hint.trim() : ''
741
+ const instruction = [
742
+ '【群聊插话判断器】你就是这个群里的一员,只做决定:接一句,还是不说。',
743
+ '默认接一句(口语、1~2 句)。只有这三种情况才不说:',
744
+ '① 明显是两个人一对一搭话,既没提到你也没什么可加;',
745
+ '② 你刚说过同类的话;',
746
+ '③ 这条只是表情/图片/链接/单字,没有可回应的内容。',
747
+ '其余情况(抛观点、吐槽、问问题、接梗)都可以接;话题不熟也可以轻接。',
748
+ hint,
749
+ '',
750
+ '群里的原文(每行 发言人: 内容):',
751
+ transcript,
752
+ '',
753
+ '输出格式(严格两行):',
754
+ '第一行:[[join: 0~3]](3=必须接,2=想接,1=可接可不接,0=不说)',
755
+ '第二行:一句话理由(不超过 40 字)',
756
+ ].filter(line => line !== '').join('\n')
757
+
758
+ try {
759
+ await sessionController.prompt({
760
+ requestId: randomUUID(),
761
+ sessionId,
762
+ mode: 'queue',
763
+ content: [{ type: 'text', text: instruction }],
764
+ clientTimeZone: 'Asia/Shanghai',
765
+ }, new AbortController().signal)
766
+ } catch (error) {
767
+ judgeWaiters.delete(sessionId)
768
+ return { ok: false, error: `judge prompt failed: ${error instanceof Error ? error.message : String(error)}` }
769
+ }
770
+
771
+ const answer = String(await verdict)
772
+ const lines = answer.split('\n').map(line => line.trim()).filter(line => line !== '')
773
+ const head = (lines[0] ?? '').toUpperCase()
774
+ const joinMatch = answer.match(/\[\[\s*join\s*:\s*([0-3])\s*\]\]/i)
775
+ const score = joinMatch ? Number(joinMatch[1]) : null
776
+ const legacyReply = head.startsWith('REPLY')
777
+ const legacySkip = head.startsWith('SKIP')
778
+ const needReply = score !== null ? score >= threshold : legacyReply
779
+ const decisive = score !== null || legacyReply || legacySkip
780
+ const noteSource = score !== null ? answer.replace(joinMatch[0], '') : lines.slice(1).join(' ')
781
+ return {
782
+ ok: decisive,
783
+ needReply,
784
+ score,
785
+ threshold,
786
+ note: noteSource.trim().split('\n').map(line => line.trim()).filter(line => line !== '').join(' ').slice(0, 200),
787
+ raw: answer.slice(0, 200),
788
+ }
789
+ },
790
+ approval: async (body) => {
791
+ const approvalId = typeof body?.approvalId === 'string' ? body.approvalId : ''
792
+ const decision = body?.decision === 'allow' ? 'allowed-once' : body?.decision === 'cancel' ? 'cancelled' : 'rejected'
793
+ const finish = approvals.get(approvalId)
794
+ if (finish === undefined) return { ok: false, error: 'unknown or expired approval' }
795
+ finish(decision)
796
+ log(`approval ${approvalId} → ${decision}`)
797
+ return { ok: true, approvalId, decision }
798
+ },
799
+ })
800
+
801
+ // Keep the QQ bot alive across DSH restarts: DSH owns its own lifecycle, so
802
+ // the host half re-spawns the supervised bot whenever the panel is missing.
803
+ const ensureBot = async () => {
804
+ if (config.autoStartBot !== true) return
805
+ try {
806
+ const response = await fetch(`http://127.0.0.1:${config.panelPort ?? 39062}/health`, { signal: AbortSignal.timeout(1500) })
807
+ if (response.ok) return
808
+ } catch {
809
+ // panel unreachable -> the supervisor is gone, start it
810
+ }
811
+ try {
812
+ // 一键装过就按 install.json 里的 venv 解释器和安装目录启动
813
+ const installed = await readInstall(config.dataDir)
814
+ const pythonPath = typeof installed?.pythonPath === 'string' && installed.pythonPath !== '' ? installed.pythonPath : config.pythonPath
815
+ const botDir = typeof installed?.botDir === 'string' && installed.botDir !== '' ? installed.botDir : config.botDir
816
+ const { spawn } = await import('node:child_process')
817
+ const child = spawn(pythonPath, ['-u', 'main.py', '--supervise'], {
818
+ cwd: botDir,
819
+ detached: true,
820
+ stdio: 'ignore',
821
+ windowsHide: true,
822
+ })
823
+ child.unref()
824
+ log(`bot supervisor spawned (pid ${child.pid})`)
825
+ } catch (error) {
826
+ log(`bot autostart failed: ${error instanceof Error ? error.message : String(error)}`)
827
+ }
828
+ }
829
+ ctx.effect(() => {
830
+ const first = setTimeout(() => { void ensureBot() }, 8000)
831
+ const ticker = setInterval(() => { void ensureBot() }, 60000)
832
+ return () => { clearTimeout(first); clearInterval(ticker) }
833
+ }, 'dsh-qq-bridge: keep the bot process alive')
834
+
835
+ // Serve the loopback port for as long as this plugin entry stays loaded.
836
+ ctx.effect(() => {
837
+ // 提问通道默认关闭:DSH 的 user-questions/request 是瀑布事件,
838
+ // 处理不当会让宿主 abort 并崩溃(crash-…-host.log)。稳定性验证通过后再打开。
839
+ if (config.questionChannel === false) return () => {}
840
+ const dispose = installQuestionChannel()
841
+ return () => { try { dispose() } catch (error) { /* already gone */ } }
842
+ }, 'dsh-qq-bridge: question channel')
843
+
844
+ ctx.effect(() => {
845
+ void bridge.start()
846
+ .then(() => log(`listening on http://${config.host}:${bridge.port} (cwd: ${config.cwd})`))
847
+ .catch(error => log(`listen failed: ${error instanceof Error ? error.message : String(error)}`))
848
+ return () => { void bridge.stop() }
849
+ }, 'dsh-qq-bridge: local http bridge')
850
+
851
+ // Live token stream: the official plugin listens to the transient
852
+ // 'agent/assistant-stream' event and reads frame.chunk.text, so do the same
853
+ // instead of sessionController.follow() (which only yields step snapshots).
854
+ const streams = new Map() // sessionId -> convKey
855
+ const agentSessions = new Map() // agentId -> sessionId
856
+
857
+ const startStream = (sessionId, convKey) => {
858
+ if (config.streamEnabled !== true) return
859
+ streams.set(sessionId, convKey)
860
+ }
861
+
862
+ const stopStream = (sessionId) => {
863
+ streams.delete(sessionId)
864
+ for (const [agentId, mapped] of agentSessions) {
865
+ if (mapped === sessionId) agentSessions.delete(agentId)
866
+ }
867
+ }
868
+
869
+ ctx.on('agent/assistant-stream', (payload) => {
870
+ if (config.streamEnabled !== true || streams.size === 0) return
871
+ const agentId = payload?.agent?.id
872
+ const frame = payload?.frame
873
+ if (typeof agentId !== 'string' || agentId === '' || frame == null) return
874
+
875
+ let sessionId = agentSessions.get(agentId)
876
+ if (sessionId === undefined) {
877
+ const newest = [...streams.keys()].pop()
878
+ if (newest === undefined) return
879
+ agentSessions.set(agentId, newest)
880
+ sessionId = newest
881
+ }
882
+ const convKey = streams.get(sessionId)
883
+ if (convKey === undefined) return
884
+ if (frame.type !== 'chunk') return
885
+ const chunk = frame.chunk
886
+ if (chunk?.type !== 'text-delta' || typeof chunk.text !== 'string' || chunk.text === '') return
887
+ bridge.push({
888
+ type: 'stream',
889
+ convKey,
890
+ turnId: turns.get(sessionId)?.turnId ?? '',
891
+ text: chunk.text,
892
+ final: false,
893
+ })
894
+ })
895
+
896
+ // Independent judge sessions (Plan B): one per conversation, no shared history.
897
+ const judgeTexts = new Map() // sessionId -> collected assistant text
898
+ const judgeWaiters = new Map() // sessionId -> resolve(text)
899
+ const judgeSessions = new Map() // convKey -> sessionId
900
+
901
+ // Capture each finished turn so the bot can answer the QQ message.
902
+ ctx.on('session/event', (session, event) => {
903
+ const sessionId = String(session?.id ?? '')
904
+ if (sessionId === '') return
905
+ const convKey = store.convOf(sessionId)
906
+ if (convKey === undefined) return
907
+ const data = event?.data ?? {}
908
+ if (judgeTexts.has(sessionId)) {
909
+ if (event.type === 'assistant/message') {
910
+ const t = textOf(data.message)
911
+ if (t.trim() !== '') judgeTexts.get(sessionId).push(t)
912
+ }
913
+ if (event.type === 'turn/end') {
914
+ const done = judgeWaiters.get(sessionId)
915
+ if (done !== undefined) {
916
+ judgeWaiters.delete(sessionId)
917
+ done(judgeTexts.get(sessionId).join('\n').trim())
918
+ }
919
+ }
920
+ return
921
+ }
922
+ if (event.type === 'turn/start') {
923
+ turns.set(sessionId, { texts: [], tools: [], turnId: `${Date.now().toString(36)}-${sessionId.slice(-6)}` })
924
+ startStream(sessionId, convKey)
925
+ return
926
+ }
927
+ if (event.type === 'assistant/message') {
928
+ const state = turns.get(sessionId)
929
+ if (state === undefined) return
930
+ const text = textOf(data.message)
931
+ if (text.trim() !== '') state.texts.push(text)
932
+ return
933
+ }
934
+ if (event.type === 'tool/call') {
935
+ const state = turns.get(sessionId)
936
+ if (state === undefined) return
937
+ if (typeof data.name === 'string') state.tools.push(data.name)
938
+ if (typeof data.callId === 'string') {
939
+ callArguments.set(`${sessionId}:${data.callId}`, preview(data.arguments, config.argumentPreviewChars))
940
+ if (callArguments.size > 200) callArguments.delete(callArguments.keys().next().value)
941
+ }
942
+ return
943
+ }
944
+ if (event.type === 'turn/end') {
945
+ const state = turns.get(sessionId) ?? { texts: [], tools: [] }
946
+ turns.delete(sessionId)
947
+ stopStream(sessionId)
948
+ bridge.push({ type: 'stream', convKey, turnId: state.turnId ?? '', text: state.texts.join('\n\n').trim(), final: true })
949
+ // data.reason is an object on this host generation; never ship "[object Object]"
950
+ const rawReason = data.reason
951
+ const reason = typeof rawReason === 'string'
952
+ ? rawReason
953
+ : (rawReason && typeof rawReason === 'object' ? String(rawReason.kind ?? rawReason.type ?? '') : '')
954
+ bridge.push({
955
+ type: 'reply',
956
+ convKey,
957
+ turnId: state.turnId ?? '',
958
+ text: state.texts.join('\n\n').trim(),
959
+ tools: state.tools,
960
+ reason,
961
+ })
962
+ }
963
+ })
964
+
965
+ // Route approvals of bridged Sessions to their owner FIRST: the Web GUI also
966
+ // answers approvals, and only a prepended listener wins that waterfall.
967
+ // Sessions this plugin does not own fall through with next().
968
+ ctx.on('approval/request', async (request, next) => {
969
+ const sessionId = String(request?.agent?.session?.id ?? '')
970
+ const convKey = sessionId === '' ? undefined : store.convOf(sessionId)
971
+ if (convKey === undefined) return next()
972
+ if (!botIsListening()) {
973
+ // Nobody is polling the bridge: never swallow the approval, let the GUI ask.
974
+ log(`approval for ${convKey} handed to the GUI (bot not polling)`)
975
+ return next()
976
+ }
977
+ const approvalTarget = store.approvalTargetOf(convKey) ?? convKey
978
+ const callId = typeof request?.callId === 'string' ? request.callId : ''
979
+ try {
980
+ return await requestDecision({
981
+ approvalId: randomUUID(),
982
+ convKey,
983
+ approvalTarget,
984
+ toolName: String(request?.toolName ?? 'unknown'),
985
+ reason: String(request?.reason ?? ''),
986
+ argumentPreview: callId === '' ? '' : (callArguments.get(`${sessionId}:${callId}`) ?? ''),
987
+ signal: request?.signal,
988
+ })
989
+ } catch (error) {
990
+ log(`approval relay failed: ${error instanceof Error ? error.message : String(error)}`)
991
+ return 'rejected'
992
+ }
993
+ }, { prepend: true })
994
+
995
+ // The Session service may arrive after this entry; wait for it instead of
996
+ // failing the whole profile boot when it is absent.
997
+ // Model-facing retrieval over the timestamped history buffer.
998
+ ctx.inject(['tools'], (scope) => {
999
+ const tools = scope.tools ?? (typeof scope.get === 'function' ? scope.get('tools') : undefined)
1000
+ if (tools === undefined || typeof tools.register !== 'function') {
1001
+ log('qq_history tool unavailable (tools service missing)')
1002
+ return
1003
+ }
1004
+ const definition = {
1005
+ name: 'qq_history',
1006
+ description:
1007
+ '搜索 QQ 群聊/私聊最近的历史消息(每行带 [HH:MM] 时间戳)。' +
1008
+ '当对方提到你没见过的内容、或需要确认「谁在什么时候说过什么」时调用。',
1009
+ parameters: {
1010
+ type: 'object',
1011
+ additionalProperties: false,
1012
+ properties: {
1013
+ convKey: { type: 'string', description: '会话键,如 group:XXXX 或 c2c:XXXX;留空表示所有会话' },
1014
+ query: { type: 'string', description: '关键词,留空返回最近若干条' },
1015
+ limit: { type: 'number', description: '返回条数上限,默认 30,最大 100' },
1016
+ },
1017
+ },
1018
+ output: {
1019
+ schema: { type: 'object' },
1020
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
1021
+ },
1022
+ async execute(args) {
1023
+ const limit = Math.max(1, Math.min(Number(args?.limit ?? 30) || 30, 100))
1024
+ const needle = typeof args?.query === 'string' ? args.query.trim() : ''
1025
+ const convFilter = typeof args?.convKey === 'string' ? args.convKey.trim() : ''
1026
+ const keys = convFilter !== '' ? [convFilter] : [...history.keys()]
1027
+ const lines = []
1028
+ for (const key of keys) {
1029
+ for (const line of history.get(key) ?? []) {
1030
+ if (needle === '' || line.includes(needle)) lines.push(`${key} ${line}`)
1031
+ }
1032
+ }
1033
+ return { ok: true, count: lines.slice(-limit).length, lines: lines.slice(-limit) }
1034
+ },
1035
+ }
1036
+ try {
1037
+ tools.register(definition)
1038
+ log('qq_history tool registered')
1039
+ } catch (error) {
1040
+ log(`qq_history registration failed: ${error instanceof Error ? error.message : String(error)}`)
1041
+ }
1042
+
1043
+ // ── 群管理工具(禁言 / 踢人 / 成员索引) ──
1044
+ const adminCall = async (payload) => {
1045
+ const port = Number(config.panelPort) || 39062
1046
+ const response = await fetch(`http://127.0.0.1:${port}/api/admin`, {
1047
+ method: 'POST',
1048
+ headers: { 'content-type': 'application/json' },
1049
+ body: JSON.stringify(payload),
1050
+ })
1051
+ return await response.json().catch(() => ({}))
1052
+ }
1053
+
1054
+ const readMembers = () => {
1055
+ try {
1056
+ const file = join(String(config.botDir || "."), "state", "members.json")
1057
+ const raw = readFileSync(file, "utf8")
1058
+ return JSON.parse(raw)
1059
+ } catch (error) {
1060
+ return {}
1061
+ }
1062
+ }
1063
+
1064
+ const resolveMember = (convKey, member) => {
1065
+ const known = readMembers()[convKey] || {}
1066
+ const raw = String(member || "").trim().replace(/^@/, "").replace(/^群友/i, "").toUpperCase()
1067
+ if (raw === "") return undefined
1068
+ for (const [tail, info] of Object.entries(known)) {
1069
+ if (tail.toUpperCase() === raw) return info?.openid ?? info
1070
+ }
1071
+ for (const [tail, info] of Object.entries(known)) {
1072
+ if (raw.length >= 4 && tail.toUpperCase().includes(raw)) return info?.openid ?? info
1073
+ }
1074
+ // 按昵称找人:群里 @ 出来的名字或自己记得的名字都能用
1075
+ const wanted = String(member || "").trim().replace(/^@/, "").replace(/^群友/i, "")
1076
+ if (wanted) {
1077
+ for (const [tail, info] of Object.entries(known)) {
1078
+ const name = String((info && typeof info === "object" && info.name) || "").trim()
1079
+ if (name && name.toLowerCase() === wanted.toLowerCase()) return info?.openid ?? info
1080
+ }
1081
+ for (const [tail, info] of Object.entries(known)) {
1082
+ const name = String((info && typeof info === "object" && info.name) || "").trim()
1083
+ if (name && wanted.length >= 2 && name.toLowerCase().includes(wanted.toLowerCase())) return info?.openid ?? info
1084
+ }
1085
+ }
1086
+ if (/^[0-9A-F]{32}$/.test(raw)) return raw
1087
+ return undefined
1088
+ }
1089
+
1090
+ const adminTools = [
1091
+ {
1092
+ name: "qq_members",
1093
+ description: "列出本群/本会话里发过言的成员(短号 → openid)。禁言/踢人前先查这个拿短号。",
1094
+ parameters: { type: "object", additionalProperties: false, properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } } },
1095
+ async execute(args) {
1096
+ const convKey = String(args?.convKey || "")
1097
+ const all = readMembers()
1098
+ const people = convKey !== "" ? { [convKey]: all[convKey] || {} } : all
1099
+ const lines = []
1100
+ for (const [key, members] of Object.entries(people)) {
1101
+ for (const [tail, info] of Object.entries(members || {})) {
1102
+ lines.push({
1103
+ convKey: key,
1104
+ tail,
1105
+ name: (info && typeof info === "object" && info.name) || "",
1106
+ openid: (info && typeof info === "object" ? info.openid : info) || "",
1107
+ avatar: (info && typeof info === "object" && info.avatar) || "",
1108
+ })
1109
+ }
1110
+ }
1111
+ return { ok: true, count: lines.length, members: lines }
1112
+ },
1113
+ },
1114
+ {
1115
+ name: "qq_mute",
1116
+ description: "禁言群里某个成员(需要机器人是群管理员且有接口权限)。member 可以是短号(如 1B6CBB)或 @群友XXXX。",
1117
+ parameters: {
1118
+ type: "object", additionalProperties: false,
1119
+ required: ["convKey", "member", "minutes"],
1120
+ properties: {
1121
+ convKey: { type: "string", description: "会话键,如 group:XXXX" },
1122
+ member: { type: "string", description: "被禁言的成员:短号或 @群友XXXX" },
1123
+ minutes: { type: "number", description: "禁言分钟数(720=12 小时);传 0 表示解除禁言" },
1124
+ },
1125
+ },
1126
+ async execute(args) {
1127
+ const convKey = String(args?.convKey || "")
1128
+ const openid = resolveMember(convKey, args?.member)
1129
+ if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1130
+ const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1131
+ // minutes <= 0 表示解除禁言(op=del);注意不能用 `|| 10`,否则 0 会被吞成 10
1132
+ const raw = Number(args?.minutes)
1133
+ const minutes = Number.isFinite(raw) ? raw : 10
1134
+ const seconds = minutes <= 0 ? 0 : Math.min(Math.round(minutes * 60), 60 * 60 * 24 * 30)
1135
+ const result = await adminCall({ action: "mute", convKey, group, member: openid, seconds })
1136
+ return {
1137
+ ok: result.ok === true,
1138
+ member: args?.member,
1139
+ op: seconds > 0 ? "add" : "del",
1140
+ minutes: seconds / 60,
1141
+ error: result.error,
1142
+ }
1143
+ },
1144
+ },
1145
+ {
1146
+ name: "qq_unmute",
1147
+ description: "解除某个成员的禁言(等价 op=del)。语义独立,避免把 0 分钟误当禁言时长。",
1148
+ parameters: {
1149
+ type: "object", additionalProperties: false,
1150
+ required: ["convKey", "member"],
1151
+ properties: {
1152
+ convKey: { type: "string", description: "会话键,如 group:XXXX" },
1153
+ member: { type: "string", description: "成员:短号或 @群友XXXX" },
1154
+ },
1155
+ },
1156
+ async execute(args) {
1157
+ const convKey = String(args?.convKey || "")
1158
+ const openid = resolveMember(convKey, args?.member)
1159
+ if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1160
+ const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1161
+ const result = await adminCall({ action: "mute", convKey, group, member: openid, seconds: 0 })
1162
+ return { ok: result.ok === true, member: args?.member, op: "del", error: result.error }
1163
+ },
1164
+ },
1165
+ {
1166
+ name: "qq_mute_state",
1167
+ description: "查询本群当前的禁言设置(平台原样返回),用于确认禁言/解禁是否真的生效。",
1168
+ parameters: {
1169
+ type: "object", additionalProperties: false,
1170
+ required: ["convKey"],
1171
+ properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } },
1172
+ },
1173
+ async execute(args) {
1174
+ const convKey = String(args?.convKey || "")
1175
+ const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1176
+ const result = await adminCall({ action: "mute_state", convKey, group })
1177
+ return { ok: result.ok === true, state: result.state, error: result.error }
1178
+ },
1179
+ },
1180
+ {
1181
+ name: "qq_kick",
1182
+ description: "把某个成员移出群(需要机器人是群管理员且有接口权限)。member 可以是短号或 @群友XXXX。",
1183
+ parameters: {
1184
+ type: "object", additionalProperties: false,
1185
+ required: ["convKey", "member"],
1186
+ properties: {
1187
+ convKey: { type: "string", description: "会话键,如 group:XXXX" },
1188
+ member: { type: "string", description: "被移出的成员:短号或 @群友XXXX" },
1189
+ blacklist: { type: "boolean", description: "是否同时拉黑,默认否" },
1190
+ },
1191
+ },
1192
+ async execute(args) {
1193
+ const convKey = String(args?.convKey || "")
1194
+ const openid = resolveMember(convKey, args?.member)
1195
+ if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1196
+ const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1197
+ const result = await adminCall({ action: "kick", convKey, group, member: openid, blacklist: args?.blacklist === true })
1198
+ if (result.pending === true) {
1199
+ // 还没执行:明确告诉模型"等待确认",不要说已经踢了
1200
+ return {
1201
+ ok: false,
1202
+ pending: true,
1203
+ member: args?.member,
1204
+ error: null,
1205
+ hint: result.hint || "已发送私聊二次确认,等主人点头后才执行;现在还没有踢人",
1206
+ }
1207
+ }
1208
+ return { ok: result.ok === true, member: args?.member, error: result.error }
1209
+ },
1210
+ },
1211
+ ]
1212
+
1213
+ const infoTools = [
1214
+ {
1215
+ name: "qq_group",
1216
+ description: "查看当前群资料:群名、群简介、分类、标签、成员数,以及全群禁言规则。",
1217
+ parameters: { type: "object", properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } } },
1218
+ async execute(args) {
1219
+ const convKey = String(args?.convKey || "")
1220
+ const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1221
+ const result = await adminCall({ action: "group", convKey, group })
1222
+ return { ok: result.ok === true, group: result.group, mute_rule: result.mute_rule, known_members: result.known_members, error: result.error }
1223
+ },
1224
+ },
1225
+ {
1226
+ name: "qq_muted",
1227
+ description: "列出本群当前被禁言的成员(名字、openid、短号、到期时间)。",
1228
+ parameters: { type: "object", properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } } },
1229
+ async execute(args) {
1230
+ const convKey = String(args?.convKey || "")
1231
+ const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1232
+ const result = await adminCall({ action: "muted", convKey, group })
1233
+ return { ok: result.ok === true, count: result.count || 0, muted: result.muted || [], error: result.error }
1234
+ },
1235
+ },
1236
+ {
1237
+ name: "qq_member",
1238
+ description: "查看某个群成员的资料:昵称、头像地址、openid、短号、最后发言时间、是否被禁言。member 可传短号/昵称/openid。",
1239
+ parameters: {
1240
+ type: "object",
1241
+ properties: {
1242
+ convKey: { type: "string", description: "会话键,如 group:XXXX" },
1243
+ member: { type: "string", description: "短号、昵称或 openid" },
1244
+ },
1245
+ },
1246
+ async execute(args) {
1247
+ const convKey = String(args?.convKey || "")
1248
+ const openid = resolveMember(convKey, args?.member)
1249
+ if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1250
+ const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1251
+ const result = await adminCall({ action: "member", convKey, group, member: openid })
1252
+ return { ok: result.ok === true, member: result.member, error: result.error }
1253
+ },
1254
+ },
1255
+ {
1256
+ name: "qq_stats",
1257
+ description: "查看机器人统计:私聊/群聊消息数、插话判断与开口次数、流式次数、文件发送、审批、提问、禁言踢人次数、最近事件。",
1258
+ parameters: { type: "object", properties: {} },
1259
+ async execute() {
1260
+ const result = await adminCall({ action: "stats" })
1261
+ return { ok: result.ok === true, counters: result.counters, events: result.events, error: result.error }
1262
+ },
1263
+ },
1264
+ ]
1265
+
1266
+ // DSH 拒收非无损 JSON(undefined / NaN / Infinity),工具返回值先过一遍
1267
+ const jsonSafe = (value) => {
1268
+ if (value === null) return null
1269
+ const kind = typeof value
1270
+ if (kind === "undefined" || kind === "function" || kind === "symbol") return undefined
1271
+ if (kind === "number") return Number.isFinite(value) ? value : null
1272
+ if (kind === "bigint") return String(value)
1273
+ if (kind !== "object") return value
1274
+ if (Array.isArray(value)) return value.map((item) => {
1275
+ const clean = jsonSafe(item)
1276
+ return clean === undefined ? null : clean
1277
+ })
1278
+ const out = {}
1279
+ for (const [key, item] of Object.entries(value)) {
1280
+ const clean = jsonSafe(item)
1281
+ if (clean !== undefined) out[key] = clean
1282
+ }
1283
+ return out
1284
+ }
1285
+
1286
+ for (const tool of [...infoTools, ...adminTools]) {
1287
+ try {
1288
+ tools.register({
1289
+ ...tool,
1290
+ execute: async (...args) => jsonSafe(await tool.execute(...args)),
1291
+ output: { schema: { type: "object" }, render: (_a, value) => [{ type: "text", text: JSON.stringify(value) }] },
1292
+ })
1293
+ log(`${tool.name} tool registered`)
1294
+ } catch (error) {
1295
+ log(`${tool.name} registration failed: ${error instanceof Error ? error.message : String(error)}`)
1296
+ }
1297
+ }
1298
+ })
1299
+
1300
+ ctx.inject(['sessionController'], (sctx) => {
1301
+ host.sessionController = sctx.sessionController
1302
+ log('sessionController attached')
1303
+ })
1304
+ }