@mcviseron/dsh-qq-bridge 0.2.1 → 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
@@ -11,6 +11,8 @@ import { randomUUID } from 'node:crypto'
11
11
  import { readFileSync } from 'node:fs'
12
12
  import { appendFile, mkdir } from 'node:fs/promises'
13
13
  import { dirname, join, resolve } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+ import { Installer, readInstall, resolveSourceDir } from './install.js'
14
16
  import { HttpBridge } from './server.js'
15
17
  import { ConversationStore } from './store.js'
16
18
 
@@ -118,6 +120,27 @@ export function apply(ctx, rawConfig) {
118
120
  log(`state init failed: ${error instanceof Error ? error.message : String(error)}`)
119
121
  })
120
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
+
121
144
  const stripHints = (line) => {
122
145
  // the bot appends a sticker hint to the prompt; keep it out of the transcript
123
146
  const at = line.indexOf('(想发个表情包时')
@@ -221,7 +244,17 @@ export function apply(ctx, rawConfig) {
221
244
  const id = randomUUID()
222
245
  const labels = options.map((item) => String(item.label ?? item))
223
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)
224
256
  questionPending.set(id, {
257
+ deadline,
225
258
  resolve: (answer) => {
226
259
  const index = Number(answer?.index)
227
260
  const picked = labels[index]
@@ -262,7 +295,7 @@ export function apply(ctx, rawConfig) {
262
295
  }
263
296
 
264
297
  /** Model-facing preamble: where the message came from and who is speaking. */
265
- const composePrompt = ({ text, convKey, senderName, isOwner, chime, quote }) => {
298
+ const composePrompt = ({ text, convKey, senderName, isOwner, chime, quote, persona }) => {
266
299
  const isGroup = convKey.startsWith('group:')
267
300
  const header = isGroup ? 'QQ 群聊' : 'QQ 单聊'
268
301
  const who = isOwner
@@ -299,9 +332,11 @@ export function apply(ctx, rawConfig) {
299
332
  parts.push('', '这条不是点名问你,是你自己决定要不要插话:觉得没必要就只回 [NO_REPLY]。')
300
333
  }
301
334
  parts.push('', isGroup && !isOwner
302
- ? '(这是群聊:像真人一样回 1~3 句口语,别用标题/列表/表格,除非对方明确要步骤。想清楚再说完,不要复述工具过程。)'
335
+ ? '(这是群聊:像真人一样回 1~3 句口语。想清楚再说完,不要复述工具过程。)'
303
336
  : '(先直接回答,别铺垫;默认简短,需要细节时再用 Markdown 展开。)')
304
337
  parts.push('', '(QQ 侧支持 Markdown 渲染:标题/列表/代码块/表格都能用,表情符号可以直接用。要把本地图片或文件发给对方,先把文件写到工作目录里,再在回复里单独一行写 [[send_file: 绝对路径]],机器人会把它作为文件发出。)')
338
+ // 人设只在会话的第一条消息里出现一次,之后靠会话历史记住
339
+ if (typeof persona === 'string' && persona.trim() !== '') parts.push('', '人设:', persona.trim())
305
340
  return parts.join('\n')
306
341
  }
307
342
 
@@ -378,6 +413,23 @@ export function apply(ctx, rawConfig) {
378
413
  conversations: store.size(),
379
414
  pendingApprovals: approvals.size,
380
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
+ },
381
433
  status: () => ({
382
434
  ok: true,
383
435
  cwd: config.cwd,
@@ -445,9 +497,11 @@ export function apply(ctx, rawConfig) {
445
497
  if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
446
498
 
447
499
  let sessionId = store.sessionOf(convKey)
500
+ let freshSession = false
448
501
  if (sessionId === undefined) {
449
502
  const created = await sessionController.create({ cwd: await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot }) })
450
503
  sessionId = String(created.sessionId)
504
+ freshSession = true
451
505
  log(`session created: ${convKey} → ${sessionId}`)
452
506
  }
453
507
  await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
@@ -470,7 +524,9 @@ export function apply(ctx, rawConfig) {
470
524
  selected.add(sessionId)
471
525
  }
472
526
 
473
- const content = [{ type: 'text', text: composePrompt({ text, convKey, senderName, isOwner: body?.isOwner === true, chime: body?.chime === true, quote }) }]
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 }) }]
474
530
  for (const image of images.slice(0, 4)) {
475
531
  const mediaType = typeof image?.mediaType === 'string' ? image.mediaType : ''
476
532
  const data = typeof image?.data === 'string' ? image.data : ''
@@ -525,6 +581,7 @@ export function apply(ctx, rawConfig) {
525
581
  const id = typeof body?.id === 'string' ? body.id : ''
526
582
  if (id === '') return { ok: false, error: 'id required' }
527
583
  const pending = questionPending.get(id)
584
+ if (pending?.deadline) clearTimeout(pending.deadline)
528
585
  if (pending === undefined) return { ok: false, error: 'this question is no longer pending' }
529
586
  questionPending.delete(id)
530
587
  try { pending.resolve(body) } catch (error) { /* already settled */ }
@@ -679,15 +736,24 @@ export function apply(ctx, rawConfig) {
679
736
  }, 90000)
680
737
  })
681
738
 
739
+ const threshold = Number.isFinite(Number(body?.threshold)) ? Number(body.threshold) : 2
740
+ const hint = typeof body?.hint === 'string' ? body.hint.trim() : ''
682
741
  const instruction = [
683
- '【群聊插话判断器】你是一个独立判断器,不参与聊天,只做判断。',
684
- '下面是这个群里最近的消息原文(每行 发言人: 内容):',
742
+ '【群聊插话判断器】你就是这个群里的一员,只做决定:接一句,还是不说。',
743
+ '默认接一句(口语、1~2 句)。只有这三种情况才不说:',
744
+ '① 明显是两个人一对一搭话,既没提到你也没什么可加;',
745
+ '② 你刚说过同类的话;',
746
+ '③ 这条只是表情/图片/链接/单字,没有可回应的内容。',
747
+ '其余情况(抛观点、吐槽、问问题、接梗)都可以接;话题不熟也可以轻接。',
748
+ hint,
749
+ '',
750
+ '群里的原文(每行 发言人: 内容):',
685
751
  transcript,
686
752
  '',
687
- '判断现在是否需要一个机器人插话/回答。只输出两行:',
688
- '第一行:REPLY 或 SKIP',
689
- '第二行:一句话理由(不超过40字)',
690
- ].join('\n')
753
+ '输出格式(严格两行):',
754
+ '第一行:[[join: 0~3]](3=必须接,2=想接,1=可接可不接,0=不说)',
755
+ '第二行:一句话理由(不超过 40 字)',
756
+ ].filter(line => line !== '').join('\n')
691
757
 
