dsh-qq-affinity 0.15.2 → 1.0.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/client.js CHANGED
@@ -20,7 +20,7 @@ window.__ModuleLoader__.load({
20
20
  * This bundle's version. The Host reports its own; when the two differ the
21
21
  * panel says so, because a stale bundle otherwise looks like a broken button.
22
22
  */
23
- const VERSION = '0.15.0'
23
+ const VERSION = '0.15.3'
24
24
 
25
25
  // ---------------------------------------------------------------- palette
26
26
 
package/lib/analyze.js CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { score as clampScore, clamp, isAiAuthored, formatTime, styleReply } from './util.js'
14
- import { lastInbound, measure, renderTranscript, rowsForPerson } from './features.js'
14
+ import { lastInbound, measure, renderTranscript, rowsForPerson, GROUP_UNMENTIONED_WEIGHT } from './features.js'
15
15
  import { completeText, extractJson, routeFor } from './llm.js'
16
16
  import { collectImageBlocks, imagesOf, modelSeesImages } from './vision.js'
17
17
 
@@ -118,6 +118,12 @@ function visionBlock(vision) {
118
118
  /** Render the measurement block for the prompt. */
119
119
  function measurementBlock(features, extra = {}) { return [
120
120
  `总消息数 ${features.totalMessages}(对方 ${features.theirMessages} / 我 ${features.myMessages},其中我的真实表达 ${features.myAuthenticMessages} 条、AI代笔 ${features.aiAdoptedMessages} 条)`,
121
+ features.theirUnaddressedGroupMessages === undefined || features.theirUnaddressedGroupMessages === 0
122
+ ? ''
123
+ : `⚠ 对方有 ${features.theirUnaddressedGroupMessages} 条群聊消息没有 @ 我(占他全部发言的 ${Math.round(features.theirUnaddressedGroupMessages / Math.max(1, features.theirMessages) * 100)}%):这些很可能不是说给我听的,按 ${Math.round(GROUP_UNMENTIONED_WEIGHT * 100)}% 权重计入,下面的行为统计只按「真正对我说的话」重算过。`,
124
+ features.theirAddressedMessages === undefined
125
+ ? ''
126
+ : `对方真正对我说的话 ${features.theirAddressedMessages} 条(私聊 + 群里 @ 我),加权后相当于 ${features.theirWeightedMessages} 条。`,
121
127
  `平均字数:对方 ${features.theirAvgChars} / 我 ${features.myAvgChars}`,
122
128
  `提问率:对方 ${features.theirQuestionRatio} / 我 ${features.myQuestionRatio}`,
123
129
  `每条消息的颜文字或表情标记数:对方 ${features.theirDecorationPerMessage} / 我 ${features.myDecorationPerMessage}`,
@@ -126,7 +132,7 @@ function measurementBlock(features, extra = {}) { return [
126
132
  `对方深夜(23:00-05:00)消息占比 ${features.theirNightRatio},连续追问 ${features.theirDoubleTextCount} 次`,
127
133
  `覆盖天数 ${features.spanDays},活跃天数 ${features.activeDays},距最后一条消息 ${features.lastContactDays ?? '—'} 天`,
128
134
  ...(extra.lines ?? []),
129
- ].join('\n')
135
+ ].filter(line => line !== '').join('\n')
130
136
  }
131
137
 
132
138
  /** Find one person row, with a readable display name. */
@@ -248,6 +254,8 @@ export async function scorePerson(ctx, store, uin, options = {}) {
248
254
  '字段含义:',
249
255
  'theirFavor = 对方对我的好感度;myFavor = 我对对方的好感度;intimacy = 我们的亲密度(熟悉、放松、互相接得住的程度)。',
250
256
  'My favor 必须只由我的真实表达推出;如果我的真实表达很少,就明确说明证据不足并给较低 confidence。',
257
+ '群聊纪律:对方在群里没有 @ 我的发言,多数不是对我说的(转写里标了「群里未点名」)。判断 theirFavor 时这些只能算很弱的旁证——'
258
+ + '不要把「他在群里聊得热闹」当成「他对我热情」,也不要把「他在群里没理我」当成冷落。',
251
259
  )
252
260
 
253
261
  // Look at the newest pictures only when both the user and the model allow it.
package/lib/features.js CHANGED
@@ -14,6 +14,16 @@ const SIX_HOURS = 6 * 60 * 60 * 1000
14
14
  const EMOJI = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{FE0F}\u{2764}]/gu
15
15
  const STICKER = /\[(表情|图片|动画表情|贴图|视频|语音|文件|红包|转账)\]/g
16
16
 
17
+ /**
18
+ * How much one group message that did not @ me counts towards "their favour".
19
+ *
20
+ * In a group, a line nobody addressed to me is usually aimed at someone else, so
21
+ * counting it like a private message inflates the number badly. It is kept as
22
+ * weak evidence rather than dropped: they still chose to speak that way in front
23
+ * of me.
24
+ */
25
+ export const GROUP_UNMENTIONED_WEIGHT = 0.25
26
+
17
27
  /** Median of a numeric list, or 0. */
18
28
  function median(values) {
19
29
  if (values.length === 0) return 0
@@ -54,15 +64,24 @@ function hourOf(ts) {
54
64
  */
55
65
  export function rowsForPerson(store, targetUin) {
56
66
  const enabled = new Set(store.enabledConversationIds())
67
+ const selfUin = String(store.state.settings.selfUin ?? '')
57
68
  const rows = []
58
69
  for (const conversation of store.state.conversations) {
59
70
  if (!enabled.has(conversation.id)) continue
60
71
  const concernsTarget = conversation.peerUin === targetUin
61
72
  || (conversation.participants ?? []).includes(targetUin)
62
73
  if (!concernsTarget) continue
74
+ const isGroup = conversation.kind === 'group'
63
75
  for (const row of store.messages(conversation.id)) {
64
76
  if (row.senderUin === targetUin || row.direction === 'out') {
65
- rows.push({ ...row, conversationId: conversation.id })
77
+ // `atMe` decides the weight later: in a group, a line that never names me
78
+ // is probably a conversation with somebody else.
79
+ rows.push({
80
+ ...row,
81
+ conversationId: conversation.id,
82
+ group: isGroup,
83
+ atMe: selfUin !== '' && String(row.text ?? '').includes(`@${selfUin}`),
84
+ })
66
85
  }
67
86
  }
68
87
  }
@@ -81,9 +100,17 @@ export function measure(rows, targetUin) {
81
100
  const mine = rows.filter(row => row.direction === 'out')
82
101
  const mineAuthentic = mine.filter(row => !isAiAuthored(row))
83
102
 
84
- const theirQuestions = theirs.filter(row => isQuestion(row.text)).length
103
+ // In a group, only the lines that named me count as addressed to me. The rest
104
+ // still appear in the transcript, but they cannot carry the same weight in a
105
+ // "how do they feel about me" verdict.
106
+ const theirAddressed = theirs.filter(row => row.group !== true || row.atMe === true)
107
+ const theirUnaddressed = theirs.filter(row => row.group === true && row.atMe !== true)
108
+ // One number for the prompt: addressed lines at full weight, the rest discounted.
109
+ const theirWeighted = Math.round((theirAddressed.length + theirUnaddressed.length * GROUP_UNMENTIONED_WEIGHT) * 100) / 100
110
+
111
+ const theirQuestions = theirAddressed.filter(row => isQuestion(row.text)).length
85
112
  const myQuestions = mineAuthentic.filter(row => isQuestion(row.text)).length
86
- const theirDecoration = theirs.reduce((total, row) => total + decorationCount(row.text), 0)
113
+ const theirDecoration = theirAddressed.reduce((total, row) => total + decorationCount(row.text), 0)
87
114
  const myDecoration = mineAuthentic.reduce((total, row) => total + decorationCount(row.text), 0)
88
115
 
89
116
  // Initiative: a message that lands more than half an hour after anything else starts a burst.
@@ -103,7 +130,7 @@ export function measure(rows, targetUin) {
103
130
  if (row.senderUin === targetUin && previous.direction === 'out') theirReplies.push(gap)
104
131
  }
105
132
 
106
- const theirNight = theirs.filter(row => hourOf(row.ts) >= 23 || hourOf(row.ts) < 5).length
133
+ const theirNight = theirAddressed.filter(row => hourOf(row.ts) >= 23 || hourOf(row.ts) < 5).length
107
134
  const activeDays = new Set(rows.map(row => new Date(row.ts).toDateString())).size
108
135
  const spanDays = rows.length === 0
109
136
  ? 0
@@ -120,20 +147,26 @@ export function measure(rows, targetUin) {
120
147
  return {
121
148
  totalMessages: rows.length,
122
149
  theirMessages: theirs.length,
150
+ /** Their lines that were actually aimed at me: private, or an @ in a group. */
151
+ theirAddressedMessages: theirAddressed.length,
152
+ /** Group lines that never named me — weak evidence only. */
153
+ theirUnaddressedGroupMessages: theirUnaddressed.length,
154
+ /** Addressed at full weight plus the unaddressed ones at GROUP_UNMENTIONED_WEIGHT. */
155
+ theirWeightedMessages: theirWeighted,
123
156
  myMessages: mine.length,
124
157
  myAuthenticMessages: mineAuthentic.length,
125
158
  aiAdoptedMessages: mine.length - mineAuthentic.length,
126
- theirAvgChars: mean(theirs.map(row => row.text.length)),
159
+ theirAvgChars: mean(theirAddressed.map(row => row.text.length)),
127
160
  myAvgChars: mean(mineAuthentic.map(row => row.text.length)),
128
- theirQuestionRatio: theirs.length === 0 ? 0 : Math.round((theirQuestions / theirs.length) * 100) / 100,
161
+ theirQuestionRatio: theirAddressed.length === 0 ? 0 : Math.round((theirQuestions / theirAddressed.length) * 100) / 100,
129
162
  myQuestionRatio: mineAuthentic.length === 0 ? 0 : Math.round((myQuestions / mineAuthentic.length) * 100) / 100,
130
- theirDecorationPerMessage: theirs.length === 0 ? 0 : Math.round((theirDecoration / theirs.length) * 100) / 100,
163
+ theirDecorationPerMessage: theirAddressed.length === 0 ? 0 : Math.round((theirDecoration / theirAddressed.length) * 100) / 100,
131
164
  myDecorationPerMessage: mineAuthentic.length === 0 ? 0 : Math.round((myDecoration / mineAuthentic.length) * 100) / 100,
132
- theirInitiativeRatio: theirs.length === 0 ? 0 : Math.round((theirInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
165
+ theirInitiativeRatio: theirAddressed.length === 0 ? 0 : Math.round((theirInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
133
166
  myInitiativeRatio: mineAuthentic.length === 0 ? 0 : Math.round((myInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
134
167
  theirMedianReplySeconds: Math.round(median(theirReplies) / 1000),
135
168
  myMedianReplySeconds: Math.round(median(myReplies.filter((_, index) => index < mineAuthentic.length)) / 1000),
136
- theirNightRatio: theirs.length === 0 ? 0 : Math.round((theirNight / theirs.length) * 100) / 100,
169
+ theirNightRatio: theirAddressed.length === 0 ? 0 : Math.round((theirNight / theirAddressed.length) * 100) / 100,
137
170
  theirDoubleTextCount: theirBursts,
138
171
  activeDays,
139
172
  spanDays,
@@ -169,8 +202,11 @@ export function renderTranscript(rows, options) {
169
202
  if (excludeAdopted && isAiAuthored(row)) continue
170
203
  const who = row.senderUin === targetUin ? targetName : '我'
171
204
  const marker = isAiAuthored(row) && markAdopted ? '(AI代笔)' : ''
205
+ // A group line nobody addressed to me is not a message to me; saying so in
206
+ // the transcript is what lets the model discount it.
207
+ const aside = row.group === true && row.senderUin === targetUin && row.atMe !== true ? '(群里未点名)' : ''
172
208
  const body = truncate(String(row.text).replace(/\n+/g, ' / '), 240)
173
- kept.push(`[${formatTime(row.ts)}] ${who}${marker}:${body}`)
209
+ kept.push(`[${formatTime(row.ts)}] ${who}${marker}${aside}:${body}`)
174
210
  }
175
211
  kept.reverse()
176
212
  let text = ''
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qq-affinity",
3
- "version": "0.15.2",
3
+ "version": "1.0.0",
4
4
  "description": "QQ 聊天记录好感度档案:本地建档、三项亲密度评分、智能回复提示、按人开启的智能托管、人格画像、可迁移的本地数据位置、从实时通道自动补齐历史。",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,76 @@
1
+ // Group lines that never @ me must weigh less than lines aimed at me.
2
+ // - rowsForPerson tags every row with `group` and `atMe`
3
+ // - measure() counts behaviour over addressed lines only and discounts the rest
4
+ // - renderTranscript() labels the unaddressed ones so the model can discount them
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import { fileURLToPath, pathToFileURL } from 'node:url'
9
+
10
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
11
+ const href = (rel) => pathToFileURL(path.join(root, rel)).href
12
+ const { Store } = await import(href('lib/store.js'))
13
+ const { rowsForPerson, measure, renderTranscript, GROUP_UNMENTIONED_WEIGHT } = await import(href('lib/features.js'))
14
+
15
+ let failures = 0
16
+ const check = (label, ok, extra = '') => {
17
+ console.log(` ${ok ? 'ok ' : 'FAIL'} ${label}${extra === '' ? '' : ` :: ${extra}`}`)
18
+ if (!ok) failures += 1
19
+ }
20
+
21
+ // ---------------------------------------------------------------- real rows
22
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-mention-'))
23
+ process.env.DSH_QQ_AFFINITY_HOME = dir
24
+ const store = new Store(dir)
25
+ store.state.settings.selfUin = '20002'
26
+ store.state.settings.selfName = '我'
27
+
28
+ const privateChat = store.ensureConversation({ kind: 'c2c', title: '私聊', peerUin: '10001' }).conversation
29
+ store.setEnabled(privateChat.id, true)
30
+ const groupChat = store.ensureConversation({ kind: 'group', title: '一个群', groupUin: '90001' }).conversation
31
+ store.setEnabled(groupChat.id, true)
32
+ // The group conversation only contributes while this person is one of its members.
33
+ store.updateConversation(groupChat.id, {})
34
+ store.state.conversations.find(row => row.id === groupChat.id).participants = ['10001']
35
+
36
+ const base = 1700000000000
37
+ store.appendMessages(privateChat.id, [
38
+ { ts: base, senderUin: '10001', senderName: '小明', text: '私聊一句' },
39
+ { ts: base + 1000, senderUin: '20002', senderName: '我', text: '我回一句' },
40
+ ])
41
+ store.appendMessages(groupChat.id, [
42
+ { ts: base + 2000, senderUin: '10001', senderName: '小明', text: '@20002 群里叫我' },
43
+ { ts: base + 3000, senderUin: '10001', senderName: '小明', text: '这句是在跟别人聊' },
44
+ ])
45
+
46
+ const rows = rowsForPerson(store, '10001')
47
+ const inGroup = rows.filter(row => row.group === true)
48
+ const inPrivate = rows.filter(row => row.group !== true)
49
+
50
+ console.log('\n== rowsForPerson tags the origin ==')
51
+ check('private rows are not marked as group', inPrivate.every(row => row.group !== true), JSON.stringify(inPrivate.map(row => row.group)))
52
+ check('group rows are marked', inGroup.length === 2, `${inGroup.length}`)
53
+ check('the @ line is recognised', inGroup.find(row => row.text.includes('@20002'))?.atMe === true)
54
+ check('the other line is not', inGroup.find(row => row.text.includes('跟别人'))?.atMe === false)
55
+
56
+ console.log('\n== measure splits addressed from unaddressed ==')
57
+ const features = measure(rows, '10001')
58
+ check('two of their lines were addressed to me', features.theirAddressedMessages === 2, `${features.theirAddressedMessages}`)
59
+ check('one group line was not', features.theirUnaddressedGroupMessages === 1, `${features.theirUnaddressedGroupMessages}`)
60
+ check('the weighted count discounts it', features.theirWeightedMessages === Math.round((2 + GROUP_UNMENTIONED_WEIGHT) * 100) / 100, `${features.theirWeightedMessages}`)
61
+ const addressedRows = rows.filter(row => row.senderUin === '10001' && (row.group !== true || row.atMe === true))
62
+ const expectedAvg = Math.round(addressedRows.reduce((total, row) => total + row.text.length, 0) / addressedRows.length)
63
+ check('average length uses addressed lines only', features.theirAvgChars === expectedAvg,
64
+ `${features.theirAvgChars} vs ${expectedAvg} over ${addressedRows.length} rows`)
65
+
66
+ console.log('\n== the transcript labels what was not aimed at me ==')
67
+ const transcript = renderTranscript(rows, { targetUin: '10001', targetName: '小明' }).text
68
+ check('the unaddressed group line is marked', transcript.includes('这句是在跟别人聊'.slice(0, 5)) && transcript.includes('(群里未点名)'), transcript)
69
+ const markedCount = (transcript.match(/(群里未点名)/g) ?? []).length
70
+ check('only one line carries the label', markedCount === 1, `${markedCount}`)
71
+ check('the @ line is not labelled', !transcript.split('\n').some(line => line.includes('群里叫我') && line.includes('(群里未点名)')))
72
+
73
+ console.log(`\nweight in use: ${GROUP_UNMENTIONED_WEIGHT}`)
74
+ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
75
+ fs.rmSync(dir, { recursive: true, force: true })
76
+ process.exit(failures === 0 ? 0 : 1)