dsh-qq-affinity 1.5.6 → 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 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.6.0'
24
24
 
25
25
  // ---------------------------------------------------------------- palette
26
26
 
@@ -1219,6 +1219,7 @@ window.__ModuleLoader__.load({
1219
1219
  h('div', { key: 'top', style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } }, [
1220
1220
  h(Chip, { key: 's', color: OUTBOX_COLOR(row.status) }, OUTBOX_LABEL[row.status] ?? row.status),
1221
1221
  row.kind === 'excuse' ? h(Chip, { key: 'k', color: C.warn }, '推辞(到上限)') : null,
1222
+ row.taskRequest === undefined || row.taskRequest === '' ? null : h(Chip, { key: 'tr', color: C.warn }, '非日常请求(已拒绝)'),
1222
1223
  row.personaId === undefined || row.personaId === '' ? null : h(Chip, {
1223
1224
  key: 'p',
1224
1225
  color: row.personaId === 'default' ? C.idle : C.brand,
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,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/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.6.1",
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)
@@ -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)