dsh-qq-affinity 1.0.3 → 1.6.1
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 +356 -4
- package/lib/analyze.js +336 -10
- package/lib/api.js +63 -1
- package/lib/care.js +247 -19
- package/lib/features.js +105 -0
- package/lib/guard.js +66 -0
- package/lib/personas.js +54 -0
- package/lib/store.js +111 -1
- package/package.json +1 -1
- package/scripts/api-e2e.mjs +17 -1
- package/scripts/care-e2e.mjs +158 -7
- package/scripts/group-e2e.mjs +166 -0
- package/scripts/guard-e2e.mjs +56 -0
- package/scripts/persona-e2e.mjs +161 -0
package/lib/care.js
CHANGED
|
@@ -16,7 +16,9 @@
|
|
|
16
16
|
|
|
17
17
|
import { plainText, send as sendThroughBridge } from './onebot.js'
|
|
18
18
|
import { inQuietHours, isAiAuthored, uid } from './util.js'
|
|
19
|
-
import { writeAutoReply } from './analyze.js'
|
|
19
|
+
import { writeAutoReply, writeCapExcuse, cannedExcuse } from './analyze.js'
|
|
20
|
+
import { resolvePersona } from './personas.js'
|
|
21
|
+
import { isNonChatRequest, nonChatReason } from './guard.js'
|
|
20
22
|
|
|
21
23
|
const HOUR = 60 * 60 * 1000
|
|
22
24
|
|
|
@@ -40,6 +42,10 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
|
|
|
40
42
|
const chains = new Map()
|
|
41
43
|
/** uin -> timestamps of replies actually sent, for the hourly cap. */
|
|
42
44
|
const sent = new Map()
|
|
45
|
+
/** uin -> when the cap brush-off was last sent, so it happens at most once an hour. */
|
|
46
|
+
const excused = new Map()
|
|
47
|
+
/** uin -> { events, timer }: messages waiting for the debounce window to close. */
|
|
48
|
+
const pending = new Map()
|
|
43
49
|
|
|
44
50
|
const sendOut = deliverOverride ?? ((settings, target, text) => sendThroughBridge(settings, target, text))
|
|
45
51
|
|
|
@@ -51,12 +57,51 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
|
|
|
51
57
|
return next
|
|
52
58
|
}
|
|
53
59
|
|
|
54
|
-
/**
|
|
60
|
+
/** ISO timestamp of one outbox row, in milliseconds. */
|
|
61
|
+
function stampOf(row) {
|
|
62
|
+
const at = Date.parse(row.sentAt ?? row.createdAt ?? '')
|
|
63
|
+
return Number.isFinite(at) ? at : 0
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The start of the current quota window for one person.
|
|
68
|
+
*
|
|
69
|
+
* Usually "an hour ago", but a manual reset moves it forward: the user's
|
|
70
|
+
* decision to zero the count beats the sliding window.
|
|
71
|
+
*/
|
|
72
|
+
function windowStart(uin) {
|
|
73
|
+
return Math.max(Date.now() - HOUR, store.careResetAt(uin))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Reply *events* sent to one person inside the last hour.
|
|
78
|
+
*
|
|
79
|
+
* One event = one automatic reply, no matter how many of their messages that
|
|
80
|
+
* reply covered (the debounce can fold five messages into one answer — that is
|
|
81
|
+
* still 一次). Counted from the outbox rather than only from memory: the quota
|
|
82
|
+
* has to survive a plugin reload.
|
|
83
|
+
*/
|
|
55
84
|
function recentCount(uin) {
|
|
56
|
-
const cutoff =
|
|
85
|
+
const cutoff = windowStart(uin)
|
|
57
86
|
const kept = (sent.get(uin) ?? []).filter(at => at >= cutoff)
|
|
58
87
|
sent.set(uin, kept)
|
|
59
|
-
|
|
88
|
+
const recorded = store.outbox().filter(row => row.uin === uin
|
|
89
|
+
&& (row.kind ?? 'reply') === 'reply'
|
|
90
|
+
// 'sending' is in flight; counting it stops a burst from slipping through.
|
|
91
|
+
&& (row.status === 'sent' || row.status === 'sending')
|
|
92
|
+
&& stampOf(row) >= cutoff).length
|
|
93
|
+
return Math.max(kept.length, recorded)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** How many of their messages those reply events covered, for the panel. */
|
|
97
|
+
function coveredMessages(uin) {
|
|
98
|
+
const cutoff = windowStart(uin)
|
|
99
|
+
return store.outbox()
|
|
100
|
+
.filter(row => row.uin === uin
|
|
101
|
+
&& (row.kind ?? 'reply') === 'reply'
|
|
102
|
+
&& (row.status === 'sent' || row.status === 'sending')
|
|
103
|
+
&& stampOf(row) >= cutoff)
|
|
104
|
+
.reduce((total, row) => total + (Number(row.inboundCount) > 0 ? Number(row.inboundCount) : 1), 0)
|
|
60
105
|
}
|
|
61
106
|
|
|
62
107
|
/** Record one reply attempt and return its outbox row. */
|
|
@@ -64,11 +109,30 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
|
|
|
64
109
|
return store.recordOutbox({ id: uid('o'), ...fields })
|
|
65
110
|
}
|
|
66
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Whether this person has already been brushed off in the current hour.
|
|
114
|
+
*
|
|
115
|
+
* The outbox is the source of truth, not the in-memory map: a reload in the
|
|
116
|
+
* middle of the hour must not produce a second excuse, and the outbox is what
|
|
117
|
+
* survives a reload.
|
|
118
|
+
*/
|
|
119
|
+
function excusedRecently(uin) {
|
|
120
|
+
const cutoff = windowStart(uin)
|
|
121
|
+
const fromOutbox = store.outbox().some(row => row.uin === uin
|
|
122
|
+
&& row.kind === 'excuse'
|
|
123
|
+
// A draft or in-flight excuse counts too: it is still this hour's one brush-off.
|
|
124
|
+
&& (row.status === 'sent' || row.status === 'sending' || row.status === 'draft')
|
|
125
|
+
&& stampOf(row) >= cutoff)
|
|
126
|
+
if (fromOutbox) return true
|
|
127
|
+
return (excused.get(uin) ?? 0) >= cutoff
|
|
128
|
+
}
|
|
129
|
+
|
|
67
130
|
/**
|
|
68
131
|
* Actually send one reply and fold it into the conversation.
|
|
69
132
|
* @returns {Promise<object>} the updated outbox row.
|
|
70
133
|
*/
|
|
71
|
-
async function dispatch(row, conversation, targetUin) {
|
|
134
|
+
async function dispatch(row, conversation, targetUin, options = {}) {
|
|
135
|
+
const track = options.track !== false
|
|
72
136
|
const settings = store.state.settings
|
|
73
137
|
const bridge = settings.onebot
|
|
74
138
|
const target = {
|
|
@@ -85,7 +149,8 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
|
|
|
85
149
|
text: row.text,
|
|
86
150
|
aiAuto: true,
|
|
87
151
|
}])
|
|
88
|
-
|
|
152
|
+
// A cap brush-off is a courtesy, not one of the replies the cap counts.
|
|
153
|
+
if (track) sent.set(targetUin, [...(sent.get(targetUin) ?? []), Date.now()])
|
|
89
154
|
store.markStale(conversation)
|
|
90
155
|
return store.updateOutbox(row.id, {
|
|
91
156
|
status: 'sent',
|
|
@@ -156,28 +221,163 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
|
|
|
156
221
|
// Answering every line in a group would be noise; only a mention wakes it.
|
|
157
222
|
return { action: 'ignored', reason: 'not-mentioned' }
|
|
158
223
|
}
|
|
159
|
-
|
|
224
|
+
// Everything else is decided when the wait is over, not now: a burst of
|
|
225
|
+
// messages should produce one reply to the whole burst.
|
|
226
|
+
return schedule(event, conversation, care)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Buffer one eligible message and (re)start the wait.
|
|
231
|
+
*
|
|
232
|
+
* Each new message restarts the timer, so the reply lands once the other side
|
|
233
|
+
* stops typing — the way a person answers a run of messages in one go.
|
|
234
|
+
*/
|
|
235
|
+
function schedule(event, conversation, care) {
|
|
236
|
+
const uin = event.peerUin
|
|
237
|
+
const delayMs = Math.max(0, Math.round(Number(care.replyDelaySeconds ?? 5) * 1000))
|
|
238
|
+
const entry = pending.get(uin) ?? { events: [], timer: null, conversation }
|
|
239
|
+
entry.events.push(event)
|
|
240
|
+
entry.conversation = conversation
|
|
241
|
+
if (entry.timer !== null) {
|
|
242
|
+
clearTimeout(entry.timer)
|
|
243
|
+
entry.timer = null
|
|
244
|
+
}
|
|
245
|
+
pending.set(uin, entry)
|
|
246
|
+
if (delayMs === 0) return flush(uin)
|
|
247
|
+
entry.timer = setTimeout(() => {
|
|
248
|
+
entry.timer = null
|
|
249
|
+
// The timer fires outside the per-person chain, so join it here.
|
|
250
|
+
void serialize(uin, () => flush(uin))
|
|
251
|
+
}, delayMs)
|
|
252
|
+
return {
|
|
253
|
+
action: 'queued',
|
|
254
|
+
reason: `等 ${Math.max(1, Math.round(delayMs / 1000))} 秒看还有没有新消息,到时一起回`,
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Answer everything buffered for one person, in a single turn.
|
|
260
|
+
*
|
|
261
|
+
* Deliberately not serialized here: the immediate path already runs inside the
|
|
262
|
+
* per-person chain, and re-entering it would make the chain await itself. The
|
|
263
|
+
* timer path wraps this in `serialize` instead.
|
|
264
|
+
* @param {string} uin
|
|
265
|
+
*/
|
|
266
|
+
function flush(uin) {
|
|
267
|
+
const entry = pending.get(uin)
|
|
268
|
+
if (entry === undefined) return Promise.resolve({ action: 'ignored', reason: 'nothing-queued' })
|
|
269
|
+
if (entry.timer !== null) clearTimeout(entry.timer)
|
|
270
|
+
pending.delete(uin)
|
|
271
|
+
return replyTurn(entry.events, entry.conversation)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* The reply pipeline for one coalesced burst.
|
|
276
|
+
* @param {Array<object>} events - every buffered message, oldest first.
|
|
277
|
+
* @param {object} conversation
|
|
278
|
+
*/
|
|
279
|
+
async function replyTurn(events, conversation) {
|
|
280
|
+
// A picture or a bare sticker on its own is not something to answer; if the
|
|
281
|
+
// burst contains anything with words, those are what get answered.
|
|
282
|
+
const usable = events.filter(entry => !UNANSWERABLE.test(plainText(entry.text)))
|
|
283
|
+
const uin = (usable[usable.length - 1] ?? events[events.length - 1]).peerUin
|
|
284
|
+
const care = store.careFor(uin)
|
|
285
|
+
const skip = (reason, extra = {}) => {
|
|
286
|
+
const newest = events[events.length - 1]
|
|
287
|
+
const row = note({
|
|
288
|
+
conversationId: conversation.id,
|
|
289
|
+
uin,
|
|
290
|
+
inboundText: newest.text,
|
|
291
|
+
inboundTs: newest.ts,
|
|
292
|
+
inboundCount: events.length,
|
|
293
|
+
status: 'skipped',
|
|
294
|
+
reason,
|
|
295
|
+
...extra,
|
|
296
|
+
})
|
|
297
|
+
return { action: 'skipped', reason, outboxId: row.id }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
if (care === undefined || care.enabled !== true) return { action: 'recorded', reason: 'person-off' }
|
|
301
|
+
if (usable.length === 0) {
|
|
160
302
|
return skip('对方只发了图片或表情,没有可以接的话。')
|
|
161
303
|
}
|
|
304
|
+
const event = usable[usable.length - 1]
|
|
305
|
+
// The voice in force right now, recorded on every row it produces.
|
|
306
|
+
const persona = resolvePersona(store.state.replyPersonas, care.persona)
|
|
307
|
+
// A pasted exam question or a coding request is not a conversation. Refusing
|
|
308
|
+
// locally costs nothing; answering it would cost tokens and look wrong.
|
|
309
|
+
const nonChat = isNonChatRequest(event.text)
|
|
310
|
+
if (nonChat.blocked) {
|
|
311
|
+
return skip(nonChatReason(nonChat.why), { taskRequest: nonChat.why })
|
|
312
|
+
}
|
|
162
313
|
if (inQuietHours(nowMinutes(), care.quietFrom, care.quietTo)) {
|
|
163
314
|
return skip(`落在免打扰时段(${care.quietFrom}–${care.quietTo})。`)
|
|
164
315
|
}
|
|
165
|
-
// No minimum gap: the hourly cap is the only rate limit.
|
|
166
|
-
|
|
167
|
-
|
|
316
|
+
// No minimum gap: the hourly cap is the only rate limit. Reaching it is not
|
|
317
|
+
// silence: one polite brush-off goes out, and only then does it stop.
|
|
318
|
+
if (recentCount(uin) >= care.hourlyCap) {
|
|
319
|
+
// One brush-off per hour, for the (N+1)-th message only. Everything after
|
|
320
|
+
// it stays silent, however many messages arrive.
|
|
321
|
+
if (excusedRecently(uin)) {
|
|
322
|
+
return skip(`这一小时已经回复 ${care.hourlyCap} 次并推辞过一次,不再打扰。`)
|
|
323
|
+
}
|
|
324
|
+
const excuseTask = tasks === null ? '' : tasks.begin({
|
|
325
|
+
kind: 'care',
|
|
326
|
+
label: '找借口推辞',
|
|
327
|
+
detail: store.person(uin)?.names?.slice(-1)[0] ?? uin,
|
|
328
|
+
})
|
|
329
|
+
let excuse
|
|
330
|
+
try {
|
|
331
|
+
excuse = await writeCapExcuse(ctx, store, {
|
|
332
|
+
conversationId: conversation.id,
|
|
333
|
+
uin,
|
|
334
|
+
maxChars: Math.min(30, care.maxReplyChars),
|
|
335
|
+
})
|
|
336
|
+
if (excuseTask !== '') tasks.finish(excuseTask)
|
|
337
|
+
} catch (error) {
|
|
338
|
+
// A phrasing failure must never turn into silence: fall back to a canned line.
|
|
339
|
+
excuse = cannedExcuse(event.ts)
|
|
340
|
+
if (excuseTask !== '') tasks.finish(excuseTask, '模型没写出推辞,用了备用话术')
|
|
341
|
+
}
|
|
342
|
+
excused.set(uin, Date.now())
|
|
343
|
+
const excuseRow = note({
|
|
344
|
+
conversationId: conversation.id,
|
|
345
|
+
uin,
|
|
346
|
+
inboundText: event.text,
|
|
347
|
+
inboundTs: event.ts,
|
|
348
|
+
inboundCount: events.length,
|
|
349
|
+
text: excuse,
|
|
350
|
+
kind: 'excuse',
|
|
351
|
+
personaId: persona.id,
|
|
352
|
+
personaName: persona.name,
|
|
353
|
+
status: care.mode === 'auto' ? 'sending' : 'draft',
|
|
354
|
+
})
|
|
355
|
+
if (care.mode !== 'auto') {
|
|
356
|
+
return { action: 'declined', reason: '已达回复上限,已备好一句推辞等你确认。', outboxId: excuseRow.id }
|
|
357
|
+
}
|
|
358
|
+
// The brush-off itself does not consume the hourly quota.
|
|
359
|
+
const sentExcuse = await dispatch(excuseRow, conversation, uin, { track: false })
|
|
360
|
+
return {
|
|
361
|
+
action: 'declined',
|
|
362
|
+
reason: '已达回复上限,已礼貌推辞这次聊天。',
|
|
363
|
+
outboxId: excuseRow.id,
|
|
364
|
+
error: sentExcuse.status === 'sent' ? '' : sentExcuse.reason,
|
|
365
|
+
}
|
|
168
366
|
}
|
|
169
367
|
|
|
170
368
|
let text
|
|
369
|
+
const stats = {}
|
|
171
370
|
const replyTask = tasks === null ? '' : tasks.begin({
|
|
172
371
|
kind: 'care',
|
|
173
372
|
label: care.mode === 'auto' ? '自动回复' : '生成托管草稿',
|
|
174
|
-
detail: store.person(
|
|
373
|
+
detail: store.person(uin)?.names?.slice(-1)[0] ?? uin,
|
|
175
374
|
})
|
|
176
375
|
try {
|
|
177
376
|
text = await writeAutoReply(ctx, store, {
|
|
178
377
|
conversationId: conversation.id,
|
|
179
|
-
uin
|
|
378
|
+
uin,
|
|
180
379
|
maxChars: care.maxReplyChars,
|
|
380
|
+
stats,
|
|
181
381
|
})
|
|
182
382
|
if (replyTask !== '') tasks.finish(replyTask)
|
|
183
383
|
} catch (error) {
|
|
@@ -187,15 +387,21 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
|
|
|
187
387
|
|
|
188
388
|
const row = note({
|
|
189
389
|
conversationId: conversation.id,
|
|
190
|
-
uin
|
|
390
|
+
uin,
|
|
191
391
|
inboundText: event.text,
|
|
192
392
|
inboundTs: event.ts,
|
|
393
|
+
inboundCount: events.length,
|
|
193
394
|
text,
|
|
395
|
+
// Which voice wrote this line — the record should say so, not just the panel.
|
|
396
|
+
personaId: persona.id,
|
|
397
|
+
personaName: persona.name,
|
|
398
|
+
// How big the request was, so an unusual jump is visible in the record.
|
|
399
|
+
promptChars: Number(stats.promptChars ?? 0),
|
|
194
400
|
status: care.mode === 'auto' ? 'sending' : 'draft',
|
|
195
401
|
})
|
|
196
402
|
|
|
197
403
|
if (care.mode !== 'auto') return { action: 'drafted', outboxId: row.id }
|
|
198
|
-
const updated = await dispatch(row, conversation,
|
|
404
|
+
const updated = await dispatch(row, conversation, uin)
|
|
199
405
|
return { action: updated.status === 'sent' ? 'sent' : 'failed', outboxId: row.id, reason: updated.reason }
|
|
200
406
|
}
|
|
201
407
|
|
|
@@ -206,6 +412,11 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
|
|
|
206
412
|
return serialize(key, () => handleEvent(event))
|
|
207
413
|
}
|
|
208
414
|
|
|
415
|
+
/** How many people currently have messages waiting for their debounce window. */
|
|
416
|
+
function pendingCount() {
|
|
417
|
+
return pending.size
|
|
418
|
+
}
|
|
419
|
+
|
|
209
420
|
/** Send a draft the user approved. Cooldowns do not apply to an explicit action. */
|
|
210
421
|
async function approve(id) {
|
|
211
422
|
const row = store.outbox().find(entry => entry.id === id)
|
|
@@ -228,17 +439,34 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
|
|
|
228
439
|
return store.updateOutbox(id, { status: 'cancelled', decidedAt: new Date().toISOString() })
|
|
229
440
|
}
|
|
230
441
|
|
|
231
|
-
/**
|
|
442
|
+
/**
|
|
443
|
+
* Per-person usage for the panel: reply events this hour, the messages they
|
|
444
|
+
* covered, and the configured cap.
|
|
445
|
+
*/
|
|
232
446
|
function usage() {
|
|
233
447
|
const result = {}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
448
|
+
const rows = store.outbox()
|
|
449
|
+
const uins = new Set(rows.filter(row => (row.kind ?? 'reply') === 'reply').map(row => row.uin))
|
|
450
|
+
for (const uin of uins) {
|
|
451
|
+
const times = recentCount(uin)
|
|
452
|
+
if (times <= 0) continue
|
|
453
|
+
const care = store.careFor(uin)
|
|
454
|
+
const lastAt = rows
|
|
455
|
+
.filter(row => row.uin === uin
|
|
456
|
+
&& (row.kind ?? 'reply') === 'reply'
|
|
457
|
+
&& (row.status === 'sent' || row.status === 'sending'))
|
|
458
|
+
.reduce((latest, row) => Math.max(latest, stampOf(row)), 0)
|
|
459
|
+
result[uin] = {
|
|
460
|
+
lastHour: times,
|
|
461
|
+
coveredMessages: coveredMessages(uin),
|
|
462
|
+
lastAt: lastAt === 0 ? null : lastAt,
|
|
463
|
+
cap: care === undefined ? undefined : care.hourlyCap,
|
|
464
|
+
}
|
|
237
465
|
}
|
|
238
466
|
return result
|
|
239
467
|
}
|
|
240
468
|
|
|
241
|
-
return { handleEvent, enqueue, approve, cancel, usage }
|
|
469
|
+
return { handleEvent, enqueue, flush, pendingCount, approve, cancel, usage }
|
|
242
470
|
}
|
|
243
471
|
|
|
244
472
|
/** Count the AI-authored rows of one conversation, for the UI badge. */
|
package/lib/features.js
CHANGED
|
@@ -234,3 +234,108 @@ export function lastInbound(rows, targetUin) {
|
|
|
234
234
|
}
|
|
235
235
|
return undefined
|
|
236
236
|
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* What a group looks like as a room, rather than as a set of individuals.
|
|
240
|
+
*
|
|
241
|
+
* A group has no "the other person", so the usual measure() split does not apply:
|
|
242
|
+
* here the interesting facts are who speaks, when, how fast the room moves, and
|
|
243
|
+
* how much of it is addressed at me.
|
|
244
|
+
* @param {Array<object>} rows - every row of one group conversation.
|
|
245
|
+
* @param {string} [selfUin]
|
|
246
|
+
*/
|
|
247
|
+
export function groupFeatures(rows, selfUin = '') {
|
|
248
|
+
const ordered = [...rows].sort((left, right) => left.ts - right.ts)
|
|
249
|
+
const speakers = new Map()
|
|
250
|
+
for (const row of ordered) {
|
|
251
|
+
const uin = row.senderUin === '' ? 'unknown' : row.senderUin
|
|
252
|
+
const entry = speakers.get(uin) ?? { uin, names: new Map(), count: 0, chars: 0, questions: 0, decor: 0 }
|
|
253
|
+
entry.count += 1
|
|
254
|
+
entry.chars += String(row.text ?? '').length
|
|
255
|
+
if (isQuestion(row.text)) entry.questions += 1
|
|
256
|
+
entry.decor += decorationCount(row.text)
|
|
257
|
+
const name = String(row.senderName ?? '').trim()
|
|
258
|
+
if (name !== '') entry.names.set(name, (entry.names.get(name) ?? 0) + 1)
|
|
259
|
+
speakers.set(uin, entry)
|
|
260
|
+
}
|
|
261
|
+
const total = ordered.length
|
|
262
|
+
const ranked = [...speakers.values()]
|
|
263
|
+
.sort((left, right) => right.count - left.count)
|
|
264
|
+
.map(entry => ({
|
|
265
|
+
uin: entry.uin,
|
|
266
|
+
// The most frequent display name is the one the room actually uses.
|
|
267
|
+
name: [...entry.names.entries()].sort((left, right) => right[1] - left[1]).map(([name]) => name)[0] ?? '',
|
|
268
|
+
messages: entry.count,
|
|
269
|
+
share: total === 0 ? 0 : Math.round((entry.count / total) * 100) / 100,
|
|
270
|
+
avgChars: Math.round(entry.chars / Math.max(1, entry.count)),
|
|
271
|
+
questionRatio: Math.round((entry.questions / Math.max(1, entry.count)) * 100) / 100,
|
|
272
|
+
decorationPerMessage: Math.round((entry.decor / Math.max(1, entry.count)) * 100) / 100,
|
|
273
|
+
}))
|
|
274
|
+
|
|
275
|
+
// How crowded the room is: many speakers each saying a little, or a few loud ones.
|
|
276
|
+
const activeSpeakers = ranked.filter(entry => entry.messages >= 2).length
|
|
277
|
+
const topThreeShare = Math.round(ranked.slice(0, 3).reduce((sum, entry) => sum + entry.share, 0) * 100) / 100
|
|
278
|
+
|
|
279
|
+
const hours = Array.from({ length: 24 }, () => 0)
|
|
280
|
+
for (const row of ordered) hours[hourOf(row.ts)] += 1
|
|
281
|
+
const peakHours = hours
|
|
282
|
+
.map((count, hour) => ({ hour, count }))
|
|
283
|
+
.sort((left, right) => right.count - left.count)
|
|
284
|
+
.slice(0, 3)
|
|
285
|
+
.filter(entry => entry.count > 0)
|
|
286
|
+
.map(entry => entry.hour)
|
|
287
|
+
|
|
288
|
+
const activeDays = new Set(ordered.map(row => new Date(row.ts).toDateString())).size
|
|
289
|
+
const spanDays = ordered.length === 0
|
|
290
|
+
? 0
|
|
291
|
+
: Math.max(1, Math.round((ordered[ordered.length - 1].ts - ordered[0].ts) / (24 * 60 * 60 * 1000)))
|
|
292
|
+
|
|
293
|
+
// Bursts: consecutive messages less than two minutes apart are one conversation.
|
|
294
|
+
let bursts = 0
|
|
295
|
+
let inBurst = false
|
|
296
|
+
let fastestGap = Number.POSITIVE_INFINITY
|
|
297
|
+
for (let index = 0; index < ordered.length; index += 1) {
|
|
298
|
+
const previous = ordered[index - 1]
|
|
299
|
+
if (previous === undefined) {
|
|
300
|
+
inBurst = false
|
|
301
|
+
continue
|
|
302
|
+
}
|
|
303
|
+
const gap = ordered[index].ts - previous.ts
|
|
304
|
+
if (gap > 2000 && gap < fastestGap) fastestGap = gap
|
|
305
|
+
if (gap <= 120000) {
|
|
306
|
+
if (!inBurst) {
|
|
307
|
+
bursts += 1
|
|
308
|
+
inBurst = true
|
|
309
|
+
}
|
|
310
|
+
} else {
|
|
311
|
+
inBurst = false
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const textRows = ordered.filter(row => String(row.text ?? '').trim() !== '')
|
|
316
|
+
const links = textRows.filter(row => /https?:\/\//.test(row.text)).length
|
|
317
|
+
const atMe = selfUin === '' ? 0 : ordered.filter(row => String(row.text ?? '').includes(`@${selfUin}`)).length
|
|
318
|
+
const mineRows = selfUin === '' ? [] : ordered.filter(row => row.senderUin === selfUin)
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
totalMessages: total,
|
|
322
|
+
activeSpeakers,
|
|
323
|
+
topThreeShare,
|
|
324
|
+
speakers: ranked.slice(0, 12),
|
|
325
|
+
myMessages: mineRows.length,
|
|
326
|
+
myShare: total === 0 ? 0 : Math.round((mineRows.length / total) * 100) / 100,
|
|
327
|
+
atMeMessages: atMe,
|
|
328
|
+
avgChars: mean(textRows.map(row => row.text.length)),
|
|
329
|
+
questionRatio: textRows.length === 0 ? 0 : Math.round((textRows.filter(row => isQuestion(row.text)).length / textRows.length) * 100) / 100,
|
|
330
|
+
decorationPerMessage: textRows.length === 0 ? 0 : Math.round((textRows.reduce((sum, row) => sum + decorationCount(row.text), 0) / textRows.length) * 100) / 100,
|
|
331
|
+
linkShare: textRows.length === 0 ? 0 : Math.round((links / textRows.length) * 100) / 100,
|
|
332
|
+
hourHistogram: hours,
|
|
333
|
+
peakHours,
|
|
334
|
+
activeDays,
|
|
335
|
+
spanDays,
|
|
336
|
+
messagesPerActiveDay: activeDays === 0 ? 0 : Math.round(total / activeDays),
|
|
337
|
+
bursts,
|
|
338
|
+
fastestReplySeconds: Number.isFinite(fastestGap) ? Math.round(fastestGap / 1000) : 0,
|
|
339
|
+
lastContactDays: ordered.length === 0 ? null : Math.round((Date.now() - ordered[ordered.length - 1].ts) / (24 * 60 * 60 * 1000)),
|
|
340
|
+
}
|
|
341
|
+
}
|
package/lib/guard.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A cheap, deterministic filter for requests that are not casual chatting.
|
|
3
|
+
*
|
|
4
|
+
* Automatic replies exist to keep a conversation alive, not to do homework. A
|
|
5
|
+
* pasted exam question or "帮我写个爬虫" is both off-purpose and expensive, so the
|
|
6
|
+
* obvious cases are refused locally — no model call, no tokens — before the
|
|
7
|
+
* reply pipeline runs.
|
|
8
|
+
*
|
|
9
|
+
* The rules are deliberately conservative: everyday chat must never be blocked
|
|
10
|
+
* by accident. A friendly line that merely mentions numbers ("3+4 都算错") has no
|
|
11
|
+
* request verb, so it passes; a bare code block is only refused when it comes
|
|
12
|
+
* with a request or is long enough to be a task rather than a shared snippet.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Arithmetic with digits on both sides of an operator. */
|
|
16
|
+
const ARITHMETIC = /[\d))]\s*[-+*/^×÷%]\s*[\d((]/
|
|
17
|
+
const EQUATION = /\d\s*[xX×]\s*[\d^+]|=\s*[-]?\d|[xX]\s*\^\s*\d/
|
|
18
|
+
/** "算一下 / 求解 / 证明 / 等于多少" style request verbs. */
|
|
19
|
+
const MATH_VERB = /(算一下|算算|计算|求解|解方程|解一下|求导|积分|证明|因式分解|化简|几道题|这道题|题目|等于多少|是多少|得多少)/
|
|
20
|
+
/** Code fences, the most reliable signal of pasted code. */
|
|
21
|
+
const CODE_FENCE = /```|~~~/
|
|
22
|
+
/**
|
|
23
|
+
* A *request* to write or fix code. The imperative matters: "我写了个脚本 笑死"
|
|
24
|
+
* is a story, not a request, and must stay conversational.
|
|
25
|
+
*/
|
|
26
|
+
const CODE_REQUEST = /(帮我|给我|替我|麻烦|帮忙|能否|能不能|可不可以|你).{0,8}(写|改|修|调|优化|检查|看).{0,12}(代码|程序|脚本|函数|正则|报错|bug|BUG|sql|SQL|接口|爬虫|算法|leetcode|LeetCode)|^(写|改|修|实现|优化).{0,12}(代码|程序|脚本|函数|爬虫|算法)/
|
|
27
|
+
const HOMEWORK = /(作业|考卷|考试题|习题|卷子|复习题|练习题)/
|
|
28
|
+
const HOMEWORK_ASK = /(怎么做|怎么解|答案是|答案|帮我做|解一下|算一下|写一下)/
|
|
29
|
+
const LONG_TEXT_TASK = /(翻译|总结|概括|润色|改写|缩写).{0,14}(这|下面|以下|一下|整篇|全文|文章|内容|这段)/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Whether one inbound message is asking for non-conversational work.
|
|
33
|
+
* @param {string} text
|
|
34
|
+
* @returns {{ blocked: boolean, why: string }}
|
|
35
|
+
*/
|
|
36
|
+
export function isNonChatRequest(text) {
|
|
37
|
+
const full = String(text ?? '')
|
|
38
|
+
const trimmed = full.trim()
|
|
39
|
+
if (trimmed === '') return { blocked: false, why: '' }
|
|
40
|
+
|
|
41
|
+
if (CODE_REQUEST.test(trimmed)) return { blocked: true, why: 'code' }
|
|
42
|
+
if (CODE_FENCE.test(trimmed) && trimmed.length > 400) return { blocked: true, why: 'code' }
|
|
43
|
+
|
|
44
|
+
const mathy = ARITHMETIC.test(trimmed) || EQUATION.test(trimmed)
|
|
45
|
+
if (mathy && MATH_VERB.test(trimmed)) {
|
|
46
|
+
return { blocked: true, why: 'math' }
|
|
47
|
+
}
|
|
48
|
+
if (HOMEWORK.test(trimmed) && (mathy || HOMEWORK_ASK.test(trimmed))) {
|
|
49
|
+
return { blocked: true, why: 'homework' }
|
|
50
|
+
}
|
|
51
|
+
if (LONG_TEXT_TASK.test(trimmed) && trimmed.length > 200) {
|
|
52
|
+
return { blocked: true, why: 'long-text' }
|
|
53
|
+
}
|
|
54
|
+
return { blocked: false, why: '' }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The one-line reason stored on the outbox row. */
|
|
58
|
+
export function nonChatReason(why) {
|
|
59
|
+
const label = {
|
|
60
|
+
code: '写代码/改代码',
|
|
61
|
+
math: '数学题/计算',
|
|
62
|
+
homework: '作业题',
|
|
63
|
+
'long-text': '长文翻译或总结',
|
|
64
|
+
}[why] ?? '非日常任务'
|
|
65
|
+
return `对方在要我做${label},托管不接这类请求(不是闲聊)。`
|
|
66
|
+
}
|
package/lib/personas.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reply personas: the voice an automatic reply is written in.
|
|
3
|
+
*
|
|
4
|
+
* Only the default ships with the plugin: it imitates the user from their own
|
|
5
|
+
* transcripts. Every other voice is added by the user through the persona
|
|
6
|
+
* interface, so nothing in here needs to guess at a character they did not ask for.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Built-in presets. `prompt` is empty for the default: it uses the transcript. */
|
|
10
|
+
export const REPLY_PERSONAS = [
|
|
11
|
+
{
|
|
12
|
+
id: 'default',
|
|
13
|
+
name: '默认(像我本人)',
|
|
14
|
+
summary: '从你的聊天记录里学语气,回得像你自己。',
|
|
15
|
+
prompt: '',
|
|
16
|
+
},
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
/** The preset with this id, or undefined. */
|
|
20
|
+
export function presetPersona(id) {
|
|
21
|
+
return REPLY_PERSONAS.find(entry => entry.id === id)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Normalize one custom persona from storage.
|
|
26
|
+
* @returns {{ id: string, name: string, prompt: string, custom: true } | undefined}
|
|
27
|
+
*/
|
|
28
|
+
export function normalizeCustomPersona(raw) {
|
|
29
|
+
if (raw === null || typeof raw !== 'object') return undefined
|
|
30
|
+
const id = String(raw.id ?? '').trim()
|
|
31
|
+
const name = String(raw.name ?? '').trim().slice(0, 40)
|
|
32
|
+
const prompt = String(raw.prompt ?? '').trim().slice(0, 2000)
|
|
33
|
+
if (id === '' || name === '' || prompt === '') return undefined
|
|
34
|
+
return { id, name, prompt, custom: true, createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : '' }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Every persona the picker should show: built-in presets first, then custom. */
|
|
38
|
+
export function listPersonas(custom = []) {
|
|
39
|
+
const presets = REPLY_PERSONAS.map(entry => ({ ...entry, custom: false }))
|
|
40
|
+
const extras = (Array.isArray(custom) ? custom : []).map(normalizeCustomPersona).filter(entry => entry !== undefined)
|
|
41
|
+
return [...presets, ...extras]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Resolve the persona to use for a reply.
|
|
46
|
+
*
|
|
47
|
+
* An unknown id (a deleted custom persona, or a hand-edited file) falls back to
|
|
48
|
+
* the default rather than failing: a reply in the user's own voice is always a
|
|
49
|
+
* sane answer.
|
|
50
|
+
*/
|
|
51
|
+
export function resolvePersona(custom, id) {
|
|
52
|
+
const wanted = String(id ?? 'default')
|
|
53
|
+
return listPersonas(custom).find(entry => entry.id === wanted) ?? REPLY_PERSONAS[0]
|
|
54
|
+
}
|