692
758
  try {
693
759
  await sessionController.prompt({
@@ -705,12 +771,19 @@ export function apply(ctx, rawConfig) {
705
771
  const answer = String(await verdict)
706
772
  const lines = answer.split('\n').map(line => line.trim()).filter(line => line !== '')
707
773
  const head = (lines[0] ?? '').toUpperCase()
708
- const needReply = head.startsWith('REPLY')
709
- const decisive = head.startsWith('REPLY') || head.startsWith('SKIP')
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(' ')
710
781
  return {
711
782
  ok: decisive,
712
783
  needReply,
713
- note: lines.slice(1).join(' ').slice(0, 200),
784
+ score,
785
+ threshold,
786
+ note: noteSource.trim().split('\n').map(line => line.trim()).filter(line => line !== '').join(' ').slice(0, 200),
714
787
  raw: answer.slice(0, 200),
715
788
  }
716
789
  },
@@ -736,9 +809,13 @@ export function apply(ctx, rawConfig) {
736
809
  // panel unreachable -> the supervisor is gone, start it
737
810
  }
738
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
739
816
  const { spawn } = await import('node:child_process')
740
- const child = spawn(config.pythonPath, ['-u', 'main.py', '--supervise'], {
741
- cwd: config.botDir,
817
+ const child = spawn(pythonPath, ['-u', 'main.py', '--supervise'], {
818
+ cwd: botDir,
742
819
  detached: true,
743
820
  stdio: 'ignore',
744
821
  windowsHide: true,
@@ -994,6 +1071,18 @@ export function apply(ctx, rawConfig) {
994
1071
  for (const [tail, info] of Object.entries(known)) {
995
1072
  if (raw.length >= 4 && tail.toUpperCase().includes(raw)) return info?.openid ?? info
996
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
+ }
997
1086
  if (/^[0-9A-F]{32}$/.test(raw)) return raw
998
1087
  return undefined
999
1088
  }
@@ -1009,7 +1098,15 @@ export function apply(ctx, rawConfig) {
1009
1098
  const people = convKey !== "" ? { [convKey]: all[convKey] || {} } : all
1010
1099
  const lines = []
1011
1100
  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 })
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
+ }
1013
1110
  }
1014
1111
  return { ok: true, count: lines.length, members: lines }
1015
1112
  },
@@ -1035,7 +1132,7 @@ export function apply(ctx, rawConfig) {
1035
1132
  const raw = Number(args?.minutes)
1036
1133
  const minutes = Number.isFinite(raw) ? raw : 10
1037
1134
  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 })
1135
+ const result = await adminCall({ action: "mute", convKey, group, member: openid, seconds })
1039
1136
  return {
1040
1137
  ok: result.ok === true,
1041
1138
  member: args?.member,
@@ -1061,7 +1158,7 @@ export function apply(ctx, rawConfig) {
1061
1158
  const openid = resolveMember(convKey, args?.member)
1062
1159
  if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1063
1160
  const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1064
- const result = await adminCall({ action: "mute", group, member: openid, seconds: 0 })
1161
+ const result = await adminCall({ action: "mute", convKey, group, member: openid, seconds: 0 })
1065
1162
  return { ok: result.ok === true, member: args?.member, op: "del", error: result.error }
1066
1163
  },
1067
1164
  },
@@ -1076,7 +1173,7 @@ export function apply(ctx, rawConfig) {
1076
1173
  async execute(args) {
1077
1174
  const convKey = String(args?.convKey || "")
1078
1175
  const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1079
- const result = await adminCall({ action: "mute_state", group })
1176
+ const result = await adminCall({ action: "mute_state", convKey, group })
1080
1177
  return { ok: result.ok === true, state: result.state, error: result.error }
1081
1178
  },
1082
1179
  },
@@ -1097,15 +1194,102 @@ export function apply(ctx, rawConfig) {
1097
1194
  const openid = resolveMember(convKey, args?.member)
1098
1195
  if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
1099
1196
  const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
1100
- const result = await adminCall({ action: "kick", group, member: openid, blacklist: args?.blacklist === true })
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
+ }
1101
1208
  return { ok: result.ok === true, member: args?.member, error: result.error }
1102
1209
  },
1103
1210
  },
1104
1211
  ]
1105
1212
 
1106
- for (const tool of adminTools) {
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]) {
1107
1287
  try {
1108
- tools.register({ ...tool, output: { schema: { type: "object" }, render: (_a, value) => [{ type: "text", text: JSON.stringify(value) }] } })
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
+ })
1109
1293
  log(`${tool.name} tool registered`)
1110
1294
  } catch (error) {
1111
1295
  log(`${tool.name} registration failed: ${error instanceof Error ? error.message : String(error)}`)