dsh-qq-affinity 1.0.0 → 1.5.6

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/api.js CHANGED
@@ -8,11 +8,12 @@ import fs from 'node:fs'
8
8
  import path from 'node:path'
9
9
  import { clamp, isAiAuthored, styleReply } from './util.js'
10
10
  import { parseTranscript } from './parse.js'
11
- import { scorePerson, suggestReplies, analyzePersona, analyzeSelf } from './analyze.js'
11
+ import { scorePerson, suggestReplies, analyzePersona, analyzeSelf, analyzeGroup } from './analyze.js'
12
12
  import { routeFor } from './llm.js'
13
13
  import { modelSeesImages } from './vision.js'
14
14
  import { measure } from './features.js'
15
15
  import { defaultCare } from './store.js'
16
+ import { listPersonas, presetPersona } from './personas.js'
16
17
  import { probe, send as sendThroughBridge } from './onebot.js'
17
18
  import { describeLocation, expandPath, relocate, resetLocation } from './home.js'
18
19
  import { backfillAll, backfillConversation, AUTO_BACKFILL_COUNT } from './backfill.js'
@@ -134,7 +135,7 @@ function personView(store, uin, transcripts) {
134
135
  }
135
136
 
136
137
  /** Build the whole panel snapshot, reading each enabled transcript once. */
