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/store.js
CHANGED
|
@@ -64,6 +64,12 @@ function emptyMeta() {
|
|
|
64
64
|
personas: {},
|
|
65
65
|
/** Per-QQ-number automatic reply settings. */
|
|
66
66
|
care: {},
|
|
67
|
+
/** Per-conversation group analysis, keyed by conversation id. */
|
|
68
|
+
groupProfiles: {},
|
|
69
|
+
/** User-added reply personas; the built-in presets live in code. */
|
|
70
|
+
replyPersonas: [],
|
|
71
|
+
/** uin -> ISO time the hourly reply quota was last reset by hand. */
|
|
72
|
+
careReset: {},
|
|
67
73
|
/** User-arranged display order for the two left-hand lists. */
|
|
68
74
|
order: { conversations: [], people: [] },
|
|
69
75
|
/** Pinned conversation ids, first is topmost. Multiple pins allowed. */
|
|
@@ -83,6 +89,13 @@ export function defaultCare() {
|
|
|
83
89
|
quietTo: '08:00',
|
|
84
90
|
groupOnlyWhenMentioned: true,
|
|
85
91
|
maxReplyChars: 60,
|
|
92
|
+
/** Reply voice: 'default' (imitate me), a preset id, or a custom persona id. */
|
|
93
|
+
persona: 'default',
|
|
94
|
+
/**
|
|
95
|
+
* Seconds to wait before answering, so a burst of messages gets one reply
|
|
96
|
+
* instead of several. Every new message restarts the wait. 0 = answer at once.
|
|
97
|
+
*/
|
|
98
|
+
replyDelaySeconds: 5,
|
|
86
99
|
updatedAt: new Date().toISOString(),
|
|
87
100
|
}
|
|
88
101
|
}
|
|
@@ -94,6 +107,15 @@ function normalizeMeta(raw) {
|
|
|
94
107
|
const settings = raw.settings !== null && typeof raw.settings === 'object' ? raw.settings : {}
|
|
95
108
|
const onebot = settings.onebot !== null && typeof settings.onebot === 'object' ? settings.onebot : {}
|
|
96
109
|
const care = {}
|
|
110
|
+
// Personas are parsed first: a care entry may point at a custom one, and a
|
|
111
|
+
// persona that no longer exists must fall back to the default voice instead of
|
|
112
|
+
// leaving a dangling id in the settings.
|
|
113
|
+
const customPersonas = Array.isArray(raw.replyPersonas) ? raw.replyPersonas : []
|
|
114
|
+
const knownPersona = (id) => {
|
|
115
|
+
const value = typeof id === 'string' ? id : ''
|
|
116
|
+
if (value === 'default') return 'default'
|
|
117
|
+
return customPersonas.some(entry => entry !== null && typeof entry === 'object' && entry.id === value) ? value : 'default'
|
|
118
|
+
}
|
|
97
119
|
if (raw.care !== null && typeof raw.care === 'object') {
|
|
98
120
|
for (const [uin, value] of Object.entries(raw.care)) {
|
|
99
121
|
if (value === null || typeof value !== 'object') continue
|
|
@@ -108,6 +130,10 @@ function normalizeMeta(raw) {
|
|
|
108
130
|
quietTo: typeof value.quietTo === 'string' ? value.quietTo : fallback.quietTo,
|
|
109
131
|
groupOnlyWhenMentioned: value.groupOnlyWhenMentioned !== false,
|
|
110
132
|
maxReplyChars: Number.isFinite(Number(value.maxReplyChars)) ? Math.min(300, Math.max(10, Number(value.maxReplyChars))) : fallback.maxReplyChars,
|
|
133
|
+
persona: knownPersona(value.persona),
|
|
134
|
+
replyDelaySeconds: Number.isFinite(Number(value.replyDelaySeconds))
|
|
135
|
+
? Math.min(300, Math.max(0, Math.round(Number(value.replyDelaySeconds))))
|
|
136
|
+
: fallback.replyDelaySeconds,
|
|
111
137
|
updatedAt: typeof value.updatedAt === 'string' ? value.updatedAt : fallback.updatedAt,
|
|
112
138
|
}
|
|
113
139
|
}
|
|
@@ -151,6 +177,9 @@ function normalizeMeta(raw) {
|
|
|
151
177
|
adoptions: Array.isArray(raw.adoptions) ? raw.adoptions.filter(row => row !== null && typeof row === 'object') : [],
|
|
152
178
|
personas: raw.personas !== null && typeof raw.personas === 'object' ? raw.personas : {},
|
|
153
179
|
care,
|
|
180
|
+
groupProfiles: raw.groupProfiles !== null && typeof raw.groupProfiles === 'object' ? raw.groupProfiles : {},
|
|
181
|
+
replyPersonas: customPersonas,
|
|
182
|
+
careReset: raw.careReset !== null && typeof raw.careReset === 'object' ? raw.careReset : {},
|
|
154
183
|
order: {
|
|
155
184
|
conversations: Array.isArray(raw.order?.conversations) ? raw.order.conversations.filter(v => typeof v === 'string') : [],
|
|
156
185
|
people: Array.isArray(raw.order?.people) ? raw.order.people.filter(v => typeof v === 'string') : [],
|
|
@@ -387,6 +416,8 @@ export class Store {
|
|
|
387
416
|
this.state.conversations.splice(index, 1)
|
|
388
417
|
fs.rmSync(this.messagesFile(id), { force: true })
|
|
389
418
|
fs.rmSync(this.suggestionsFile(id), { force: true })
|
|
419
|
+
delete this.state.groupProfiles[id]
|
|
420
|
+
this.state.pinned = this.state.pinned.filter(value => value !== id)
|
|
390
421
|
this.save()
|
|
391
422
|
this.rebuildPeople()
|
|
392
423
|
return true
|
|
@@ -486,6 +517,68 @@ export class Store {
|
|
|
486
517
|
return this.state.selfProfile ?? null
|
|
487
518
|
}
|
|
488
519
|
|
|
520
|
+
/** Record one group analysis for a conversation. */
|
|
521
|
+
saveGroupProfile(conversationId, result) {
|
|
522
|
+
this.state.groupProfiles[conversationId] = { ...result, conversationId, updatedAt: new Date().toISOString() }
|
|
523
|
+
this.save()
|
|
524
|
+
return this.state.groupProfiles[conversationId]
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** The stored group analysis for a conversation, or undefined. */
|
|
528
|
+
groupProfile(conversationId) {
|
|
529
|
+
return this.state.groupProfiles[conversationId]
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** Every user-added reply persona. */
|
|
533
|
+
customPersonas() {
|
|
534
|
+
return this.state.replyPersonas
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Add one custom reply persona. The id is derived from a counter so it never
|
|
539
|
+
* collides with a built-in preset id.
|
|
540
|
+
* @param {{ name: string, prompt: string }} draft
|
|
541
|
+
*/
|
|
542
|
+
addReplyPersona(draft) {
|
|
543
|
+
const name = String(draft?.name ?? '').trim().slice(0, 40)
|
|
544
|
+
const prompt = String(draft?.prompt ?? '').trim().slice(0, 2000)
|
|
545
|
+
if (name === '' || prompt === '') return undefined
|
|
546
|
+
let index = this.state.replyPersonas.length + 1
|
|
547
|
+
const taken = new Set(this.state.replyPersonas.map(entry => entry.id))
|
|
548
|
+
while (taken.has(`custom-${index}`)) index += 1
|
|
549
|
+
const entry = { id: `custom-${index}`, name, prompt, createdAt: new Date().toISOString() }
|
|
550
|
+
this.state.replyPersonas.push(entry)
|
|
551
|
+
this.save()
|
|
552
|
+
return entry
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Remove one custom persona; returns whether it existed. */
|
|
556
|
+
removeReplyPersona(id) { const before = this.state.replyPersonas.length
|
|
557
|
+
this.state.replyPersonas = this.state.replyPersonas.filter(entry => entry.id !== id)
|
|
558
|
+
if (this.state.replyPersonas.length === before) return false
|
|
559
|
+
this.save()
|
|
560
|
+
return true
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Forget the hourly reply count for one person.
|
|
565
|
+
*
|
|
566
|
+
* Stored as a timestamp rather than by deleting outbox rows: the record of what
|
|
567
|
+
* was said stays intact, the quota simply starts counting from now.
|
|
568
|
+
*/
|
|
569
|
+
resetCareCount(uin) {
|
|
570
|
+
const key = String(uin)
|
|
571
|
+
this.state.careReset[key] = new Date().toISOString()
|
|
572
|
+
this.save()
|
|
573
|
+
return this.state.careReset[key]
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** When this person's quota was last reset by hand, in ms; 0 when never. */
|
|
577
|
+
careResetAt(uin) {
|
|
578
|
+
const at = Date.parse(this.state.careReset[String(uin)] ?? '')
|
|
579
|
+
return Number.isFinite(at) ? at : 0
|
|
580
|
+
}
|
|
581
|
+
|
|
489
582
|
/** Pin one conversation to the top; returns the pinned list, first is topmost. */
|
|
490
583
|
pin(id) {
|
|
491
584
|
if (!this.state.pinned.includes(id)) {
|
|
@@ -636,7 +729,7 @@ export class Store {
|
|
|
636
729
|
const next = { ...current }
|
|
637
730
|
if (typeof patch.enabled === 'boolean') next.enabled = patch.enabled
|
|
638
731
|
if (patch.mode === 'auto' || patch.mode === 'draft') next.mode = patch.mode
|
|
639
|
-
for (const [field, min, max] of [['hourlyCap', 1, 60], ['maxReplyChars', 10, 300]]) {
|
|
732
|
+
for (const [field, min, max] of [['hourlyCap', 1, 60], ['maxReplyChars', 10, 300], ['replyDelaySeconds', 0, 300]]) {
|
|
640
733
|
if (patch[field] === undefined) continue
|
|
641
734
|
const value = Number(patch[field])
|
|
642
735
|
if (Number.isFinite(value)) next[field] = Math.round(Math.min(max, Math.max(min, value)))
|
|
@@ -648,6 +741,10 @@ export class Store {
|
|
|
648
741
|
if (value === '' || minutesOfClock(value) !== undefined) next[field] = value
|
|
649
742
|
}
|
|
650
743
|
if (typeof patch.groupOnlyWhenMentioned === 'boolean') next.groupOnlyWhenMentioned = patch.groupOnlyWhenMentioned
|
|
744
|
+
// 'default', a preset id, or a custom persona id. An unknown id still saves —
|
|
745
|
+
// resolution falls back to the default voice, and a deleted custom persona
|
|
746
|
+
// should not silently rewrite the user's choice back to 'default'.
|
|
747
|
+
if (typeof patch.persona === 'string' && patch.persona.trim() !== '') next.persona = patch.persona.trim().slice(0, 60)
|
|
651
748
|
next.updatedAt = new Date().toISOString()
|
|
652
749
|
this.state.care[key] = next
|
|
653
750
|
this.save()
|
|
@@ -678,6 +775,19 @@ export class Store {
|
|
|
678
775
|
inboundTs: row.inboundTs ?? 0,
|
|
679
776
|
text: row.text ?? '',
|
|
680
777
|
status: row.status ?? 'draft',
|
|
778
|
+
// 'reply' for a normal answer, 'excuse' for the one polite brush-off sent
|
|
779
|
+
// when the hourly cap is reached.
|
|
780
|
+
kind: row.kind === 'excuse' ? 'excuse' : 'reply',
|
|
781
|
+
// How many inbound messages this one row answers (the debounce coalesces).
|
|
782
|
+
inboundCount: Number.isFinite(Number(row.inboundCount)) ? Number(row.inboundCount) : 1,
|
|
783
|
+
// Which reply persona produced this text, so the record stays readable after
|
|
784
|
+
// the persona is renamed or deleted.
|
|
785
|
+
personaId: typeof row.personaId === 'string' ? row.personaId : '',
|
|
786
|
+
personaName: typeof row.personaName === 'string' ? row.personaName : '',
|
|
787
|
+
// Size of the request this row was generated from, in characters.
|
|
788
|
+
promptChars: Number.isFinite(Number(row.promptChars)) ? Number(row.promptChars) : 0,
|
|
789
|
+
// Set when the message was refused as a non-chat request: 'math' | 'code' | …
|
|
790
|
+
taskRequest: typeof row.taskRequest === 'string' ? row.taskRequest : '',
|
|
681
791
|
reason: row.reason ?? '',
|
|
682
792
|
createdAt: row.createdAt ?? new Date().toISOString(),
|
|
683
793
|
decidedAt: row.decidedAt ?? null,
|
package/package.json
CHANGED
package/scripts/api-e2e.mjs
CHANGED
|
@@ -188,7 +188,7 @@ const SAMPLE = `消息对象:小明
|
|
|
188
188
|
|
|
189
189
|
try {
|
|
190
190
|
console.log('\n== routes ==')
|
|
191
|
-
check('all routes registered', routes.length ===
|
|
191
|
+
check('all routes registered', routes.length === 23, `${routes.length}`)
|
|
192
192
|
check('every route is GET or POST', routes.every(r => r.method === 'GET' || r.method === 'POST'))
|
|
193
193
|
check('every route sits below /api', routes.every(r => r.path.startsWith('/api/qq-affinity/')))
|
|
194
194
|
check('the bridge callback is not an /api route', !routes.some(r => r.path === '/qq-affinity/onebot'))
|
|
@@ -561,6 +561,22 @@ try {
|
|
|
561
561
|
check('and only the new lines, not the whole transcript', !prompts[prompts.length - 1].includes('【完整对话】'))
|
|
562
562
|
check('exactly one model call was spent', prompts.length === beforeIncremental + 1, `${prompts.length - beforeIncremental}`)
|
|
563
563
|
|
|
564
|
+
console.log('\n== the group route only accepts group chats ==')
|
|
565
|
+
result = await call('/api/qq-affinity/group', { method: 'POST', body: { conversationId: convId } })
|
|
566
|
+
check('a private chat is refused', result.status === 400 && String(result.value.error).includes('只有群聊'), JSON.stringify(result.value))
|
|
567
|
+
result = await call('/api/qq-affinity/group', { method: 'POST', body: {} })
|
|
568
|
+
check('a missing id is refused', result.status === 400, `${result.status}`)
|
|
569
|
+
result = await call('/api/qq-affinity/group', { method: 'POST', body: { conversationId: 'group:99999' } })
|
|
570
|
+
check('an unknown conversation is 404', result.status === 404, `${result.status}`)
|
|
571
|
+
|
|
572
|
+
console.log('\n== resetting the hourly reply count ==')
|
|
573
|
+
await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '10001', patch: { hourlyCap: 1 } } })
|
|
574
|
+
result = await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '10001', action: 'reset-count' } })
|
|
575
|
+
check('the reset succeeds', result.value.ok === true && typeof result.value.resetAt === 'string', JSON.stringify(result.value.resetAt))
|
|
576
|
+
check('the care settings come back unchanged', result.value.care.hourlyCap === 1, JSON.stringify(result.value.care))
|
|
577
|
+
result = await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '99999999', action: 'reset-count' } })
|
|
578
|
+
check('an unknown person is refused', result.status === 404, `${result.status}`)
|
|
579
|
+
|
|
564
580
|
console.log('\n== removal clears everything ==')
|
|
565
581
|
result = await call('/api/qq-affinity/conversation', { method: 'POST', body: { action: 'remove', id: convId } })
|
|
566
582
|
check('removed', result.value.state.conversations.length === 0)
|
package/scripts/care-e2e.mjs
CHANGED
|
@@ -21,16 +21,23 @@ const check = (label, condition, detail = '') => {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
const REPLY = '好呀,周六下午两点老地方见'
|
|
24
|
+
const EXCUSE = '我这边有点事 晚点再聊'
|
|
24
25
|
// Replies are rewritten into chat shape before they are stored or sent.
|
|
25
26
|
const STYLED_REPLY = styleReply(REPLY)
|
|
26
27
|
|
|
28
|
+
const prompts = []
|
|
27
29
|
const ctx = {
|
|
28
30
|
logger: { warn() {}, error() {}, info() {} },
|
|
29
31
|
get(name) {
|
|
30
32
|
if (name === 'llm') {
|
|
31
33
|
return {
|
|
32
|
-
stream:
|
|
33
|
-
|
|
34
|
+
stream: options => (async function* () {
|
|
35
|
+
// What the model was asked, so a refusal can be proven to cost nothing.
|
|
36
|
+
prompts.push(options?.messages?.[0]?.content?.[0]?.text ?? '')
|
|
37
|
+
// A brush-off is a different ask: answer it in kind so the assertions
|
|
38
|
+
// can tell an excuse apart from a normal reply.
|
|
39
|
+
const text = options?.purpose === 'qq-affinity-excuse' ? EXCUSE : REPLY
|
|
40
|
+
yield { type: 'text-delta', index: 0, text }
|
|
34
41
|
yield { type: 'finish', reason: { kind: 'stop' } }
|
|
35
42
|
})(),
|
|
36
43
|
}
|
|
@@ -107,7 +114,7 @@ try {
|
|
|
107
114
|
check('nothing was sent', sent.length === 0)
|
|
108
115
|
|
|
109
116
|
console.log('\n== draft mode ==')
|
|
110
|
-
store.setCare('10001', { enabled: true, mode: 'draft', hourlyCap: 5 })
|
|
117
|
+
store.setCare('10001', { enabled: true, mode: 'draft', hourlyCap: 5, replyDelaySeconds: 0 })
|
|
111
118
|
result = await engine.enqueue(eventOf())
|
|
112
119
|
check('drafts instead of sending', result.action === 'drafted', JSON.stringify(result))
|
|
113
120
|
check('still nothing sent', sent.length === 0)
|
|
@@ -169,10 +176,154 @@ try {
|
|
|
169
176
|
check('auto mode sends without asking', result.action === 'sent', JSON.stringify(result))
|
|
170
177
|
check('exactly one send was added', sent.length === beforeAuto + 1, `${beforeAuto} -> ${sent.length}`)
|
|
171
178
|
|
|
172
|
-
console.log('\n==
|
|
179
|
+
console.log('\n== the cap ends the chat with one polite excuse ==')
|
|
173
180
|
store.setCare('10001', { hourlyCap: 2 })
|
|
181
|
+
const excuseRowsBefore = store.outbox().filter(row => row.kind === 'excuse').length
|
|
182
|
+
const sendsBefore = sent.length
|
|
174
183
|
result = await engine.enqueue(eventOf({ raw_message: '再问一句' }))
|
|
175
|
-
check('
|
|
184
|
+
check('the cap produces a brush-off, not silence', result.action === 'declined', JSON.stringify(result))
|
|
185
|
+
check('something was actually sent', sent.length === sendsBefore + 1, `${sendsBefore} -> ${sent.length}`)
|
|
186
|
+
const excuseRows = store.outbox().filter(row => row.kind === 'excuse')
|
|
187
|
+
check('the row is marked as an excuse', excuseRows.length === excuseRowsBefore + 1, `${excuseRows.length}`)
|
|
188
|
+
const lastExcuse = excuseRows[excuseRows.length - 1]
|
|
189
|
+
check('the excuse was delivered as-is', lastExcuse.text === styleReply(EXCUSE), lastExcuse.text)
|
|
190
|
+
check('it was sent, not left as a draft', lastExcuse.status === 'sent', lastExcuse.status)
|
|
191
|
+
|
|
192
|
+
// Same hour, another message: silent, and no second excuse.
|
|
193
|
+
result = await engine.enqueue(eventOf({ raw_message: '人呢' }))
|
|
194
|
+
check('a second message after the excuse is skipped', result.action === 'skipped', JSON.stringify(result))
|
|
195
|
+
check('no second excuse is written', store.outbox().filter(row => row.kind === 'excuse').length === excuseRowsBefore + 1)
|
|
196
|
+
check('and nothing extra was sent', sent.length === sendsBefore + 1, `${sent.length}`)
|
|
197
|
+
|
|
198
|
+
console.log('\n== a burst after the excuse stays silent ==')
|
|
199
|
+
// However many messages arrive, the excuse happened once and only once.
|
|
200
|
+
for (let index = 0; index < 4; index += 1) {
|
|
201
|
+
result = await engine.enqueue(eventOf({ raw_message: `第 ${index} 条追问` }))
|
|
202
|
+
check(`message ${index + 1} is skipped`, result.action === 'skipped', JSON.stringify(result))
|
|
203
|
+
}
|
|
204
|
+
check('still exactly one excuse', store.outbox().filter(row => row.kind === 'excuse').length === excuseRowsBefore + 1)
|
|
205
|
+
check('still nothing extra sent', sent.length === sendsBefore + 1, `${sent.length}`)
|
|
206
|
+
|
|
207
|
+
console.log('\n== the quota survives a reload ==')
|
|
208
|
+
// A fresh engine has empty in-memory maps; the outbox must still say "capped
|
|
209
|
+
// and already excused", otherwise a restart would produce a second brush-off.
|
|
210
|
+
const reloaded = createCareEngine({
|
|
211
|
+
ctx,
|
|
212
|
+
store,
|
|
213
|
+
deliver: async (settings, target, text) => {
|
|
214
|
+
sent.push({ target, text })
|
|
215
|
+
return { messageId: `mid-${sent.length}` }
|
|
216
|
+
},
|
|
217
|
+
})
|
|
218
|
+
result = await reloaded.enqueue(eventOf({ raw_message: '重启之后还在吗' }))
|
|
219
|
+
check('after a reload the message is still skipped', result.action === 'skipped', JSON.stringify(result))
|
|
220
|
+
check('no new excuse after a reload', store.outbox().filter(row => row.kind === 'excuse').length === excuseRowsBefore + 1)
|
|
221
|
+
check('and nothing was sent', sent.length === sendsBefore + 1, `${sent.length}`)
|
|
222
|
+
|
|
223
|
+
console.log('\n== resetting the hourly count restores replies ==')
|
|
224
|
+
const sentBeforeReset = sent.length
|
|
225
|
+
store.resetCareCount('10001')
|
|
226
|
+
result = await engine.enqueue(eventOf({ raw_message: '刚才那个还没说完' }))
|
|
227
|
+
check('after a reset it answers again', result.action === 'sent', JSON.stringify(result))
|
|
228
|
+
check('a real reply went out', sent.length === sentBeforeReset + 1, `${sentBeforeReset} -> ${sent.length}`)
|
|
229
|
+
check('the reset is remembered on disk', store.careResetAt('10001') > 0, `${store.careResetAt('10001')}`)
|
|
230
|
+
// And the old excuse no longer suppresses anything: hitting the cap again may
|
|
231
|
+
// produce a fresh brush-off.
|
|
232
|
+
const excusesAfterReset = store.outbox().filter(row => row.kind === 'excuse').length
|
|
233
|
+
store.setCare('10001', { hourlyCap: 1 })
|
|
234
|
+
result = await engine.enqueue(eventOf({ raw_message: '再问一句' }))
|
|
235
|
+
check('a fresh cap can end with a new excuse', result.action === 'declined', JSON.stringify(result))
|
|
236
|
+
check('the excuse count grew', store.outbox().filter(row => row.kind === 'excuse').length === excusesAfterReset + 1)
|
|
237
|
+
store.setCare('10001', { hourlyCap: 10 })
|
|
238
|
+
console.log('\n== a burst waits, then gets one reply ==')
|
|
239
|
+
// The debounce window: each new message restarts it, and only when the other
|
|
240
|
+
// side goes quiet does one reply cover everything buffered.
|
|
241
|
+
store.setCare('10001', { replyDelaySeconds: 1 })
|
|
242
|
+
const burstBefore = sent.length
|
|
243
|
+
const burstOutboxBefore = store.outbox().length
|
|
244
|
+
result = await engine.enqueue(eventOf({ raw_message: '在吗' }))
|
|
245
|
+
check('the first message is queued, not answered', result.action === 'queued', JSON.stringify(result))
|
|
246
|
+
check('the wait is stated', /等 1 秒/.test(result.reason), result.reason)
|
|
247
|
+
check('nothing was sent yet', sent.length === burstBefore, `${sent.length}`)
|
|
248
|
+
result = await engine.enqueue(eventOf({ raw_message: '那个参数你看了吗' }))
|
|
249
|
+
check('a second message joins the same window', result.action === 'queued', JSON.stringify(result))
|
|
250
|
+
check('still nothing sent', sent.length === burstBefore)
|
|
251
|
+
check('both messages are archived right away', store.messages(conversation.id).filter(row => row.text === '那个参数你看了吗').length === 1)
|
|
252
|
+
check('one pending turn is buffered', engine.pendingCount() === 1, `${engine.pendingCount()}`)
|
|
253
|
+
|
|
254
|
+
// Let the real timer fire this time, so the schedule is exercised end to end.
|
|
255
|
+
await new Promise(done => setTimeout(done, 1300))
|
|
256
|
+
check('the timer flushed the burst', engine.pendingCount() === 0, `${engine.pendingCount()}`)
|
|
257
|
+
check('exactly one reply was sent', sent.length === burstBefore + 1, `${burstBefore} -> ${sent.length}`)
|
|
258
|
+
const burstRows = store.outbox().slice(burstOutboxBefore)
|
|
259
|
+
check('one outbox row covers the whole burst', burstRows.length === 1, JSON.stringify(burstRows.map(row => row.status)))
|
|
260
|
+
check('it records how many messages it answered', burstRows[0].inboundCount === 2, `${burstRows[0].inboundCount}`)
|
|
261
|
+
check('it answers the newest message', burstRows[0].inboundText === '那个参数你看了吗', burstRows[0].inboundText)
|
|
262
|
+
|
|
263
|
+
console.log('\n== the wait can be switched off ==')
|
|
264
|
+
store.setCare('10001', { replyDelaySeconds: 0 })
|
|
265
|
+
const immediateBefore = sent.length
|
|
266
|
+
result = await engine.enqueue(eventOf({ raw_message: '立刻回我' }))
|
|
267
|
+
check('zero delay answers at once', result.action === 'sent', JSON.stringify(result))
|
|
268
|
+
check('and it really sent', sent.length === immediateBefore + 1)
|
|
269
|
+
|
|
270
|
+
console.log('\n== a burst with nothing to answer is skipped once ==')
|
|
271
|
+
store.setCare('10001', { replyDelaySeconds: 0 })
|
|
272
|
+
const silentBefore = store.outbox().length
|
|
273
|
+
result = await engine.enqueue(eventOf({ raw_message: '[CQ:face,id=178]' }))
|
|
274
|
+
check('a bare face is skipped', result.action === 'skipped', JSON.stringify(result))
|
|
275
|
+
check('with one recorded reason', store.outbox().slice(silentBefore).length === 1, `${store.outbox().slice(silentBefore).length}`)
|
|
276
|
+
|
|
277
|
+
console.log('\n== one reply event counts as one 次, whatever it covers ==')
|
|
278
|
+
// The debounce folds a burst into a single reply; that reply is 一次, not 三条.
|
|
279
|
+
store.setCare('10001', { replyDelaySeconds: 0, hourlyCap: 20 })
|
|
280
|
+
const usageBefore = engine.usage()['10001']?.lastHour ?? 0
|
|
281
|
+
await engine.enqueue(eventOf({ raw_message: '第一句' }))
|
|
282
|
+
await engine.enqueue(eventOf({ raw_message: '第二句' }))
|
|
283
|
+
const usageAfter = engine.usage()['10001']
|
|
284
|
+
check('two answers took two 次', usageAfter.lastHour === usageBefore + 2, `${usageBefore} -> ${usageAfter.lastHour}`)
|
|
285
|
+
check('each 次 covered one message', usageAfter.coveredMessages >= 2, JSON.stringify(usageAfter))
|
|
286
|
+
check('the cap is reported alongside', usageAfter.cap === 20, JSON.stringify(usageAfter))
|
|
287
|
+
|
|
288
|
+
console.log('\n== every reply record names the persona that wrote it ==')
|
|
289
|
+
store.setCare('10001', { replyDelaySeconds: 0, hourlyCap: 20, persona: 'default' })
|
|
290
|
+
await engine.enqueue(eventOf({ raw_message: '用默认人设回我' }))
|
|
291
|
+
const defaultRow = store.outbox().slice(-1)[0]
|
|
292
|
+
check('the default voice is recorded', defaultRow.personaId === 'default', JSON.stringify(defaultRow.personaId))
|
|
293
|
+
check('and its display name too', defaultRow.personaName === '默认(像我本人)', defaultRow.personaName)
|
|
294
|
+
|
|
295
|
+
const voice = store.addReplyPersona({ name: '测试人设', prompt: '只用短句,语气平淡。' })
|
|
296
|
+
store.setCare('10001', { persona: voice.id })
|
|
297
|
+
await engine.enqueue(eventOf({ raw_message: '换个人设回我' }))
|
|
298
|
+
const customRow = store.outbox().slice(-1)[0]
|
|
299
|
+
check('a custom persona is recorded by id', customRow.personaId === voice.id, customRow.personaId)
|
|
300
|
+
check('and by the name shown in the picker', customRow.personaName === '测试人设', customRow.personaName)
|
|
301
|
+
// The record must survive the persona being deleted.
|
|
302
|
+
store.removeReplyPersona(voice.id)
|
|
303
|
+
const keptName = store.outbox().slice(-1)[0].personaName
|
|
304
|
+
check('the recorded name survives a delete', keptName === '测试人设', keptName)
|
|
305
|
+
store.setCare('10001', { persona: 'default' })
|
|
306
|
+
|
|
307
|
+
console.log('\n== one huge message cannot inflate the request ==')
|
|
308
|
+
store.setCare('10001', { replyDelaySeconds: 0, hourlyCap: 20, persona: 'default' })
|
|
309
|
+
const huge = '这是一段很长的消息'.repeat(2000) // 18000 chars
|
|
310
|
+
await engine.enqueue(eventOf({ raw_message: huge }))
|
|
311
|
+
const hugeRow = store.outbox().slice(-1)[0]
|
|
312
|
+
check('the request stayed bounded', hugeRow.promptChars > 0 && hugeRow.promptChars <= 6000, `${hugeRow.promptChars}`)
|
|
313
|
+
check('the inbound size was noted', hugeRow.inboundCount === 1, `${hugeRow.inboundCount}`)
|
|
314
|
+
check('the stored transcript keeps the full text', store.messages(conversation.id).some(row => row.text.length >= 18000), `${Math.max(...store.messages(conversation.id).map(row => row.text.length))}`)
|
|
315
|
+
|
|
316
|
+
console.log('\n== a homework question is refused without calling the model ==')
|
|
317
|
+
store.setCare('10001', { replyDelaySeconds: 0, hourlyCap: 20, persona: 'default' })
|
|
318
|
+
const promptsBefore = prompts.length
|
|
319
|
+
result = await engine.enqueue(eventOf({ raw_message: '帮我算一下 12345*6789 等于多少' }))
|
|
320
|
+
check('the request is skipped', result.action === 'skipped', JSON.stringify(result))
|
|
321
|
+
check('the reason says why', /数学题|非日常/.test(result.reason), result.reason)
|
|
322
|
+
check('no model call was spent', prompts.length === promptsBefore, `${prompts.length - promptsBefore}`)
|
|
323
|
+
const taskRow = store.outbox().slice(-1)[0]
|
|
324
|
+
check('the row is marked as a task request', taskRow.taskRequest === 'math', JSON.stringify(taskRow.taskRequest))
|
|
325
|
+
result = await engine.enqueue(eventOf({ raw_message: '今天真的好累啊' }))
|
|
326
|
+
check('ordinary chat is still answered', result.action === 'sent', JSON.stringify(result))
|
|
176
327
|
|
|
177
328
|
console.log('\n== a group only wakes on a mention ==')
|
|
178
329
|
const { conversation: group } = store.ensureConversation({ kind: 'group', title: '老同学群', groupUin: '555666' })
|
|
@@ -180,13 +331,13 @@ try {
|
|
|
180
331
|
store.appendMessages(group.id, [{ ts: Date.now() - 60000, senderName: '小明', senderUin: '10001', text: '大家好' }])
|
|
181
332
|
store.setCare('10001', { hourlyCap: 10 })
|
|
182
333
|
const before = store.messages(group.id).length
|
|
183
|
-
const
|
|
334
|
+
const groupOutboxBefore = store.outbox().length
|
|
184
335
|
result = await engine.enqueue(eventOf({ message_type: 'group', group_id: 555666, raw_message: '大家好' }))
|
|
185
336
|
check('an unmentioned group line is ignored', result.action === 'ignored' && result.reason === 'not-mentioned', JSON.stringify(result))
|
|
186
337
|
// The conversation is on, so the line belongs in its transcript; only the
|
|
187
338
|
// answering is skipped.
|
|
188
339
|
check('the line is still recorded', store.messages(group.id).length === before + 1, `${store.messages(group.id).length}`)
|
|
189
|
-
check('but no outbox row is written for it', store.outbox().length ===
|
|
340
|
+
check('but no outbox row is written for it', store.outbox().length === groupOutboxBefore, `${store.outbox().length}`)
|
|
190
341
|
result = await engine.enqueue(eventOf({ message_type: 'group', group_id: 555666, raw_message: `[CQ:at,qq=20002] 你说呢` }))
|
|
191
342
|
check('a mention is answered into the group', result.action === 'sent' || result.action === 'drafted', JSON.stringify(result))
|
|
192
343
|
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Group-room analysis: the statistics behind it, and the stored verdict.
|
|
2
|
+
// - groupFeatures(): who speaks, when, how fast the room moves
|
|
3
|
+
// - analyzeGroup(): cached, incremental, and stored per conversation
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import os from 'node:os'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
8
|
+
|
|
9
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
10
|
+
const href = (rel) => pathToFileURL(path.join(root, rel)).href
|
|
11
|
+
const { Store } = await import(href('lib/store.js'))
|
|
12
|
+
const { groupFeatures } = await import(href('lib/features.js'))
|
|
13
|
+
const { analyzeGroup } = await import(href('lib/analyze.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
|
+
const GROUP_ANSWER = JSON.stringify({
|
|
22
|
+
summary: '一个熟人局,白天聊工作和工具,晚上互相打趣。',
|
|
23
|
+
topics: [
|
|
24
|
+
{ label: '折腾配置', share: 0.4, evidence: '「这个参数我又调了一晚上」' },
|
|
25
|
+
{ label: '日常吐槽', share: 0.25, evidence: '「今天又加班」' },
|
|
26
|
+
],
|
|
27
|
+
atmosphere: {
|
|
28
|
+
label: '熟人局的日常碎碎念',
|
|
29
|
+
energy: 68,
|
|
30
|
+
warmth: 62,
|
|
31
|
+
order: 40,
|
|
32
|
+
seriousness: 35,
|
|
33
|
+
evidence: ['「笑死」连着刷了三条'],
|
|
34
|
+
},
|
|
35
|
+
coreMembers: [
|
|
36
|
+
{ uin: '10001', name: '小明', role: '话题发起', evidence: '每天都先开口' },
|
|
37
|
+
{ uin: '10002', name: '小红', role: '气氛担当', evidence: '「笑死」' },
|
|
38
|
+
],
|
|
39
|
+
norms: ['深夜不聊工作'],
|
|
40
|
+
cautions: ['别在群里催进度'],
|
|
41
|
+
howToJoin: ['接着别人的话茬问一句具体细节'],
|
|
42
|
+
confidence: 0.55,
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
const prompts = []
|
|
46
|
+
function fakeStream(options) {
|
|
47
|
+
prompts.push(options.messages?.[0]?.content?.[0]?.text ?? '')
|
|
48
|
+
const text = GROUP_ANSWER
|
|
49
|
+
return (async function* () {
|
|
50
|
+
for (let i = 0; i < text.length; i += 200) {
|
|
51
|
+
yield { type: 'text-delta', index: 0, text: text.slice(i, i + 200) }
|
|
52
|
+
}
|
|
53
|
+
yield { type: 'usage', usage: { inputTokens: 2400, outputTokens: 420 } }
|
|
54
|
+
yield { type: 'finish', reason: { kind: 'stop' } }
|
|
55
|
+
})()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function makeCtx() {
|
|
59
|
+
return {
|
|
60
|
+
get(name) {
|
|
61
|
+
if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'stub', model: 'stub-flash' }) }
|
|
62
|
+
if (name === 'llm') {
|
|
63
|
+
return {
|
|
64
|
+
stream: options => fakeStream(options),
|
|
65
|
+
listProviders: () => [{ id: 'stub' }],
|
|
66
|
+
listModels: async () => [{ id: 'stub-flash' }],
|
|
67
|
+
// Text-only, so the vision gate short-circuits and no download happens.
|
|
68
|
+
resolveModelInfo: async () => ({ inputModalities: ['text'] }),
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return undefined
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ------------------------------------------------------------------ fixture
|
|
77
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-group-'))
|
|
78
|
+
process.env.DSH_QQ_AFFINITY_HOME = dir
|
|
79
|
+
const store = new Store(dir)
|
|
80
|
+
store.state.settings.selfUin = '20002'
|
|
81
|
+
store.state.settings.selfName = '我'
|
|
82
|
+
const conversation = store.ensureConversation({ kind: 'group', title: '折腾群', groupUin: '900123' }).conversation
|
|
83
|
+
store.setEnabled(conversation.id, true)
|
|
84
|
+
|
|
85
|
+
const base = Date.UTC(2024, 0, 1, 12, 0, 0)
|
|
86
|
+
const speakers = ['10001', '10002', '10003']
|
|
87
|
+
const rows = []
|
|
88
|
+
for (let index = 0; index < 30; index += 1) {
|
|
89
|
+
const isMine = index % 10 === 7
|
|
90
|
+
const sender = isMine ? '20002' : speakers[index % speakers.length]
|
|
91
|
+
const text = index % 6 === 0
|
|
92
|
+
? `@20002 这个参数我又调了一晚上 ${index}`
|
|
93
|
+
: index % 4 === 0 ? '笑死' : `第 ${index} 条,今天又加班`
|
|
94
|
+
rows.push({ ts: base + index * 60_000, senderUin: sender, senderName: sender === '10001' ? '小明' : sender === '10002' ? '小红' : sender === '10003' ? '小刚' : '我', text })
|
|
95
|
+
}
|
|
96
|
+
store.appendMessages(conversation.id, rows)
|
|
97
|
+
|
|
98
|
+
console.log('\n== groupFeatures reads the room ==')
|
|
99
|
+
const features = groupFeatures(store.messages(conversation.id), '20002')
|
|
100
|
+
check('counts every message', features.totalMessages === 30, `${features.totalMessages}`)
|
|
101
|
+
check('finds the speakers', features.activeSpeakers === 4, `${features.activeSpeakers}`)
|
|
102
|
+
check('ranks the busiest first', features.speakers[0].messages >= features.speakers[1].messages, JSON.stringify(features.speakers.map(s => s.messages)))
|
|
103
|
+
check('names come from the rows', features.speakers.some(speaker => speaker.name === '小明'), JSON.stringify(features.speakers.map(s => s.name)))
|
|
104
|
+
check('my share is counted', features.myMessages === 3 && features.myShare > 0, `${features.myMessages}/${features.myShare}`)
|
|
105
|
+
check('mentions of me are counted', features.atMeMessages === 5, `${features.atMeMessages}`)
|
|
106
|
+
check('hours come from the clock', features.hourHistogram.length === 24 && features.peakHours.length >= 1, JSON.stringify(features.peakHours))
|
|
107
|
+
check('shares add up to about one', Math.abs(features.speakers.reduce((sum, speaker) => sum + speaker.share, 0) - 1) < 0.02, String(features.speakers.reduce((sum, speaker) => sum + speaker.share, 0)))
|
|
108
|
+
check('bursts are detected', features.bursts >= 1, `${features.bursts}`)
|
|
109
|
+
|
|
110
|
+
console.log('\n== analyzeGroup asks the model once and stores the verdict ==')
|
|
111
|
+
const ctx = makeCtx()
|
|
112
|
+
const first = await analyzeGroup(ctx, store, conversation.id)
|
|
113
|
+
check('it returns a summary', typeof first.summary === 'string' && first.summary !== '', first.summary)
|
|
114
|
+
check('topics came through', first.topics.length === 2 && first.topics[0].share > 0, JSON.stringify(first.topics))
|
|
115
|
+
check('the atmosphere has four dimensions', typeof first.atmosphere.energy === 'number' && typeof first.atmosphere.warmth === 'number'
|
|
116
|
+
&& typeof first.atmosphere.order === 'number' && typeof first.atmosphere.seriousness === 'number', JSON.stringify(first.atmosphere))
|
|
117
|
+
check('core members keep their uin', first.coreMembers[0].uin === '10001', JSON.stringify(first.coreMembers))
|
|
118
|
+
check('norms and cautions are stored', first.norms.length === 1 && first.cautions.length === 1, JSON.stringify([first.norms, first.cautions]))
|
|
119
|
+
check('the prompt names the group', prompts[0].includes('折腾群'), prompts[0].slice(0, 80))
|
|
120
|
+
check('the prompt carries the speaker table', prompts[0].includes('说话人分布'), prompts[0].slice(0, 200))
|
|
121
|
+
check('token usage is recorded', first.usage.inputTokens === 2400, JSON.stringify(first.usage))
|
|
122
|
+
check('the measured stats ride along', first.stats.activeSpeakers === 4 && first.stats.atMeMessages === 5, JSON.stringify(first.stats).slice(0, 120))
|
|
123
|
+
check('the verdict is stored on the conversation', store.groupProfile(conversation.id)?.summary === first.summary, 'ok')
|
|
124
|
+
check('the evidence is fingerprinted', typeof first.basedOn.fingerprint === 'string' && first.basedOn.fingerprint !== '', first.basedOn.fingerprint)
|
|
125
|
+
|
|
126
|
+
console.log('\n== unchanged evidence is reused ==')
|
|
127
|
+
const callsBefore = prompts.length
|
|
128
|
+
const second = await analyzeGroup(ctx, store, conversation.id)
|
|
129
|
+
check('the stored analysis is reused', second.reused === true, String(second.reused))
|
|
130
|
+
check('no model call was made', prompts.length === callsBefore, `${prompts.length - callsBefore}`)
|
|
131
|
+
|
|
132
|
+
console.log('\n== new messages switch to an incremental run ==')
|
|
133
|
+
store.appendMessages(conversation.id, [
|
|
134
|
+
{ ts: base + 30 * 60_000 + 5 * 60_000, senderUin: '10002', senderName: '小红', text: '今晚谁还在' },
|
|
135
|
+
])
|
|
136
|
+
const third = await analyzeGroup(ctx, store, conversation.id)
|
|
137
|
+
check('the run is incremental', third.basedOn.incremental === true, JSON.stringify(third.basedOn))
|
|
138
|
+
check('it only covers the new rows', third.basedOn.deltaMessages === 1, `${third.basedOn.deltaMessages}`)
|
|
139
|
+
check('the prompt carries the previous verdict', prompts[prompts.length - 1].includes('【上次的群聊分析'), prompts[prompts.length - 1].slice(0, 120))
|
|
140
|
+
|
|
141
|
+
console.log('\n== guards ==')
|
|
142
|
+
const privateChat = store.ensureConversation({ kind: 'c2c', title: '私聊', peerUin: '10001' }).conversation
|
|
143
|
+
let refused = ''
|
|
144
|
+
try {
|
|
145
|
+
await analyzeGroup(ctx, store, privateChat.id)
|
|
146
|
+
} catch (error) {
|
|
147
|
+
refused = error.message
|
|
148
|
+
}
|
|
149
|
+
check('a private chat is refused', refused.includes('只有群聊'), refused)
|
|
150
|
+
const tiny = store.ensureConversation({ kind: 'group', title: '空群', groupUin: '900999' }).conversation
|
|
151
|
+
store.setEnabled(tiny.id, true)
|
|
152
|
+
let tooSmall = ''
|
|
153
|
+
try {
|
|
154
|
+
await analyzeGroup(ctx, store, tiny.id)
|
|
155
|
+
} catch (error) {
|
|
156
|
+
tooSmall = error.message
|
|
157
|
+
}
|
|
158
|
+
check('a tiny group is refused', tooSmall.includes('至少需要 20 条'), tooSmall)
|
|
159
|
+
|
|
160
|
+
console.log('\n== deleting a group drops its analysis ==')
|
|
161
|
+
store.removeConversation(conversation.id)
|
|
162
|
+
check('the stored analysis is gone', store.groupProfile(conversation.id) === undefined, 'ok')
|
|
163
|
+
|
|
164
|
+
console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
|
|
165
|
+
fs.rmSync(dir, { recursive: true, force: true })
|
|
166
|
+
process.exit(failures === 0 ? 0 : 1)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// The non-chat filter: a pasted exam question must be refused locally, and
|
|
2
|
+
// everyday chat must never be blocked by accident.
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
|
|
6
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
7
|
+
const { isNonChatRequest, nonChatReason } = await import(pathToFileURL(path.join(root, 'lib/guard.js')).href)
|
|
8
|
+
|
|
9
|
+
let failures = 0
|
|
10
|
+
const check = (label, ok, extra = '') => {
|
|
11
|
+
console.log(` ${ok ? 'ok ' : 'FAIL'} ${label}${extra === '' ? '' : ` :: ${extra}`}`)
|
|
12
|
+
if (!ok) failures += 1
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
console.log('\n== requests that are not chatting ==')
|
|
16
|
+
const blocked = [
|
|
17
|
+
['帮我算一下 12345*6789', 'math'],
|
|
18
|
+
['解方程 x^2-3x+2=0', 'math'],
|
|
19
|
+
['12345*6789 等于多少', 'math'],
|
|
20
|
+
['作业第3题怎么做', 'homework'],
|
|
21
|
+
['帮我写个爬虫', 'code'],
|
|
22
|
+
['你帮我改一下这段代码', 'code'],
|
|
23
|
+
['能不能帮我写个正则', 'code'],
|
|
24
|
+
]
|
|
25
|
+
for (const [text, why] of blocked) {
|
|
26
|
+
const result = isNonChatRequest(text)
|
|
27
|
+
check(`refused: ${text}`, result.blocked === true && result.why === why, JSON.stringify(result))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
console.log('\n== ordinary chat must pass ==')
|
|
31
|
+
const allowed = [
|
|
32
|
+
'今天好累啊',
|
|
33
|
+
'3+4 都算错了吧哈哈',
|
|
34
|
+
'我写了个脚本 笑死',
|
|
35
|
+
'今天的作业好多啊',
|
|
36
|
+
'这道菜怎么做',
|
|
37
|
+
'周末去看展吗',
|
|
38
|
+
'帮我翻译一下这段',
|
|
39
|
+
'```js\nconsole.log(1)\n```',
|
|
40
|
+
'',
|
|
41
|
+
'在吗',
|
|
42
|
+
]
|
|
43
|
+
for (const text of allowed) {
|
|
44
|
+
const result = isNonChatRequest(text)
|
|
45
|
+
check(`passes: ${JSON.stringify(text)}`, result.blocked === false, JSON.stringify(result))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
console.log('\n== the recorded reason reads like a sentence ==')
|
|
49
|
+
check('math', nonChatReason('math').includes('数学题'), nonChatReason('math'))
|
|
50
|
+
check('code', nonChatReason('code').includes('代码'), nonChatReason('code'))
|
|
51
|
+
check('homework', nonChatReason('homework').includes('作业'), nonChatReason('homework'))
|
|
52
|
+
check('long text', nonChatReason('long-text').includes('长文'), nonChatReason('long-text'))
|
|
53
|
+
check('an unknown kind still reads fine', nonChatReason('mystery').includes('非日常'), nonChatReason('mystery'))
|
|
54
|
+
|
|
55
|
+
console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
|
|
56
|
+
process.exit(failures === 0 ? 0 : 1)
|