dsh-qq-affinity 0.0.0-stage → 0.14.2
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 +55 -2
- package/client.js +3550 -0
- package/cordis.patch.yml +6 -0
- package/docs/DETAIL.md +332 -0
- package/icon.svg +12 -0
- package/index.js +128 -0
- package/lib/analyze.js +777 -0
- package/lib/api.js +984 -0
- package/lib/backfill.js +146 -0
- package/lib/bridge-server.js +78 -0
- package/lib/care.js +240 -0
- package/lib/features.js +200 -0
- package/lib/home.js +168 -0
- package/lib/inbound.js +120 -0
- package/lib/llm.js +137 -0
- package/lib/media.js +161 -0
- package/lib/onebot.js +207 -0
- package/lib/parse.js +184 -0
- package/lib/recover.js +46 -0
- package/lib/store.js +705 -0
- package/lib/util.js +186 -0
- package/lib/vision.js +108 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +38 -4
- package/scripts/api-e2e.mjs +538 -0
- package/scripts/backfill-e2e.mjs +142 -0
- package/scripts/backfill-live.mjs +60 -0
- package/scripts/bridge-e2e.mjs +137 -0
- package/scripts/care-e2e.mjs +217 -0
- package/scripts/check-hook-order.mjs +83 -0
- package/scripts/make-napcat-config.mjs +87 -0
- package/scripts/media-e2e.mjs +103 -0
- package/scripts/recover-e2e.mjs +75 -0
- package/scripts/selftest.mjs +159 -0
- package/scripts/strip-bom.mjs +27 -0
package/lib/store.js
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local profile store. Everything this plugin knows lives in one directory:
|
|
3
|
+
* `meta.json` for conversations, per-QQ-number profiles, scores and adoptions,
|
|
4
|
+
* `messages/<conversation>.ndjson` for the transcripts, and
|
|
5
|
+
* `suggestions/<conversation>.json` for the outstanding smart-reply batches.
|
|
6
|
+
*
|
|
7
|
+
* Nothing is read from QQ: a conversation only contributes to analysis while
|
|
8
|
+
* `enabled` is true, and the only writer is an explicit import request.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import { minutesOfClock, readJson, readLines, rewriteLines, writeJson, appendLines, similarity, uid } from './util.js'
|
|
14
|
+
import { resolveDataDirectory } from './home.js'
|
|
15
|
+
|
|
16
|
+
/** Bumped when the on-disk shape changes in a way that needs migration. */
|
|
17
|
+
export const STORE_VERSION = 1
|
|
18
|
+
|
|
19
|
+
/** The conversation key derives from who the conversation is with, so repeats merge. */
|
|
20
|
+
function conversationKey(kind, peerUin, groupUin, title) {
|
|
21
|
+
if (kind === 'group' && groupUin) return `group:${groupUin}`
|
|
22
|
+
if (kind === 'c2c' && peerUin) return `c2c:${peerUin}`
|
|
23
|
+
const slug = String(title ?? '').trim().slice(0, 40)
|
|
24
|
+
return `custom:${slug || uid('c-')}`
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A fresh metadata document. */
|
|
28
|
+
function emptyMeta() {
|
|
29
|
+
return {
|
|
30
|
+
version: STORE_VERSION,
|
|
31
|
+
settings: {
|
|
32
|
+
selfUin: '',
|
|
33
|
+
selfName: '',
|
|
34
|
+
maxTranscriptChars: 12000,
|
|
35
|
+
/** Global kill switch for automatic replies, independent of each person's own toggle. */
|
|
36
|
+
careEnabled: false,
|
|
37
|
+
/**
|
|
38
|
+
* Allow chat images and stickers to be sent to the model.
|
|
39
|
+
*
|
|
40
|
+
* On by default because understanding pictures is the point, but this is
|
|
41
|
+
* the one setting that moves bytes off the machine, so it stays visible
|
|
42
|
+
* and can be turned off without losing `[图片]` markers in the archive.
|
|
43
|
+
*/
|
|
44
|
+
visionImages: true,
|
|
45
|
+
/** Real-time bridge (OneBot v11 HTTP API) used to receive and send messages. */
|
|
46
|
+
onebot: {
|
|
47
|
+
apiBase: 'http://127.0.0.1:3001',
|
|
48
|
+
accessToken: '',
|
|
49
|
+
inboundToken: '',
|
|
50
|
+
enabled: false,
|
|
51
|
+
/** ISO time of the last event the bridge successfully reported, for the panel. */
|
|
52
|
+
lastInboundAt: '',
|
|
53
|
+
/** Pull history from the bridge when the channel is enabled. */
|
|
54
|
+
autoBackfill: true,
|
|
55
|
+
/** ISO time of the last history pull. */
|
|
56
|
+
lastBackfillAt: '',
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
conversations: [],
|
|
60
|
+
people: {},
|
|
61
|
+
scores: {},
|
|
62
|
+
adoptions: [],
|
|
63
|
+
/** Per-QQ-number personality sketches, keyed by QQ number. */
|
|
64
|
+
personas: {},
|
|
65
|
+
/** Per-QQ-number automatic reply settings. */
|
|
66
|
+
care: {},
|
|
67
|
+
/** User-arranged display order for the two left-hand lists. */
|
|
68
|
+
order: { conversations: [], people: [] },
|
|
69
|
+
/** Pinned conversation ids, first is topmost. Multiple pins allowed. */
|
|
70
|
+
pinned: [],
|
|
71
|
+
/** One analysis of the user themself, across every enabled conversation. */
|
|
72
|
+
selfProfile: null,
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Default per-person care settings. */
|
|
77
|
+
export function defaultCare() {
|
|
78
|
+
return {
|
|
79
|
+
enabled: false,
|
|
80
|
+
mode: 'draft',
|
|
81
|
+
hourlyCap: 5,
|
|
82
|
+
quietFrom: '23:30',
|
|
83
|
+
quietTo: '08:00',
|
|
84
|
+
groupOnlyWhenMentioned: true,
|
|
85
|
+
maxReplyChars: 60,
|
|
86
|
+
updatedAt: new Date().toISOString(),
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Normalize a stored document so a hand-edited or older file still loads. */
|
|
91
|
+
function normalizeMeta(raw) {
|
|
92
|
+
const base = emptyMeta()
|
|
93
|
+
if (raw === null || typeof raw !== 'object') return base
|
|
94
|
+
const settings = raw.settings !== null && typeof raw.settings === 'object' ? raw.settings : {}
|
|
95
|
+
const onebot = settings.onebot !== null && typeof settings.onebot === 'object' ? settings.onebot : {}
|
|
96
|
+
const care = {}
|
|
97
|
+
if (raw.care !== null && typeof raw.care === 'object') {
|
|
98
|
+
for (const [uin, value] of Object.entries(raw.care)) {
|
|
99
|
+
if (value === null || typeof value !== 'object') continue
|
|
100
|
+
const fallback = defaultCare()
|
|
101
|
+
care[uin] = {
|
|
102
|
+
enabled: value.enabled === true,
|
|
103
|
+
mode: value.mode === 'auto' ? 'auto' : 'draft',
|
|
104
|
+
// `cooldownMinutes` from older archives is dropped on purpose: the hourly
|
|
105
|
+
// cap is the rate limit now.
|
|
106
|
+
hourlyCap: Number.isFinite(Number(value.hourlyCap)) ? Math.min(60, Math.max(1, Number(value.hourlyCap))) : fallback.hourlyCap,
|
|
107
|
+
quietFrom: typeof value.quietFrom === 'string' ? value.quietFrom : fallback.quietFrom,
|
|
108
|
+
quietTo: typeof value.quietTo === 'string' ? value.quietTo : fallback.quietTo,
|
|
109
|
+
groupOnlyWhenMentioned: value.groupOnlyWhenMentioned !== false,
|
|
110
|
+
maxReplyChars: Number.isFinite(Number(value.maxReplyChars)) ? Math.min(300, Math.max(10, Number(value.maxReplyChars))) : fallback.maxReplyChars,
|
|
111
|
+
updatedAt: typeof value.updatedAt === 'string' ? value.updatedAt : fallback.updatedAt,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
version: STORE_VERSION,
|
|
117
|
+
settings: {
|
|
118
|
+
selfUin: typeof settings.selfUin === 'string' ? settings.selfUin : '',
|
|
119
|
+
selfName: typeof settings.selfName === 'string' ? settings.selfName : '',
|
|
120
|
+
maxTranscriptChars: Number.isFinite(Number(settings.maxTranscriptChars))
|
|
121
|
+
? Math.min(60000, Math.max(2000, Number(settings.maxTranscriptChars)))
|
|
122
|
+
: 12000,
|
|
123
|
+
careEnabled: settings.careEnabled === true,
|
|
124
|
+
visionImages: settings.visionImages !== false,
|
|
125
|
+
onebot: {
|
|
126
|
+
apiBase: typeof onebot.apiBase === 'string' ? onebot.apiBase : 'http://127.0.0.1:3001',
|
|
127
|
+
accessToken: typeof onebot.accessToken === 'string' ? onebot.accessToken : '',
|
|
128
|
+
inboundToken: typeof onebot.inboundToken === 'string' ? onebot.inboundToken : '',
|
|
129
|
+
enabled: onebot.enabled === true,
|
|
130
|
+
lastInboundAt: typeof onebot.lastInboundAt === 'string' ? onebot.lastInboundAt : '',
|
|
131
|
+
autoBackfill: onebot.autoBackfill !== false,
|
|
132
|
+
lastBackfillAt: typeof onebot.lastBackfillAt === 'string' ? onebot.lastBackfillAt : '',
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
conversations: Array.isArray(raw.conversations)
|
|
136
|
+
? raw.conversations.filter(row => row !== null && typeof row === 'object' && typeof row.id === 'string').map(row => ({
|
|
137
|
+
id: row.id,
|
|
138
|
+
kind: row.kind === 'group' ? 'group' : 'c2c',
|
|
139
|
+
title: typeof row.title === 'string' ? row.title : '',
|
|
140
|
+
peerUin: typeof row.peerUin === 'string' ? row.peerUin : '',
|
|
141
|
+
groupUin: typeof row.groupUin === 'string' ? row.groupUin : '',
|
|
142
|
+
enabled: row.enabled === true,
|
|
143
|
+
createdAt: typeof row.createdAt === 'string' ? row.createdAt : new Date().toISOString(),
|
|
144
|
+
messageCount: Number.isFinite(Number(row.messageCount)) ? Number(row.messageCount) : 0,
|
|
145
|
+
lastMessageAt: typeof row.lastMessageAt === 'string' ? row.lastMessageAt : '',
|
|
146
|
+
participants: Array.isArray(row.participants) ? row.participants.filter(v => typeof v === 'string') : [],
|
|
147
|
+
}))
|
|
148
|
+
: [],
|
|
149
|
+
people: raw.people !== null && typeof raw.people === 'object' ? raw.people : {},
|
|
150
|
+
scores: raw.scores !== null && typeof raw.scores === 'object' ? raw.scores : {},
|
|
151
|
+
adoptions: Array.isArray(raw.adoptions) ? raw.adoptions.filter(row => row !== null && typeof row === 'object') : [],
|
|
152
|
+
personas: raw.personas !== null && typeof raw.personas === 'object' ? raw.personas : {},
|
|
153
|
+
care,
|
|
154
|
+
order: {
|
|
155
|
+
conversations: Array.isArray(raw.order?.conversations) ? raw.order.conversations.filter(v => typeof v === 'string') : [],
|
|
156
|
+
people: Array.isArray(raw.order?.people) ? raw.order.people.filter(v => typeof v === 'string') : [],
|
|
157
|
+
},
|
|
158
|
+
pinned: Array.isArray(raw.pinned) ? raw.pinned.filter(v => typeof v === 'string') : [],
|
|
159
|
+
selfProfile: raw.selfProfile !== null && typeof raw.selfProfile === 'object' ? raw.selfProfile : null,
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export class Store {
|
|
164
|
+
constructor(directory = resolveDataDirectory()) {
|
|
165
|
+
this.retarget(directory)
|
|
166
|
+
this.meta = null
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Point this store at another directory, keeping the same object identity. */
|
|
170
|
+
retarget(directory) {
|
|
171
|
+
this.directory = directory
|
|
172
|
+
this.metaFile = path.join(directory, 'meta.json')
|
|
173
|
+
this.messagesDir = path.join(directory, 'messages')
|
|
174
|
+
this.suggestionsDir = path.join(directory, 'suggestions')
|
|
175
|
+
this.outboxFile = path.join(directory, 'outbox.ndjson')
|
|
176
|
+
// The cached document belongs to the previous directory.
|
|
177
|
+
this.meta = null
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The live metadata document, loaded once. */
|
|
181
|
+
get state() {
|
|
182
|
+
if (this.meta === null) this.meta = normalizeMeta(readJson(this.metaFile, null))
|
|
183
|
+
return this.meta
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
save() {
|
|
187
|
+
writeJson(this.metaFile, this.state)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Re-read the document from disk, discarding the cache. */
|
|
191
|
+
reload() {
|
|
192
|
+
this.meta = null
|
|
193
|
+
return this.state
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
messagesFile(convId) {
|
|
197
|
+
return path.join(this.messagesDir, `${convId.replace(/[^A-Za-z0-9._-]/g, '_')}.ndjson`)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
suggestionsFile(convId) {
|
|
201
|
+
return path.join(this.suggestionsDir, `${convId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The conversation row for an id, or undefined. */
|
|
205
|
+
conversation(id) {
|
|
206
|
+
return this.state.conversations.find(row => row.id === id)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The person row for a QQ number, or undefined. */
|
|
210
|
+
person(uin) {
|
|
211
|
+
return this.state.people[String(uin)]
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Conversation ids whose messages are allowed to feed analysis. */
|
|
215
|
+
enabledConversationIds() {
|
|
216
|
+
return this.state.conversations.filter(row => row.enabled).map(row => row.id)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Create or reuse the conversation for a target, without enabling it.
|
|
221
|
+
* @returns {{ conversation: object, created: boolean }}
|
|
222
|
+
*/
|
|
223
|
+
ensureConversation({ kind = 'c2c', title = '', peerUin = '', groupUin = '' }) {
|
|
224
|
+
const id = conversationKey(kind, peerUin, groupUin, title)
|
|
225
|
+
const existing = this.conversation(id)
|
|
226
|
+
if (existing !== undefined) {
|
|
227
|
+
if (title !== '' && existing.title === '') existing.title = title
|
|
228
|
+
return { conversation: existing, created: false }
|
|
229
|
+
}
|
|
230
|
+
const conversation = {
|
|
231
|
+
id,
|
|
232
|
+
kind,
|
|
233
|
+
title,
|
|
234
|
+
peerUin,
|
|
235
|
+
groupUin,
|
|
236
|
+
enabled: false,
|
|
237
|
+
createdAt: new Date().toISOString(),
|
|
238
|
+
messageCount: 0,
|
|
239
|
+
lastMessageAt: '',
|
|
240
|
+
participants: [],
|
|
241
|
+
}
|
|
242
|
+
this.state.conversations.push(conversation)
|
|
243
|
+
this.save()
|
|
244
|
+
return { conversation, created: true }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Turn collection and analysis for one conversation on or off. */
|
|
248
|
+
setEnabled(id, enabled) {
|
|
249
|
+
const conversation = this.conversation(id)
|
|
250
|
+
if (conversation === undefined) return undefined
|
|
251
|
+
conversation.enabled = enabled === true
|
|
252
|
+
this.save()
|
|
253
|
+
this.markStale(conversation)
|
|
254
|
+
return conversation
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Flag every stored score whose evidence this conversation just changed, so
|
|
259
|
+
* the panel can ask for a fresh analysis instead of showing a stale number.
|
|
260
|
+
*/
|
|
261
|
+
markStale(conversation) {
|
|
262
|
+
const uins = new Set([conversation.peerUin, ...(conversation.participants ?? [])].filter(uin => typeof uin === 'string' && uin !== ''))
|
|
263
|
+
let touched = false
|
|
264
|
+
for (const uin of uins) {
|
|
265
|
+
const row = this.state.scores[uin]
|
|
266
|
+
if (row !== undefined && row.stale !== true) {
|
|
267
|
+
row.stale = true
|
|
268
|
+
touched = true
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (touched) this.save()
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Rename a conversation, and the target QQ number it points at. */
|
|
275
|
+
updateConversation(id, patch) {
|
|
276
|
+
const conversation = this.conversation(id)
|
|
277
|
+
if (conversation === undefined) return undefined
|
|
278
|
+
if (typeof patch.title === 'string') conversation.title = patch.title.trim().slice(0, 120)
|
|
279
|
+
if (typeof patch.peerUin === 'string') conversation.peerUin = patch.peerUin.trim().slice(0, 24)
|
|
280
|
+
if (typeof patch.groupUin === 'string') conversation.groupUin = patch.groupUin.trim().slice(0, 24)
|
|
281
|
+
this.save()
|
|
282
|
+
return conversation
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Replace one conversation's transcript wholesale, keeping its counters honest. */
|
|
286
|
+
rewrite(convId, rows) {
|
|
287
|
+
rewriteLines(this.messagesFile(convId), rows)
|
|
288
|
+
const conversation = this.conversation(convId)
|
|
289
|
+
if (conversation !== undefined) {
|
|
290
|
+
conversation.messageCount = rows.length
|
|
291
|
+
conversation.lastMessageAt = rows.length === 0 ? '' : new Date(rows[rows.length - 1].ts).toISOString()
|
|
292
|
+
this.save()
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Every message of one conversation, oldest first. */
|
|
297
|
+
messages(convId) {
|
|
298
|
+
return readLines(this.messagesFile(convId))
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Append parsed messages, deriving direction and the per-person index.
|
|
303
|
+
* @returns {{ added: number, duplicates: number }}
|
|
304
|
+
*/
|
|
305
|
+
appendMessages(convId, incoming) {
|
|
306
|
+
const conversation = this.conversation(convId)
|
|
307
|
+
if (conversation === undefined) return { added: 0, duplicates: 0 }
|
|
308
|
+
const existing = readLines(this.messagesFile(convId))
|
|
309
|
+
const seen = new Set(existing.map(row => row.fingerprint))
|
|
310
|
+
const selfUin = this.state.settings.selfUin
|
|
311
|
+
const rows = []
|
|
312
|
+
let duplicates = 0
|
|
313
|
+
for (const message of incoming) {
|
|
314
|
+
// Second granularity: a live report and the plugin's own record of the
|
|
315
|
+
// same message can differ by a few milliseconds.
|
|
316
|
+
const fingerprint = `${Math.floor(message.ts / 1000)}|${message.senderUin}|${(message.text ?? '').slice(0, 80)}`
|
|
317
|
+
if (seen.has(fingerprint)) {
|
|
318
|
+
duplicates += 1
|
|
319
|
+
continue
|
|
320
|
+
}
|
|
321
|
+
seen.add(fingerprint)
|
|
322
|
+
const direction = selfUin !== '' && message.senderUin === selfUin
|
|
323
|
+
? 'out'
|
|
324
|
+
: (message.senderUin === '' ? 'unknown' : 'in')
|
|
325
|
+
rows.push({
|
|
326
|
+
id: uid('m'),
|
|
327
|
+
ts: message.ts,
|
|
328
|
+
senderUin: message.senderUin,
|
|
329
|
+
senderName: message.senderName,
|
|
330
|
+
direction,
|
|
331
|
+
text: message.text,
|
|
332
|
+
aiAdopted: false,
|
|
333
|
+
aiAuto: message.aiAuto === true,
|
|
334
|
+
adoptionId: null,
|
|
335
|
+
fingerprint,
|
|
336
|
+
// Image URLs stay with the row: nothing is downloaded here, but the
|
|
337
|
+
// analysis can choose to look at them when the model can see images.
|
|
338
|
+
images: Array.isArray(message.images) ? message.images.slice(0, 4) : [],
|
|
339
|
+
})
|
|
340
|
+
}
|
|
341
|
+
if (rows.length === 0) return { added: 0, duplicates }
|
|
342
|
+
rows.sort((a, b) => a.ts - b.ts)
|
|
343
|
+
// The whole file is rewritten because direction and adoption marks are
|
|
344
|
+
// derived at read time; a transcript that fits in memory keeps that simple.
|
|
345
|
+
const all = existing.concat(rows).sort((a, b) => a.ts - b.ts)
|
|
346
|
+
rewriteLines(this.messagesFile(convId), all)
|
|
347
|
+
conversation.messageCount = all.length
|
|
348
|
+
conversation.lastMessageAt = all.length === 0 ? '' : new Date(all[all.length - 1].ts).toISOString()
|
|
349
|
+
this.indexPeople(conversation, rows)
|
|
350
|
+
this.save()
|
|
351
|
+
this.markStale(conversation)
|
|
352
|
+
return { added: rows.length, duplicates }
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Fold newly stored messages into the per-QQ-number profiles. */
|
|
356
|
+
indexPeople(conversation, rows) {
|
|
357
|
+
const selfUin = this.state.settings.selfUin
|
|
358
|
+
const participants = new Set(conversation.participants ?? [])
|
|
359
|
+
for (const row of rows) {
|
|
360
|
+
if (row.senderUin === '' || row.senderUin === selfUin) continue
|
|
361
|
+
participants.add(row.senderUin)
|
|
362
|
+
const person = this.state.people[row.senderUin] ?? {
|
|
363
|
+
uin: row.senderUin,
|
|
364
|
+
names: [],
|
|
365
|
+
firstSeen: new Date(row.ts).toISOString(),
|
|
366
|
+
lastSeen: new Date(row.ts).toISOString(),
|
|
367
|
+
messageCount: 0,
|
|
368
|
+
conversationIds: [],
|
|
369
|
+
}
|
|
370
|
+
if (row.senderName !== '' && !person.names.includes(row.senderName)) {
|
|
371
|
+
person.names = [...person.names, row.senderName].slice(-6)
|
|
372
|
+
}
|
|
373
|
+
person.messageCount += 1
|
|
374
|
+
person.lastSeen = new Date(Math.max(Date.parse(person.lastSeen) || 0, row.ts)).toISOString()
|
|
375
|
+
if (!person.conversationIds.includes(conversation.id)) {
|
|
376
|
+
person.conversationIds = [...person.conversationIds, conversation.id]
|
|
377
|
+
}
|
|
378
|
+
this.state.people[row.senderUin] = person
|
|
379
|
+
}
|
|
380
|
+
conversation.participants = [...participants]
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Delete one conversation's transcript and suggestions, then re-derive the index. */
|
|
384
|
+
removeConversation(id) {
|
|
385
|
+
const index = this.state.conversations.findIndex(row => row.id === id)
|
|
386
|
+
if (index < 0) return false
|
|
387
|
+
this.state.conversations.splice(index, 1)
|
|
388
|
+
fs.rmSync(this.messagesFile(id), { force: true })
|
|
389
|
+
fs.rmSync(this.suggestionsFile(id), { force: true })
|
|
390
|
+
this.save()
|
|
391
|
+
this.rebuildPeople()
|
|
392
|
+
return true
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Recompute every per-person profile from the transcripts still on disk. */
|
|
396
|
+
rebuildPeople() {
|
|
397
|
+
const selfUin = this.state.settings.selfUin
|
|
398
|
+
const people = {}
|
|
399
|
+
for (const conversation of this.state.conversations) {
|
|
400
|
+
const rows = this.messages(conversation.id)
|
|
401
|
+
const participants = new Set()
|
|
402
|
+
for (const row of rows) {
|
|
403
|
+
if (row.senderUin === '' || row.senderUin === selfUin) continue
|
|
404
|
+
participants.add(row.senderUin)
|
|
405
|
+
const person = people[row.senderUin] ?? {
|
|
406
|
+
uin: row.senderUin,
|
|
407
|
+
names: [],
|
|
408
|
+
firstSeen: new Date(row.ts).toISOString(),
|
|
409
|
+
lastSeen: new Date(row.ts).toISOString(),
|
|
410
|
+
messageCount: 0,
|
|
411
|
+
conversationIds: [],
|
|
412
|
+
}
|
|
413
|
+
if (row.senderName !== '' && !person.names.includes(row.senderName)) {
|
|
414
|
+
person.names = [...person.names, row.senderName].slice(-6)
|
|
415
|
+
}
|
|
416
|
+
person.messageCount += 1
|
|
417
|
+
person.firstSeen = new Date(Math.min(Date.parse(person.firstSeen) || row.ts, row.ts)).toISOString()
|
|
418
|
+
person.lastSeen = new Date(Math.max(Date.parse(person.lastSeen) || 0, row.ts)).toISOString()
|
|
419
|
+
if (!person.conversationIds.includes(conversation.id)) {
|
|
420
|
+
person.conversationIds = [...person.conversationIds, conversation.id]
|
|
421
|
+
}
|
|
422
|
+
people[row.senderUin] = person
|
|
423
|
+
}
|
|
424
|
+
conversation.participants = [...participants]
|
|
425
|
+
conversation.messageCount = rows.length
|
|
426
|
+
}
|
|
427
|
+
this.state.people = people
|
|
428
|
+
for (const uin of Object.keys(this.state.scores)) {
|
|
429
|
+
if (people[uin] === undefined) delete this.state.scores[uin]
|
|
430
|
+
}
|
|
431
|
+
this.save()
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Record one analysis result for a QQ number. */
|
|
435
|
+
saveScore(uin, result) {
|
|
436
|
+
const key = String(uin)
|
|
437
|
+
const previous = this.state.scores[key]
|
|
438
|
+
// Every overwrite first parks the values it replaces, so the panel can show
|
|
439
|
+
// "上次多少分" and a short history. Capped so the file stays bounded.
|
|
440
|
+
const history = Array.isArray(previous?.history) ? previous.history : []
|
|
441
|
+
if (previous !== undefined && (previous.theirFavor?.score ?? previous.myFavor?.score ?? previous.intimacy?.score) !== undefined) {
|
|
442
|
+
history.unshift({
|
|
443
|
+
at: previous.updatedAt ?? '',
|
|
444
|
+
theirFavor: previous.theirFavor?.score ?? 0,
|
|
445
|
+
myFavor: previous.myFavor?.score ?? 0,
|
|
446
|
+
intimacy: previous.intimacy?.score ?? 0,
|
|
447
|
+
confidence: previous.confidence ?? 0,
|
|
448
|
+
})
|
|
449
|
+
}
|
|
450
|
+
this.state.scores[key] = {
|
|
451
|
+
...result,
|
|
452
|
+
uin: key,
|
|
453
|
+
updatedAt: new Date().toISOString(),
|
|
454
|
+
history: history.slice(0, 20),
|
|
455
|
+
}
|
|
456
|
+
this.save()
|
|
457
|
+
return this.state.scores[key]
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** The stored score for a QQ number, or undefined. */
|
|
461
|
+
score(uin) {
|
|
462
|
+
return this.state.scores[String(uin)]
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** Record one personality sketch for a QQ number. */
|
|
466
|
+
savePersona(uin, result) {
|
|
467
|
+
this.state.personas[uin] = { ...result, uin, updatedAt: new Date().toISOString() }
|
|
468
|
+
this.save()
|
|
469
|
+
return this.state.personas[uin]
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** The stored personality sketch for a QQ number, or undefined. */
|
|
473
|
+
persona(uin) {
|
|
474
|
+
return this.state.personas[String(uin)]
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** Record the analysis of the user themself. */
|
|
478
|
+
saveSelfProfile(result) {
|
|
479
|
+
this.state.selfProfile = { ...result, updatedAt: new Date().toISOString() }
|
|
480
|
+
this.save()
|
|
481
|
+
return this.state.selfProfile
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** The stored self analysis, or null. */
|
|
485
|
+
selfProfile() {
|
|
486
|
+
return this.state.selfProfile ?? null
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Pin one conversation to the top; returns the pinned list, first is topmost. */
|
|
490
|
+
pin(id) {
|
|
491
|
+
if (!this.state.pinned.includes(id)) {
|
|
492
|
+
this.state.pinned = [id, ...this.state.pinned]
|
|
493
|
+
this.save()
|
|
494
|
+
}
|
|
495
|
+
return this.state.pinned
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** Unpin one conversation; returns the pinned list. */
|
|
499
|
+
unpin(id) {
|
|
500
|
+
const next = this.state.pinned.filter(value => value !== id)
|
|
501
|
+
if (next.length !== this.state.pinned.length) {
|
|
502
|
+
this.state.pinned = next
|
|
503
|
+
this.save()
|
|
504
|
+
}
|
|
505
|
+
return this.state.pinned
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Move one pinned conversation up or down among the pins. */
|
|
509
|
+
movePinned(id, delta) {
|
|
510
|
+
const at = this.state.pinned.indexOf(id)
|
|
511
|
+
const to = at + delta
|
|
512
|
+
if (at < 0 || to < 0 || to >= this.state.pinned.length) return this.state.pinned
|
|
513
|
+
const next = [...this.state.pinned]
|
|
514
|
+
;[next[at], next[to]] = [next[to], next[at]]
|
|
515
|
+
this.state.pinned = next
|
|
516
|
+
this.save()
|
|
517
|
+
return next
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Replace one list's display order. Ids that no longer exist are dropped and
|
|
522
|
+
* ids the caller forgot are appended, so a stale drag never hides a row.
|
|
523
|
+
* @param {'conversations' | 'people'} kind
|
|
524
|
+
* @param {string[]} ids
|
|
525
|
+
* @returns {string[] | undefined}
|
|
526
|
+
*/
|
|
527
|
+
setOrder(kind, ids) {
|
|
528
|
+
if (kind !== 'conversations' && kind !== 'people') return undefined
|
|
529
|
+
const known = kind === 'conversations'
|
|
530
|
+
? this.state.conversations.map(row => row.id)
|
|
531
|
+
: Object.keys(this.state.people)
|
|
532
|
+
const knownSet = new Set(known)
|
|
533
|
+
const ordered = []
|
|
534
|
+
for (const id of Array.isArray(ids) ? ids : []) {
|
|
535
|
+
const value = String(id)
|
|
536
|
+
if (!knownSet.has(value) || ordered.includes(value)) continue
|
|
537
|
+
ordered.push(value)
|
|
538
|
+
}
|
|
539
|
+
for (const id of known) if (!ordered.includes(id)) ordered.push(id)
|
|
540
|
+
this.state.order[kind] = ordered
|
|
541
|
+
this.save()
|
|
542
|
+
return ordered
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Read the outstanding smart-reply batches of one conversation, newest last. */
|
|
546
|
+
suggestions(convId) {
|
|
547
|
+
const value = readJson(this.suggestionsFile(convId), [])
|
|
548
|
+
return Array.isArray(value) ? value : []
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** Prepend one batch, keeping the newest 20 batches. */
|
|
552
|
+
pushSuggestions(convId, batch) {
|
|
553
|
+
const next = [batch, ...this.suggestions(convId)].slice(0, 20)
|
|
554
|
+
writeJson(this.suggestionsFile(convId), next)
|
|
555
|
+
return batch
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** Mark one suggestion as adopted, returning the stored adoption. */
|
|
559
|
+
adopt(convId, suggestionId) {
|
|
560
|
+
const batches = this.suggestions(convId)
|
|
561
|
+
for (const batch of batches) {
|
|
562
|
+
for (const option of batch.options ?? []) {
|
|
563
|
+
if (option.id !== suggestionId || option.adopted === true) continue
|
|
564
|
+
option.adopted = true
|
|
565
|
+
option.adoptedAt = new Date().toISOString()
|
|
566
|
+
writeJson(this.suggestionsFile(convId), batches)
|
|
567
|
+
const adoption = {
|
|
568
|
+
id: uid('a'),
|
|
569
|
+
conversationId: convId,
|
|
570
|
+
targetUin: batch.targetUin ?? '',
|
|
571
|
+
suggestionId,
|
|
572
|
+
text: option.text,
|
|
573
|
+
createdAt: option.adoptedAt,
|
|
574
|
+
matchedMessageIds: [],
|
|
575
|
+
}
|
|
576
|
+
this.state.adoptions.push(adoption)
|
|
577
|
+
this.save()
|
|
578
|
+
return adoption
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return undefined
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* Mark outbound messages that reproduce an adopted suggestion.
|
|
586
|
+
* A message is marked when it appears after the adoption and reads the same
|
|
587
|
+
* once whitespace and punctuation are ignored.
|
|
588
|
+
* @returns {number} messages marked by this pass.
|
|
589
|
+
*/
|
|
590
|
+
matchAdoptions(convId) {
|
|
591
|
+
const pending = this.state.adoptions.filter(row => row.conversationId === convId && (row.matchedMessageIds ?? []).length === 0)
|
|
592
|
+
if (pending.length === 0) return 0
|
|
593
|
+
const rows = this.messages(convId)
|
|
594
|
+
let marked = 0
|
|
595
|
+
let touched = false
|
|
596
|
+
for (const adoption of pending) {
|
|
597
|
+
const since = Date.parse(adoption.createdAt) - 24 * 60 * 60 * 1000
|
|
598
|
+
for (const row of rows) {
|
|
599
|
+
if (row.direction !== 'out' || row.aiAdopted === true) continue
|
|
600
|
+
if (row.ts < since) continue
|
|
601
|
+
if (similarity(row.text, adoption.text) < 0.9) continue
|
|
602
|
+
row.aiAdopted = true
|
|
603
|
+
row.adoptionId = adoption.id
|
|
604
|
+
adoption.matchedMessageIds = [...(adoption.matchedMessageIds ?? []), row.id]
|
|
605
|
+
marked += 1
|
|
606
|
+
touched = true
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
if (touched) {
|
|
610
|
+
rewriteLines(this.messagesFile(convId), rows)
|
|
611
|
+
this.save()
|
|
612
|
+
}
|
|
613
|
+
return marked
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** Count adopted messages included per conversation, for reporting. */
|
|
617
|
+
adoptedCount(convId) {
|
|
618
|
+
return this.messages(convId).filter(row => row.aiAdopted === true).length
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// ----------------------------------------------------------- automatic care
|
|
622
|
+
|
|
623
|
+
/** The automatic reply settings for one QQ number, or undefined when unset. */
|
|
624
|
+
careFor(uin) {
|
|
625
|
+
return this.state.care[String(uin)]
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Merge a patch into one person's automatic reply settings.
|
|
630
|
+
* @returns the stored settings, or undefined for an unknown person.
|
|
631
|
+
*/
|
|
632
|
+
setCare(uin, patch) {
|
|
633
|
+
const key = String(uin)
|
|
634
|
+
if (this.state.people[key] === undefined) return undefined
|
|
635
|
+
const current = this.state.care[key] ?? defaultCare()
|
|
636
|
+
const next = { ...current }
|
|
637
|
+
if (typeof patch.enabled === 'boolean') next.enabled = patch.enabled
|
|
638
|
+
if (patch.mode === 'auto' || patch.mode === 'draft') next.mode = patch.mode
|
|
639
|
+
for (const [field, min, max] of [['hourlyCap', 1, 60], ['maxReplyChars', 10, 300]]) {
|
|
640
|
+
if (patch[field] === undefined) continue
|
|
641
|
+
const value = Number(patch[field])
|
|
642
|
+
if (Number.isFinite(value)) next[field] = Math.round(Math.min(max, Math.max(min, value)))
|
|
643
|
+
}
|
|
644
|
+
for (const field of ['quietFrom', 'quietTo']) {
|
|
645
|
+
if (typeof patch[field] !== 'string') continue
|
|
646
|
+
// An empty value is how the user switches the quiet window off entirely.
|
|
647
|
+
const value = patch[field].trim()
|
|
648
|
+
if (value === '' || minutesOfClock(value) !== undefined) next[field] = value
|
|
649
|
+
}
|
|
650
|
+
if (typeof patch.groupOnlyWhenMentioned === 'boolean') next.groupOnlyWhenMentioned = patch.groupOnlyWhenMentioned
|
|
651
|
+
next.updatedAt = new Date().toISOString()
|
|
652
|
+
this.state.care[key] = next
|
|
653
|
+
this.save()
|
|
654
|
+
return next
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** Every QQ number with automatic replies turned on. */
|
|
658
|
+
activeCare() {
|
|
659
|
+
return Object.entries(this.state.care)
|
|
660
|
+
.filter(([, value]) => value.enabled === true)
|
|
661
|
+
.map(([uin, value]) => ({ uin, ...value }))
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// ---------------------------------------------------------------- outbox
|
|
665
|
+
|
|
666
|
+
/** Every recorded automatic reply attempt, oldest first. */
|
|
667
|
+
outbox() {
|
|
668
|
+
return readLines(this.outboxFile)
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** Record one attempt and return the stored row. */
|
|
672
|
+
recordOutbox(row) {
|
|
673
|
+
const stored = {
|
|
674
|
+
id: row.id ?? uid('o'),
|
|
675
|
+
conversationId: row.conversationId ?? '',
|
|
676
|
+
uin: row.uin ?? '',
|
|
677
|
+
inboundText: row.inboundText ?? '',
|
|
678
|
+
inboundTs: row.inboundTs ?? 0,
|
|
679
|
+
text: row.text ?? '',
|
|
680
|
+
status: row.status ?? 'draft',
|
|
681
|
+
reason: row.reason ?? '',
|
|
682
|
+
createdAt: row.createdAt ?? new Date().toISOString(),
|
|
683
|
+
decidedAt: row.decidedAt ?? null,
|
|
684
|
+
sentAt: row.sentAt ?? null,
|
|
685
|
+
messageId: row.messageId ?? null,
|
|
686
|
+
}
|
|
687
|
+
appendLines(this.outboxFile, [stored])
|
|
688
|
+
return stored
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** Patch one outbox row in place, returning the updated row or undefined. */
|
|
692
|
+
updateOutbox(id, patch) {
|
|
693
|
+
const rows = this.outbox()
|
|
694
|
+
const index = rows.findIndex(row => row.id === id)
|
|
695
|
+
if (index < 0) return undefined
|
|
696
|
+
rows[index] = { ...rows[index], ...patch }
|
|
697
|
+
rewriteLines(this.outboxFile, rows)
|
|
698
|
+
return rows[index]
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/** The newest outbox rows for one conversation, newest last. */
|
|
702
|
+
outboxFor(conversationId, limit = 20) {
|
|
703
|
+
return this.outbox().filter(row => row.conversationId === conversationId).slice(-limit)
|
|
704
|
+
}
|
|
705
|
+
}
|