dsh-qq-affinity 1.5.6 → 1.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -20,7 +20,7 @@ window.__ModuleLoader__.load({
20
20
  * This bundle's version. The Host reports its own; when the two differ the
21
21
  * panel says so, because a stale bundle otherwise looks like a broken button.
22
22
  */
23
- const VERSION = '1.5.5'
23
+ const VERSION = '1.7.4'
24
24
 
25
25
  // ---------------------------------------------------------------- palette
26
26
 
@@ -82,8 +82,7 @@ window.__ModuleLoader__.load({
82
82
  : C.layer1)
83
83
 
84
84
  /** Distinct accent per list position, so neighbouring traits never match. */
85
- const TRAIT_COLORS = [
86
- () => C.brand,
85
+ const TRAIT_COLORS = [ () => C.brand,
87
86
  () => mix(C.brand, C.success, 45),
88
87
  () => C.success,
89
88
  () => mix(C.success, C.warn, 50),
@@ -92,6 +91,13 @@ window.__ModuleLoader__.load({
92
91
  ]
93
92
  const traitColor = (index) => (supportsColorMix ? TRAIT_COLORS[index % TRAIT_COLORS.length]() : C.brand)
94
93
 
94
+ /**
95
+ * The contribution chart reuses the score palette on purpose: green for the
96
+ * people who carry the room, warm colours for the quiet end. Same bands as
97
+ * the favour meters, so the two charts read as one visual language.
98
+ */
99
+ const contributionColor = (position) => tone(Math.round(Math.min(1, Math.max(0, position)) * 100))
100
+
95
101
  /** "正在分析" 已经跑了多久: 12 秒 / 3 分 5 秒 / 1 小时 2 分. */
96
102
  function formatElapsed(ms) {
97
103
  const total = Math.max(0, Math.round(Number(ms) / 1000))
@@ -1219,6 +1225,7 @@ window.__ModuleLoader__.load({
1219
1225
  h('div', { key: 'top', style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } }, [
1220
1226
  h(Chip, { key: 's', color: OUTBOX_COLOR(row.status) }, OUTBOX_LABEL[row.status] ?? row.status),
1221
1227
  row.kind === 'excuse' ? h(Chip, { key: 'k', color: C.warn }, '推辞(到上限)') : null,
1228
+ row.taskRequest === undefined || row.taskRequest === '' ? null : h(Chip, { key: 'tr', color: C.warn }, '非日常请求(已拒绝)'),
1222
1229
  row.personaId === undefined || row.personaId === '' ? null : h(Chip, {
1223
1230
  key: 'p',
1224
1231
  color: row.personaId === 'default' ? C.idle : C.brand,
@@ -3532,6 +3539,8 @@ window.__ModuleLoader__.load({
3532
3539
  style: { margin: 0, paddingLeft: 18, fontSize: 11.5, color: C.label2, lineHeight: 1.8 },
3533
3540
  }, (atmosphere.evidence ?? []).map((line, index) => h('li', { key: index }, line))),
3534
3541
 
3542
+ contributionChart(group),
3543
+
3535
3544
  (group.coreMembers ?? []).length === 0 ? null : h('div', { key: 'core', style: { display: 'flex', flexDirection: 'column', gap: 5 } }, [
3536
3545
  h('div', { key: 'h', style: { fontSize: 12, color: C.label2 } }, '谁在撑这个群'),
3537
3546
  ...group.coreMembers.map((member, index) => {
@@ -3584,6 +3593,174 @@ window.__ModuleLoader__.load({
3584
3593
  ])
3585
3594
  }
3586
3595
 
3596
+ /**
3597
+ * Group contribution: the people who carry the room, with their avatar, and
3598
+ * a column chart underneath.
3599
+ *
3600
+ * The numbers come from the measured speakers, not from the model, so the
3601
+ * chart is exact. Avatars are QQ's public CDN by QQ number; when that image
3602
+ * cannot load (offline, or blocked), the circle falls back to an initial so
3603
+ * the row never collapses.
3604
+ */
3605
+ function contributionChart(group) {
3606
+ const stats = group.stats ?? {}
3607
+ const speakers = (stats.speakers ?? []).filter(speaker => speaker.uin !== 'unknown')
3608
+ if (speakers.length === 0) return null
3609
+ const top = speakers.slice(0, 6)
3610
+ // Bar height ranks against the leader; colour spreads across the visible
3611
+ // range, so six near-equal shares still read as six different shades.
3612
+ const maxShare = Math.max(...top.map(speaker => speaker.share), 0.01)
3613
+ const minShare = Math.min(...top.map(speaker => speaker.share))
3614
+ const shareSpan = maxShare - minShare
3615
+ const positionOf = (speaker) => (shareSpan > 0.0001
3616
+ ? (speaker.share - minShare) / shareSpan
3617
+ // Everyone identical: show them all at the strong end rather than
3618
+ // inventing differences that the numbers do not support.
3619
+ : 1)
3620
+ const selfUin = state.settings?.selfUin ?? ''
3621
+ const label = (speaker) => (speaker.name === '' ? `QQ ${speaker.uin}` : speaker.name)
3622
+ return h('div', { key: 'contribution', style: { display: 'flex', flexDirection: 'column', gap: 6 } }, [
3623
+ h('div', {
3624
+ key: 'h',
3625
+ style: { display: 'flex', alignItems: 'baseline', gap: 8, fontSize: 12, color: C.label2 },
3626
+ }, [
3627
+ h('span', { key: 't', style: { color: C.label, fontWeight: 600 } }, '群贡献'),
3628
+ h('span', { key: 's' }, `发言最多的 ${top.length} 人 · 柱高 = 发言占比`),
3629
+ ]),
3630
+ // Legend: the colour is the ranking, not decoration.
3631
+ h('div', {
3632
+ key: 'legend',
3633
+ style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: 10.5, color: C.label2 },
3634
+ }, [
3635
+ h('span', { key: 'l' }, '贡献低'),
3636
+ h('div', {
3637
+ key: 'g',
3638
+ 'aria-hidden': true,
3639
+ style: {
3640
+ flex: '0 0 92px',
3641
+ height: 5,
3642
+ borderRadius: 999,
3643
+ overflow: 'hidden',
3644
+ display: 'flex',
3645
+ },
3646
+ // Same band gradient the score legend uses, low → high.
3647
+ }, [...BANDS].reverse().map(([, color], index) => h('div', {
3648
+ key: index,
3649
+ style: { flex: 1, background: color() },
3650
+ }))),
3651
+ h('span', { key: 'r' }, '贡献高'),
3652
+ ]),
3653
+ h('div', {
3654
+ key: 'chart',
3655
+ style: {
3656
+ display: 'grid',
3657
+ gridTemplateColumns: `repeat(${top.length}, minmax(0, 1fr))`,
3658
+ gap: 8,
3659
+ alignItems: 'end',
3660
+ padding: '10px 4px 2px',
3661
+ background: C.bg,
3662
+ border: `1px solid ${C.border1}`,
3663
+ borderRadius: 10,
3664
+ },
3665
+ }, top.map((speaker, index) => {
3666
+ const isMe = selfUin !== '' && speaker.uin === selfUin
3667
+ const height = Math.max(6, Math.round((speaker.share / maxShare) * 100))
3668
+ // Colour follows the score palette: the loudest of the six lands in the
3669
+ // green band, the quietest in the warm end.
3670
+ const position = positionOf(speaker)
3671
+ const color = contributionColor(position)
3672
+ const initial = (label(speaker).trim()[0] ?? '?').toUpperCase()
3673
+ return h('div', {
3674
+ key: speaker.uin,
3675
+ title: `${label(speaker)}:${speaker.messages} 条,占 ${Math.round(speaker.share * 100)}%,平均 ${speaker.avgChars} 字(色阶位置 ${Math.round(position * 100)}%)`,
3676
+ style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, minWidth: 0 },
3677
+ }, [
3678
+ // Avatar, with a lettered circle behind it for when the CDN is unreachable.
3679
+ h('div', {
3680
+ key: 'av',
3681
+ style: {
3682
+ position: 'relative',
3683
+ width: 34,
3684
+ height: 34,
3685
+ borderRadius: 999,
3686
+ overflow: 'hidden',
3687
+ flex: '0 0 auto',
3688
+ background: tint(color, 18),
3689
+ border: `1px solid ${isMe ? C.warn : C.border1}`,
3690
+ display: 'flex',
3691
+ alignItems: 'center',
3692
+ justifyContent: 'center',
3693
+ fontSize: 13,
3694
+ fontWeight: 600,
3695
+ color,
3696
+ },
3697
+ }, [
3698
+ h('span', { key: 'i', style: { position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' } }, initial),
3699
+ h('img', {
3700
+ key: 'img',
3701
+ src: `https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(speaker.uin)}&s=100`,
3702
+ alt: '',
3703
+ loading: 'lazy',
3704
+ referrerPolicy: 'no-referrer',
3705
+ onError: (event) => { event.currentTarget.style.display = 'none' },
3706
+ onLoad: (event) => { event.currentTarget.style.position = 'absolute' },
3707
+ style: {
3708
+ width: '100%',
3709
+ height: '100%',
3710
+ objectFit: 'cover',
3711
+ display: 'block',
3712
+ },
3713
+ }),
3714
+ ]),
3715
+ h('div', {
3716
+ key: 'n',
3717
+ style: {
3718
+ fontSize: 10.5,
3719
+ color: isMe ? C.warn : C.label2,
3720
+ maxWidth: '100%',
3721
+ overflow: 'hidden',
3722
+ textOverflow: 'ellipsis',
3723
+ whiteSpace: 'nowrap',
3724
+ },
3725
+ }, isMe ? '我' : label(speaker)),
3726
+ // The column itself: height is proportional to the share of speech.
3727
+ h('div', {
3728
+ key: 'bar',
3729
+ 'aria-hidden': true,
3730
+ style: {
3731
+ width: '100%',
3732
+ height: 78,
3733
+ display: 'flex',
3734
+ alignItems: 'flex-end',
3735
+ justifyContent: 'center',
3736
+ },
3737
+ }, h('div', {
3738
+ style: {
3739
+ width: '62%',
3740
+ height: `${height}%`,
3741
+ minHeight: 4,
3742
+ background: color,
3743
+ borderRadius: '3px 3px 0 0',
3744
+ transition: 'height 240ms cubic-bezier(.2,.8,.2,1)',
3745
+ },
3746
+ })),
3747
+ h('div', {
3748
+ key: 'v',
3749
+ style: { fontSize: 10.5, color: C.label, fontVariantNumeric: 'tabular-nums' },
3750
+ }, `${Math.round(speaker.share * 100)}%`),
3751
+ h('div', {
3752
+ key: 'c',
3753
+ style: { fontSize: 10, color: C.label2, fontVariantNumeric: 'tabular-nums' },
3754
+ }, `${speaker.messages} 条`),
3755
+ ])
3756
+ })),
3757
+ selfUin === '' || top.some(speaker => speaker.uin === selfUin)
3758
+ ? null
3759
+ : h('div', { key: 'me', style: { fontSize: 10.5, color: C.label2 } },
3760
+ `我不在前 ${top.length} 名里,我的发言占 ${Math.round((stats.myShare ?? 0) * 100)}%。`),
3761
+ ])
3762
+ }
3763
+
3587
3764
  function personDetail(row) {
3588
3765
  const stored = row.score
3589
3766
  const persona = row.persona ?? null
package/lib/analyze.js CHANGED
@@ -396,7 +396,8 @@ export async function writeAutoReply(ctx, store, request) {
396
396
  '5. 不要问超过一个问题,不要连着寒暄,不要用「哈哈」「亲」这类套话开头。',
397
397
  '6. 如果对方说的是坏消息、求助或情绪问题,先接住情绪,不要急着给建议。',
398
398
  '7. 不要承诺时间、地点、金额这类具体事项 —— 这些需要我自己确认。',
399
- inCharacter ? '8. 保持人设,但不要写动作描写、不要用括号、不要说「(微笑)」这类旁白。' : '',
399
+ '8. 只聊日常。如果对方要你解题、写代码、写论文、做表格这类正经活儿,不要真的去做,也不要说「我看看」——用一句日常的话推掉,例如「这个我可算不明白 你找找会的」「我脑子不够用 换个人问吧」。翻译和总结照常帮忙,那属于日常聊天。',
400
+ inCharacter ? '9. 保持人设,但不要写动作描写、不要用括号、不要说「(微笑)」这类旁白。' : '',
400
401
  ].filter(line => line !== '').join('\n')
401
402
 
402
403
  // The message being answered may itself be a picture or a sticker.
package/lib/care.js CHANGED
@@ -17,7 +17,8 @@
17
17
  import { plainText, send as sendThroughBridge } from './onebot.js'
18
18
  import { inQuietHours, isAiAuthored, uid } from './util.js'
19
19
  import { writeAutoReply, writeCapExcuse, cannedExcuse } from './analyze.js'
20
- import { resolvePersona } from './personas.js'
20
+ import { resolvePersona } from './personas.js'
21
+ import { isNonChatRequest, nonChatReason } from './guard.js'
21
22
 
22
23
  const HOUR = 60 * 60 * 1000
23
24
 
@@ -303,6 +304,12 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
303
304
  const event = usable[usable.length - 1]
304
305
  // The voice in force right now, recorded on every row it produces.
305
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
+ }
306
313
  if (inQuietHours(nowMinutes(), care.quietFrom, care.quietTo)) {
307
314
  return skip(`落在免打扰时段(${care.quietFrom}–${care.quietTo})。`)
308
315
  }
package/lib/guard.js ADDED
@@ -0,0 +1,63 @@
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
+
30
+ /**
31
+ * Whether one inbound message is asking for non-conversational work.
32
+ * @param {string} text
33
+ * @returns {{ blocked: boolean, why: string }}
34
+ */
35
+ export function isNonChatRequest(text) {
36
+ const full = String(text ?? '')
37
+ const trimmed = full.trim()
38
+ if (trimmed === '') return { blocked: false, why: '' }
39
+
40
+ if (CODE_REQUEST.test(trimmed)) return { blocked: true, why: 'code' }
41
+ if (CODE_FENCE.test(trimmed) && trimmed.length > 400) return { blocked: true, why: 'code' }
42
+
43
+ const mathy = ARITHMETIC.test(trimmed) || EQUATION.test(trimmed)
44
+ if (mathy && MATH_VERB.test(trimmed)) {
45
+ return { blocked: true, why: 'math' }
46
+ }
47
+ if (HOMEWORK.test(trimmed) && (mathy || HOMEWORK_ASK.test(trimmed))) {
48
+ return { blocked: true, why: 'homework' }
49
+ }
50
+ // Translation and summarising are deliberately NOT refused: the user asked for
51
+ // them to go through, and the prompt cap keeps the cost bounded.
52
+ return { blocked: false, why: '' }
53
+ }
54
+
55
+ /** The one-line reason stored on the outbox row. */
56
+ export function nonChatReason(why) {
57
+ const label = {
58
+ code: '写代码/改代码',
59
+ math: '数学题/计算',
60
+ homework: '作业题',
61
+ }[why] ?? '非日常任务'
62
+ return `对方在要我做${label},托管不接这类请求(不是闲聊)。`
63
+ }
package/lib/store.js CHANGED
@@ -786,6 +786,8 @@ export class Store {
786
786
  personaName: typeof row.personaName === 'string' ? row.personaName : '',
787
787
  // Size of the request this row was generated from, in characters.
788
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 : '',
789
791
  reason: row.reason ?? '',
790
792
  createdAt: row.createdAt ?? new Date().toISOString(),
791
793
  decidedAt: row.decidedAt ?? null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qq-affinity",
3
- "version": "1.5.6",
3
+ "version": "1.7.5",
4
4
  "description": "QQ 聊天记录好感度档案:本地建档、三项亲密度评分、智能回复提示、按人开启的智能托管、人格画像、可迁移的本地数据位置、从实时通道自动补齐历史。",
5
5
  "type": "module",
6
6
  "exports": {
@@ -25,12 +25,15 @@ const EXCUSE = '我这边有点事 晚点再聊'
25
25
  // Replies are rewritten into chat shape before they are stored or sent.
26
26
  const STYLED_REPLY = styleReply(REPLY)
27
27
 
28
+ const prompts = []
28
29
  const ctx = {
29
30
  logger: { warn() {}, error() {}, info() {} },
30
31
  get(name) {
31
32
  if (name === 'llm') {
32
33
  return {
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 ?? '')
34
37
  // A brush-off is a different ask: answer it in kind so the assertions
35
38
  // can tell an excuse apart from a normal reply.
36
39
  const text = options?.purpose === 'qq-affinity-excuse' ? EXCUSE : REPLY
@@ -310,6 +313,18 @@ try {
310
313
  check('the inbound size was noted', hugeRow.inboundCount === 1, `${hugeRow.inboundCount}`)
311
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))}`)
312
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))
327
+
313
328
  console.log('\n== a group only wakes on a mention ==')
314
329
  const { conversation: group } = store.ensureConversation({ kind: 'group', title: '老同学群', groupUin: '555666' })
315
330
  store.setEnabled(group.id, true)
@@ -120,6 +120,15 @@ check('the prompt names the group', prompts[0].includes('折腾群'), prompts[0]
120
120
  check('the prompt carries the speaker table', prompts[0].includes('说话人分布'), prompts[0].slice(0, 200))
121
121
  check('token usage is recorded', first.usage.inputTokens === 2400, JSON.stringify(first.usage))
122
122
  check('the measured stats ride along', first.stats.activeSpeakers === 4 && first.stats.atMeMessages === 5, JSON.stringify(first.stats).slice(0, 120))
123
+ // The contribution chart draws straight from these fields: it needs a QQ number
124
+ // for the avatar, a name to label it, and the share to size the column.
125
+ const chartRow = first.stats.speakers[0]
126
+ check('speakers carry a uin for the avatar', typeof chartRow.uin === 'string' && /^\d+$/.test(chartRow.uin), chartRow.uin)
127
+ check('speakers carry a name', chartRow.name === '小明', chartRow.name)
128
+ check('speakers carry a message count', chartRow.messages === 9, `${chartRow.messages}`)
129
+ check('speakers carry a share between 0 and 1', chartRow.share > 0 && chartRow.share <= 1, `${chartRow.share}`)
130
+ check('speakers carry an average length', chartRow.avgChars > 0, `${chartRow.avgChars}`)
131
+ check('the list is longest-speaker first', first.stats.speakers.every((speaker, index, list) => index === 0 || list[index - 1].messages >= speaker.messages))
123
132
  check('the verdict is stored on the conversation', store.groupProfile(conversation.id)?.summary === first.summary, 'ok')
124
133
  check('the evidence is fingerprinted', typeof first.basedOn.fingerprint === 'string' && first.basedOn.fingerprint !== '', first.basedOn.fingerprint)
125
134
 
@@ -0,0 +1,58 @@
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
+ // Translation and summarising are allowed on purpose now, however long they are.
40
+ `帮我翻译一下这段好吗:${'这是一段需要翻译的英文文本。'.repeat(40)}`,
41
+ `总结一下这文章:${'内容内容内容内容内容。'.repeat(40)}`,
42
+ '```js\nconsole.log(1)\n```',
43
+ '',
44
+ '在吗',
45
+ ]
46
+ for (const text of allowed) {
47
+ const result = isNonChatRequest(text)
48
+ check(`passes: ${JSON.stringify(text)}`, result.blocked === false, JSON.stringify(result))
49
+ }
50
+
51
+ console.log('\n== the recorded reason reads like a sentence ==')
52
+ check('math', nonChatReason('math').includes('数学题'), nonChatReason('math'))
53
+ check('code', nonChatReason('code').includes('代码'), nonChatReason('code'))
54
+ check('homework', nonChatReason('homework').includes('作业'), nonChatReason('homework'))
55
+ check('an unknown kind still reads fine', nonChatReason('mystery').includes('非日常'), nonChatReason('mystery'))
56
+
57
+ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
58
+ process.exit(failures === 0 ? 0 : 1)