@mcviseron/dsh-qq-bridge 0.0.0-stage → 0.2.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/README.md +39 -2
- package/cordis.patch.yml +16 -0
- package/lib/client.js +372 -0
- package/lib/index.js +1120 -0
- package/lib/server.js +198 -0
- package/lib/store.js +132 -0
- package/package.json +60 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,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 { 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
|
+
}
|