137
- function stateOf(store, engine, bridgeStatus = {}) {
138
+ function stateOf(store, engine, bridgeStatus = {}, tasks = undefined) {
138
139
  // Reading every transcript once keeps this snapshot linear instead of
139
140
  // re-scanning the store for each person it lists.
140
141
  const transcripts = store.state.conversations
@@ -181,7 +182,19 @@ function stateOf(store, engine, bridgeStatus = {}) {
181
182
  bridgeError: bridgeStatus.error ?? '',
182
183
  },
183
184
  careAutoActive: Object.values(store.state.care).filter(entry => entry.enabled === true && entry.mode === 'auto').length,
185
+ // What the plugin is busy with right now, oldest first. The registry is
186
+ // optional: a bare route set (tests, or a host without one) simply has none.
187
+ // A registry failure must never take the whole snapshot down with it.
188
+ tasks: (() => {
189
+ try {
190
+ return tasks === undefined || tasks === null ? [] : tasks.list()
191
+ } catch {
192
+ return []
193
+ }
194
+ })(),
184
195
  pinned: store.state.pinned.slice(),
196
+ // The reply-persona picker: built-in presets plus whatever the user added.
197
+ replyPersonas: listPersonas(store.state.replyPersonas),
185
198
  selfProfile: store.selfProfile(),
186
199
  // Comparing the two versions is how a stale client bundle exposes itself.
187
200
  versions: {
@@ -196,6 +209,8 @@ function stateOf(store, engine, bridgeStatus = {}) {
196
209
  // Only an enabled conversation is read; the panel mirrors that in the UI.
197
210
  readable: row.enabled === true,
198
211
  aiAuthored: outbox.filter(entry => entry.conversationId === row.id && entry.status === 'sent').length,
212
+ // Group rooms carry their own analysis; private chats do not.
213
+ groupProfile: row.kind === 'group' ? (store.groupProfile(row.id) ?? null) : null,
199
214
  })),
200
215
  people,
201
216
  adoptions: store.state.adoptions.map(row => ({
@@ -224,6 +239,23 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
224
239
  }
225
240
  const bridgeStatus = bridge ?? { listening: false, port: 0, url: '', error: 'not started' }
226
241
  if (overrides.version !== undefined) bridgeStatus.version = overrides.version
242
+ // One registry for the panel: every slow operation in this file reports into it.
243
+ const tasks = overrides.tasks ?? null
244
+ const taskOf = (info) => (tasks === null ? '' : tasks.begin(info))
245
+ const taskDone = (id, error = '') => { if (tasks !== null && id !== '') tasks.finish(id, error) }
246
+ const taskStep = (id, patch) => { if (tasks !== null && id !== '') tasks.update(id, patch) }
247
+ /** Run one slow operation as a tracked task, recording how it ended. */
248
+ const tracked = async (info, work) => {
249
+ const id = taskOf(info)
250
+ try {
251
+ const value = await work()
252
+ taskDone(id)
253
+ return value
254
+ } catch (error) {
255
+ taskDone(id, error instanceof Error ? error.message : String(error))
256
+ throw error
257
+ }
258
+ }
227
259
 
228
260
  /**
229
261
  * The batch refresh job. In-memory only: a plugin reload resets it, and the
@@ -271,6 +303,10 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
271
303
  .filter(uin => privateUins.has(uin))
272
304
  .sort((left, right) => (store.state.people[right]?.messageCount ?? 0) - (store.state.people[left]?.messageCount ?? 0))
273
305
  refreshJob.total = targets.length
306
+ const batchTask = taskOf({ kind: 'refresh', label: '批量更新', total: targets.length })
307
+ if (tasks !== null && batchTask !== '') {
308
+ tasks.setQueue(batchTask, targets.slice(0, 8).map(uin => store.state.people[uin]?.names?.slice(-1)[0] ?? uin))
309
+ }
274
310
  let cursor = 0
275
311
  const worker = async () => {
276
312
  while (cursor < targets.length) {
@@ -278,6 +314,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
278
314
  const uin = targets[cursor]
279
315
  cursor += 1
280
316
  refreshJob.current = uin
317
+ taskStep(batchTask, {
318
+ done: refreshJob.done,
319
+ total: targets.length,
320
+ detail: store.state.people[uin]?.names?.slice(-1)[0] ?? uin,
321
+ })
281
322
  const outcome = { uin, score: false, persona: false, error: '' }
282
323
  try {
283
324
  await scorePerson(ctx, store, uin, { signal: refreshJob.abort.signal })
@@ -302,6 +343,8 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
302
343
  }
303
344
  // Two at a time: faster than one, still polite to the model provider.
304
345
  await Promise.all([worker(), worker()])
346
+ const cancelled = refreshJob.running !== true && refreshJob.done < refreshJob.total
347
+ taskDone(batchTask, cancelled ? '已手动停止' : '')
305
348
  refreshJob.running = false
306
349
  refreshJob.current = ''
307
350
  }
@@ -359,7 +402,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
359
402
  bridgeStatus.lastSeenClient = version
360
403
  appendArchiveLog(store, 'client.log', `state v=${version === '' ? '(none)' : version.slice(0, 24)}`)
361
404
  }
362
- const snapshot = stateOf(store, engine, bridgeStatus)
405
+ const snapshot = stateOf(store, engine, bridgeStatus, tasks)
363
406
  // Resolving model capability is a round trip; one answer per few seconds
364
407
  // is plenty for a panel that polls.
365
408
  const now = Date.now()
@@ -449,7 +492,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
449
492
  if (bridge.apiBase !== before.apiBase || bridge.accessToken !== before.accessToken) bridge.enabled = false
450
493
  }
451
494
  store.save()
452
- return json(stateOf(store, engine, bridgeStatus))
495
+ return json(stateOf(store, engine, bridgeStatus, tasks))
453
496
  }),
454
497
  },
455
498
  {
@@ -483,7 +526,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
483
526
  note: outcome.mode === 'migrate' && outcome.cleanup !== true
484
527
  ? `原来的数据仍留在 ${outcome.previous},确认新位置没问题后可以手动删除。`
485
528
  : '',
486
- state: stateOf(store, engine, bridgeStatus),
529
+ state: stateOf(store, engine, bridgeStatus, tasks),
487
530
  })
488
531
  }),
489
532
  },
@@ -499,12 +542,12 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
499
542
  if (action === 'toggle') {
500
543
  const isPinned = store.state.pinned.includes(id)
501
544
  const pinned = isPinned ? store.unpin(id) : store.pin(id)
502
- return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus) })
545
+ return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus, tasks) })
503
546
  }
504
547
  if (action === 'move') {
505
548
  const delta = Math.round(Number(body.delta))
506
549
  const pinned = store.movePinned(id, Number.isFinite(delta) ? delta : 0)
507
- return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus) })
550
+ return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus, tasks) })
508
551
  }
509
552
  return fail(`未知操作:${action}`)
510
553
  }),
@@ -518,7 +561,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
518
561
  fetch: guard(async (request) => {
519
562
  const body = await readBody(request)
520
563
  const action = textField(body.action, 20)
521
- if (action === 'status') return json({ ok: true, job: jobView(), state: stateOf(store, engine, bridgeStatus) })
564
+ if (action === 'status') return json({ ok: true, job: jobView(), state: stateOf(store, engine, bridgeStatus, tasks) })
522
565
  if (action === 'cancel') {
523
566
  if (!refreshJob.running) return fail('当前没有正在进行的更新。', 409)
524
567
  refreshJob.running = false
@@ -559,7 +602,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
559
602
  return fail('保存顺序失败。', 500)
560
603
  }
561
604
  logOrder(store, `saved ${kind} count=${ordered.length}`)
562
- return json({ ok: true, kind, order: ordered, state: stateOf(store, engine, bridgeStatus) })
605
+ return json({ ok: true, kind, order: ordered, state: stateOf(store, engine, bridgeStatus, tasks) })
563
606
  }),
564
607
  },
565
608
  {
@@ -571,12 +614,51 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
571
614
  const uin = textField(body.uin, 24).replace(/\D/g, '')
572
615
  if (uin === '') return fail('缺少 QQ 号。')
573
616
  if (store.person(uin) === undefined) return fail(`还没有 QQ ${uin} 的档案,先导入并开启一个包含 TA 的对话。`, 404)
617
+ // Zero this person's hourly reply count (the manual escape hatch when the
618
+ // cap has already ended a conversation).
619
+ if (textField(body.action, 20) === 'reset-count') {
620
+ const resetAt = store.resetCareCount(uin)
621
+ return json({
622
+ ok: true,
623
+ resetAt,
624
+ care: store.careFor(uin) ?? defaultCare(),
625
+ state: stateOf(store, engine, bridgeStatus, tasks),
626
+ })
627
+ }
574
628
  if (body.patch !== null && typeof body.patch === 'object' && body.patch.enabled === true) {
575
629
  if (store.state.settings.selfUin === '') return fail('请先填写你的 QQ 号,托管需要用它在回复时区分身份。', 409, { needsSelfUin: true })
576
630
  }
577
631
  const care = store.setCare(uin, body.patch !== null && typeof body.patch === 'object' ? body.patch : {})
578
632
  if (care === undefined) return fail('保存失败。', 500)
579
- return json({ ok: true, care, state: stateOf(store, engine, bridgeStatus) })
633
+ return json({ ok: true, care, state: stateOf(store, engine, bridgeStatus, tasks) })
634
+ }),
635
+ },
636
+ {
637
+ // The open interface for adding a reply persona of the user's own.
638
+ path: '/api/qq-affinity/personas',
639
+ method: 'POST',
640
+ requestBody: 'buffered',
641
+ fetch: guard(async (request) => {
642
+ const body = await readBody(request)
643
+ const action = textField(body.action, 20)
644
+ if (action === 'add') {
645
+ const entry = store.addReplyPersona({ name: body.name, prompt: body.prompt })
646
+ if (entry === undefined) return fail('人设名和描述都不能为空。')
647
+ return json({ ok: true, persona: entry, personas: listPersonas(store.state.replyPersonas), state: stateOf(store, engine, bridgeStatus, tasks) })
648
+ }
649
+ if (action === 'delete') {
650
+ const id = textField(body.id, 60)
651
+ if (id === '') return fail('缺少人设 id。')
652
+ if (presetPersona(id) !== undefined) return fail('内置预设不能删除。', 409)
653
+ if (!store.removeReplyPersona(id)) return fail('找不到这个人设。', 404)
654
+ // Anyone using it falls back to the default voice on the next reply.
655
+ const fallback = Object.entries(store.state.care)
656
+ .filter(([, entry]) => entry.persona === id)
657
+ .map(([uin]) => uin)
658
+ for (const uin of fallback) store.setCare(uin, { persona: 'default' })
659
+ return json({ ok: true, personas: listPersonas(store.state.replyPersonas), resetTo: fallback, state: stateOf(store, engine, bridgeStatus, tasks) })
660
+ }
661
+ return fail(`未知操作:${action}`)
580
662
  }),
581
663
  },
582
664
  {
@@ -627,7 +709,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
627
709
  return json({
628
710
  ok: true,
629
711
  login: info,
630
- state: stateOf(store, engine, bridgeStatus),
712
+ state: stateOf(store, engine, bridgeStatus, tasks),
631
713
  })
632
714
  } catch (error) {
633
715
  store.state.settings.onebot.enabled = false
@@ -656,9 +738,16 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
656
738
  if (conversationId !== '') {
657
739
  const conversation = store.conversation(conversationId)
658
740
  if (conversation === undefined) return fail('找不到这个对话。', 404)
659
- reports = [await backfillConversation({ store, bridge, conversation, count })]
741
+ reports = await tracked(
742
+ { kind: 'backfill', label: '同步已载入消息', detail: conversation.title === '' ? conversationId : conversation.title },
743
+ async () => [await deps.backfill({ store, bridge, conversation, count })],
744
+ )
660
745
  } else {
661
- reports = await backfillAll({ store, bridge, count })
746
+ const enabledCount = store.state.conversations.filter(row => row.enabled === true).length
747
+ reports = await tracked(
748
+ { kind: 'backfill', label: '同步全部已载入消息', total: enabledCount },
749
+ () => backfillAll({ store, bridge, count }),
750
+ )
662
751
  }
663
752
 
664
753
  if (reports.length > 0 && reports.some(report => report.fetched > 0)) {
@@ -676,7 +765,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
676
765
  note: failed.length === 0
677
766
  ? `补齐完成,新增 ${added} 条。`
678
767
  : `${reports.length - failed.length} 个对话补齐,另 ${failed.length} 个没成功:${failed[0].error}`,
679
- state: stateOf(store, engine, bridgeStatus),
768
+ state: stateOf(store, engine, bridgeStatus, tasks),
680
769
  })
681
770
  }),
682
771
  },
@@ -705,11 +794,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
705
794
  const action = textField(body.action, 20)
706
795
  if (action === 'approve') {
707
796
  const row = await engine.approve(id)
708
- return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus) })
797
+ return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus, tasks) })
709
798
  }
710
799
  if (action === 'cancel') {
711
800
  const row = engine.cancel(id)
712
- return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus) })
801
+ return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus, tasks) })
713
802
  }
714
803
  return fail(`未知操作:${action}`)
715
804
  }),
@@ -737,7 +826,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
737
826
  created,
738
827
  conversation: store.conversation(conversation.id),
739
828
  autoPull: pull,
740
- state: stateOf(store, engine, bridgeStatus),
829
+ state: stateOf(store, engine, bridgeStatus, tasks),
741
830
  })
742
831
  }
743
832
  const id = textField(body.id, 80)
@@ -751,7 +840,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
751
840
  ok: true,
752
841
  conversation: store.conversation(id),
753
842
  autoPull: pull,
754
- state: stateOf(store, engine, bridgeStatus),
843
+ state: stateOf(store, engine, bridgeStatus, tasks),
755
844
  })
756
845
  }
757
846
  if (action === 'update') {
@@ -760,11 +849,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
760
849
  peerUin: typeof body.peerUin === 'string' ? body.peerUin : undefined,
761
850
  groupUin: typeof body.groupUin === 'string' ? body.groupUin : undefined,
762
851
  })
763
- return json({ ok: true, conversation: store.conversation(id), state: stateOf(store, engine, bridgeStatus) })
852
+ return json({ ok: true, conversation: store.conversation(id), state: stateOf(store, engine, bridgeStatus, tasks) })
764
853
  }
765
854
  if (action === 'remove') {
766
855
  store.removeConversation(id)
767
- return json({ ok: true, state: stateOf(store, engine, bridgeStatus) })
856
+ return json({ ok: true, state: stateOf(store, engine, bridgeStatus, tasks) })
768
857
  }
769
858
  return fail(`未知操作:${action}`)
770
859
  }),
@@ -842,7 +931,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
842
931
  stats: parsed.stats,
843
932
  totalMessages: after,
844
933
  adoptedMatched: matched,
845
- state: stateOf(store, engine, bridgeStatus),
934
+ state: stateOf(store, engine, bridgeStatus, tasks),
846
935
  })
847
936
  }),
848
937
  },
@@ -855,9 +944,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
855
944
  const uin = textField(body.uin, 24).replace(/\D/g, '')
856
945
  if (uin === '') return fail('缺少 QQ 号。')
857
946
  if (store.person(uin) === undefined) return fail(`没有关于 QQ ${uin} 的任何记录。`, 404)
858
- const result = await scorePerson(ctx, store, uin, { force: body.force === true })
859
- return json({ ok: true, score: result, state: stateOf(store, engine, bridgeStatus) })
860
- }),
947
+ const result = await tracked(
948
+ { kind: 'score', label: '好感度分析', detail: store.person(uin)?.names?.slice(-1)[0] ?? uin },
949
+ () => scorePerson(ctx, store, uin, { force: body.force === true }),
950
+ )
951
+ return json({ ok: true, score: result, state: stateOf(store, engine, bridgeStatus, tasks) }) }),
861
952
  },
862
953
  {
863
954
  path: '/api/qq-affinity/self',
@@ -866,8 +957,8 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
866
957
  fetch: guard(async (request) => {
867
958
  // A body is optional here: the panel may ask for a plain analysis.
868
959
  const body = await readBody(request).catch(() => ({}))
869
- const profile = await analyzeSelf(ctx, store, { force: body?.force === true })
870
- return json({ ok: true, selfProfile: profile, state: stateOf(store, engine, bridgeStatus) })
960
+ const profile = await tracked({ kind: 'self', label: '自我分析' }, () => analyzeSelf(ctx, store, { force: body?.force === true }))
961
+ return json({ ok: true, selfProfile: profile, state: stateOf(store, engine, bridgeStatus, tasks) })
871
962
  }),
872
963
  },
873
964
  {
@@ -882,6 +973,24 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
882
973
  return json({ ok: true })
883
974
  }),
884
975
  },
976
+ {
977
+ path: '/api/qq-affinity/group',
978
+ method: 'POST',
979
+ requestBody: 'buffered',
980
+ fetch: guard(async (request) => {
981
+ const body = await readBody(request)
982
+ const conversationId = textField(body.conversationId, 80)
983
+ if (conversationId === '') return fail('缺少对话 id。')
984
+ const conversation = store.conversation(conversationId)
985
+ if (conversation === undefined) return fail('找不到这个对话。', 404)
986
+ if (conversation.kind !== 'group') return fail('只有群聊才有群聊分析。', 400)
987
+ const result = await tracked(
988
+ { kind: 'group', label: '群聊分析', detail: conversation.title === '' ? conversation.groupUin : conversation.title },
989
+ () => analyzeGroup(ctx, store, conversationId, { force: body.force === true }),
990
+ )
991
+ return json({ ok: true, group: result, state: stateOf(store, engine, bridgeStatus, tasks) })
992
+ }),
993
+ },
885
994
  {
886
995
  path: '/api/qq-affinity/persona',
887
996
  method: 'POST',
@@ -891,8 +1000,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
891
1000
  const uin = textField(body.uin, 24).replace(/\D/g, '')
892
1001
  if (uin === '') return fail('缺少 QQ 号。')
893
1002
  if (store.person(uin) === undefined) return fail(`没有关于 QQ ${uin} 的任何记录。`, 404)
894
- const result = await analyzePersona(ctx, store, uin, { force: body.force === true })
895
- return json({ ok: true, persona: result, state: stateOf(store, engine, bridgeStatus) })
1003
+ const result = await tracked(
1004
+ { kind: 'persona', label: '人格画像', detail: store.person(uin)?.names?.slice(-1)[0] ?? uin },
1005
+ () => analyzePersona(ctx, store, uin, { force: body.force === true }),
1006
+ )
1007
+ return json({ ok: true, persona: result, state: stateOf(store, engine, bridgeStatus, tasks) })
896
1008
  }),
897
1009
  },
898
1010
  {
@@ -902,7 +1014,10 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
902
1014
  fetch: guard(async (request) => {
903
1015
  const body = await readBody(request)
904
1016
  const conversationId = textField(body.conversationId, 80)
905
- const batch = await suggestReplies(ctx, store, conversationId)
1017
+ const batch = await tracked(
1018
+ { kind: 'suggest', label: '生成回复建议', detail: store.conversation(conversationId)?.title ?? conversationId },
1019
+ () => suggestReplies(ctx, store, conversationId),
1020
+ )
906
1021
  return json({ ok: true, batch, batches: store.suggestions(conversationId) })
907
1022
  }),
908
1023
  },