dsh-qq-affinity 0.0.0-stage → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -2
- package/client.js +3550 -0
- package/cordis.patch.yml +6 -0
- package/docs/DETAIL.md +332 -0
- package/icon.svg +12 -0
- package/index.js +128 -0
- package/lib/analyze.js +777 -0
- package/lib/api.js +984 -0
- package/lib/backfill.js +146 -0
- package/lib/bridge-server.js +78 -0
- package/lib/care.js +240 -0
- package/lib/features.js +200 -0
- package/lib/home.js +168 -0
- package/lib/inbound.js +120 -0
- package/lib/llm.js +137 -0
- package/lib/media.js +161 -0
- package/lib/onebot.js +207 -0
- package/lib/parse.js +184 -0
- package/lib/recover.js +46 -0
- package/lib/store.js +705 -0
- package/lib/util.js +186 -0
- package/lib/vision.js +108 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +38 -4
- package/scripts/api-e2e.mjs +538 -0
- package/scripts/backfill-e2e.mjs +142 -0
- package/scripts/backfill-live.mjs +60 -0
- package/scripts/bridge-e2e.mjs +137 -0
- package/scripts/care-e2e.mjs +217 -0
- package/scripts/check-hook-order.mjs +83 -0
- package/scripts/make-napcat-config.mjs +87 -0
- package/scripts/media-e2e.mjs +103 -0
- package/scripts/recover-e2e.mjs +75 -0
- package/scripts/selftest.mjs +159 -0
- package/scripts/strip-bom.mjs +27 -0
package/lib/backfill.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Automatic history backfill through the bridge.
|
|
3
|
+
*
|
|
4
|
+
* Live messages already arrive on their own once the bridge is connected; this
|
|
5
|
+
* fills in what happened before that. The history action is not part of OneBot
|
|
6
|
+
* v11 proper — NapCat and LLOneBot expose it under two different names — so it
|
|
7
|
+
* is tried by name and the first one that answers wins. A bridge without any of
|
|
8
|
+
* them reports that plainly instead of pretending the archive is complete.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { callApi } from './onebot.js'
|
|
12
|
+
import { extractMedia } from './media.js'
|
|
13
|
+
|
|
14
|
+
/** History actions to try, in order, per conversation kind. */
|
|
15
|
+
const ACTIONS = {
|
|
16
|
+
c2c: ['get_friend_msg_history', 'get_history_msg'],
|
|
17
|
+
group: ['get_group_msg_history', 'get_history_msg'],
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Most messages one backfill request asks for. Bridges usually cap this too. */
|
|
21
|
+
export const MAX_BACKFILL = 1000
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* How many recent messages are pulled automatically when a conversation is
|
|
25
|
+
* added or switched on. Small enough to be quick, large enough to read.
|
|
26
|
+
*/
|
|
27
|
+
export const AUTO_BACKFILL_COUNT = 200
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Normalize one history item into a stored-message candidate.
|
|
31
|
+
* @param {any} item
|
|
32
|
+
* @returns {{ ts: number, senderName: string, senderUin: string, text: string,
|
|
33
|
+
* images?: Array<{ url: string, kind: 'image' | 'sticker', summary: string }> } | undefined}
|
|
34
|
+
*/
|
|
35
|
+
export function historyRow(item) {
|
|
36
|
+
if (item === null || typeof item !== 'object') return undefined
|
|
37
|
+
const raw = typeof item.raw_message === 'string' ? item.raw_message : ''
|
|
38
|
+
const segments = Array.isArray(item.message) ? item.message : undefined
|
|
39
|
+
const media = extractMedia(raw, segments)
|
|
40
|
+
const text = media.text
|
|
41
|
+
if (text === '') return undefined
|
|
42
|
+
const seconds = Number(item.time)
|
|
43
|
+
const ts = Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 0
|
|
44
|
+
if (ts <= 0) return undefined
|
|
45
|
+
const sender = item.sender !== null && typeof item.sender === 'object' ? item.sender : {}
|
|
46
|
+
const senderUin = String(sender.user_id ?? item.user_id ?? '').replace(/\D/g, '').slice(0, 12)
|
|
47
|
+
if (senderUin === '') return undefined
|
|
48
|
+
const senderName = String(sender.card ?? '').trim() || String(sender.nickname ?? '').trim() || senderUin
|
|
49
|
+
const row = { ts, senderName, senderUin, text }
|
|
50
|
+
if (media.images.length > 0) row.images = media.images.slice(0, 4)
|
|
51
|
+
return row
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Pull the message array out of whichever envelope the bridge used. */
|
|
55
|
+
function messagesOf(data) {
|
|
56
|
+
if (Array.isArray(data)) return data
|
|
57
|
+
if (data !== null && typeof data === 'object') {
|
|
58
|
+
if (Array.isArray(data.messages)) return data.messages
|
|
59
|
+
if (Array.isArray(data.message)) return data.message
|
|
60
|
+
if (Array.isArray(data.list)) return data.list
|
|
61
|
+
}
|
|
62
|
+
return []
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Ask the bridge for recent history of one conversation.
|
|
67
|
+
* @param {object} options
|
|
68
|
+
* @param {{ apiBase: string, accessToken: string }} options.bridge
|
|
69
|
+
* @param {{ id: string, kind: 'c2c' | 'group', peerUin: string, groupUin: string }} options.conversation
|
|
70
|
+
* @param {number} [options.count]
|
|
71
|
+
* @param {Function} [options.callAction] - injectable for tests.
|
|
72
|
+
* @returns {Promise<{ rows: Array<object>, action: string, fetched: number }>}
|
|
73
|
+
*/
|
|
74
|
+
export async function fetchHistory({ bridge, conversation, count = MAX_BACKFILL, callAction = callApi }) {
|
|
75
|
+
const limit = Math.max(1, Math.min(MAX_BACKFILL, Math.round(Number(count) || MAX_BACKFILL)))
|
|
76
|
+
const isGroup = conversation.kind === 'group'
|
|
77
|
+
const target = isGroup
|
|
78
|
+
? { group_id: Number(conversation.groupUin) }
|
|
79
|
+
: { user_id: Number(conversation.peerUin) }
|
|
80
|
+
// `Number('')` is 0, which would ask the bridge about QQ number 0.
|
|
81
|
+
if (isGroup && (conversation.groupUin === '' || !Number.isFinite(target.group_id) || target.group_id <= 0)) {
|
|
82
|
+
throw new Error('这个群聊没有群号,拉不了历史。')
|
|
83
|
+
}
|
|
84
|
+
if (!isGroup && (conversation.peerUin === '' || !Number.isFinite(target.user_id) || target.user_id <= 0)) {
|
|
85
|
+
throw new Error('这个私聊还没有对方的 QQ 号,拉不了历史。')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const failures = []
|
|
89
|
+
for (const action of ACTIONS[isGroup ? 'group' : 'c2c']) {
|
|
90
|
+
try {
|
|
91
|
+
// Both shapes are sent: bridges ignore parameters they do not know, and
|
|
92
|
+
// the two extension families disagree about the name of the paging field.
|
|
93
|
+
const data = await callAction(bridge, action, {
|
|
94
|
+
...target,
|
|
95
|
+
count: limit,
|
|
96
|
+
message_seq: 0,
|
|
97
|
+
message_type: isGroup ? 'group' : 'private',
|
|
98
|
+
})
|
|
99
|
+
const items = messagesOf(data)
|
|
100
|
+
const rows = items.map(historyRow).filter(row => row !== undefined)
|
|
101
|
+
return { rows, action, fetched: items.length }
|
|
102
|
+
} catch (error) {
|
|
103
|
+
failures.push(`${action}: ${error instanceof Error ? error.message : String(error)}`)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
throw new Error(`这个桥不支持拉取历史(${failures.join(';')})。改用导出 .txt 导入。`)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Fetch and store history for one conversation.
|
|
111
|
+
* @param {object} options
|
|
112
|
+
* @param {import('./store.js').Store} options.store
|
|
113
|
+
* @param {object} options.bridge
|
|
114
|
+
* @param {object} options.conversation
|
|
115
|
+
* @param {number} [options.count]
|
|
116
|
+
* @param {Function} [options.callAction]
|
|
117
|
+
* @returns {Promise<{ conversationId: string, fetched: number, added: number, duplicates: number, action: string, error?: string }>}
|
|
118
|
+
*/
|
|
119
|
+
export async function backfillConversation({ store, bridge, conversation, count, callAction }) {
|
|
120
|
+
const base = { conversationId: conversation.id, fetched: 0, added: 0, duplicates: 0, action: '' }
|
|
121
|
+
if (conversation.enabled !== true) {
|
|
122
|
+
return { ...base, error: '这个对话没有开启,插件不会去拉它的历史。' }
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const { rows, action, fetched } = await fetchHistory({ bridge, conversation, count, callAction })
|
|
126
|
+
if (rows.length === 0) return { ...base, action, fetched, error: '桥返回了历史,但里面没有可用的文本消息。' }
|
|
127
|
+
const result = store.appendMessages(conversation.id, rows)
|
|
128
|
+
return { ...base, action, fetched, added: result.added, duplicates: result.duplicates }
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return { ...base, error: error instanceof Error ? error.message : String(error) }
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Backfill every enabled conversation, oldest conversation first so a failure
|
|
136
|
+
* in one does not stop the rest.
|
|
137
|
+
* @returns {Promise<Array<object>>} one report per conversation.
|
|
138
|
+
*/
|
|
139
|
+
export async function backfillAll({ store, bridge, count, callAction }) {
|
|
140
|
+
const reports = []
|
|
141
|
+
for (const conversation of store.state.conversations) {
|
|
142
|
+
if (conversation.enabled !== true) continue
|
|
143
|
+
reports.push(await backfillConversation({ store, bridge, conversation, count, callAction }))
|
|
144
|
+
}
|
|
145
|
+
return reports
|
|
146
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A fixed-port loopback listener for the bridge's reports.
|
|
3
|
+
*
|
|
4
|
+
* The Harness GUI port changes on every launch, so a report URL pointing at it
|
|
5
|
+
* would have to be re-copied into the bridge after each restart. This server
|
|
6
|
+
* owns a stable port instead: `http://127.0.0.1:<port>/qq-affinity/onebot`.
|
|
7
|
+
* When the port cannot be bound (another instance already holds it, or policy
|
|
8
|
+
* blocks listening) the plugin keeps working through the Harness route and says
|
|
9
|
+
* so in the panel, instead of failing silently.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import http from 'node:http'
|
|
13
|
+
|
|
14
|
+
/** The port the bridge is told to report to, unless overridden. */
|
|
15
|
+
export const DEFAULT_BRIDGE_PORT = 17890
|
|
16
|
+
|
|
17
|
+
/** The port this process should try to bind. */
|
|
18
|
+
export function bridgePort() {
|
|
19
|
+
const override = process.env.DSH_QQ_AFFINITY_BRIDGE_PORT
|
|
20
|
+
if (typeof override === 'string' && override.trim() !== '') {
|
|
21
|
+
const value = Number(override.trim())
|
|
22
|
+
if (Number.isInteger(value) && value >= 0 && value <= 65535) return value
|
|
23
|
+
}
|
|
24
|
+
return DEFAULT_BRIDGE_PORT
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The address shown to the user and configured in the bridge. */
|
|
28
|
+
export function bridgeUrl(port) {
|
|
29
|
+
return `http://127.0.0.1:${port}/qq-affinity/onebot`
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Start the listener.
|
|
34
|
+
* @param {{ handler: (req: any, res: any) => Promise<void>, port?: number }} options
|
|
35
|
+
* @returns {Promise<{ listening: boolean, port: number, url: string, error?: string, close: () => Promise<void> }>}
|
|
36
|
+
*/
|
|
37
|
+
export function startBridgeServer({ handler, port = bridgePort() }) {
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
const server = http.createServer((req, res) => {
|
|
40
|
+
// Only a loopback listener is useful here; refuse anything else outright.
|
|
41
|
+
if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(String(req.socket?.remoteAddress ?? ''))) {
|
|
42
|
+
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
|
|
43
|
+
res.end('loopback only')
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
handler(req, res).catch(() => {
|
|
47
|
+
try {
|
|
48
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
|
|
49
|
+
res.end('handler failed')
|
|
50
|
+
} catch {
|
|
51
|
+
// The socket is already gone.
|
|
52
|
+
}
|
|
53
|
+
})
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
const finish = (result) => resolve({
|
|
57
|
+
...result,
|
|
58
|
+
close: () => new Promise((done) => {
|
|
59
|
+
server.close(() => done())
|
|
60
|
+
// A keep-alive socket would otherwise hold the close open until timeout.
|
|
61
|
+
server.closeAllConnections?.()
|
|
62
|
+
}),
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
server.once('error', (error) => {
|
|
66
|
+
const reason = error !== null && typeof error === 'object' && typeof error.code === 'string'
|
|
67
|
+
? `${error.code}${error.code === 'EADDRINUSE' ? '(端口被占用)' : ''}`
|
|
68
|
+
: String(error)
|
|
69
|
+
finish({ listening: false, port, url: bridgeUrl(port), error: reason })
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
server.listen(port, '127.0.0.1', () => {
|
|
73
|
+
const address = server.address()
|
|
74
|
+
const bound = address !== null && typeof address === 'object' ? address.port : port
|
|
75
|
+
finish({ listening: true, port: bound, url: bridgeUrl(bound) })
|
|
76
|
+
})
|
|
77
|
+
})
|
|
78
|
+
}
|
package/lib/care.js
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The automatic reply engine ("智能托管").
|
|
3
|
+
*
|
|
4
|
+
* It runs only for people the user switched on individually, and only while the
|
|
5
|
+
* global switch is on. Every attempt — sent, drafted, skipped, failed — lands in
|
|
6
|
+
* one outbox file, so "why didn't it answer?" always has a recorded answer.
|
|
7
|
+
*
|
|
8
|
+
* Guard rails, in the order they are checked:
|
|
9
|
+
* monitored conversation → global switch → per-person switch → content filter
|
|
10
|
+
* → quiet hours → hourly cap → generation → send.
|
|
11
|
+
*
|
|
12
|
+
* There is deliberately no minimum gap between two replies: the hourly cap is
|
|
13
|
+
* the rate limit. Messages are serialized per person, so a burst is answered
|
|
14
|
+
* one message at a time, never in parallel.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { plainText, send as sendThroughBridge } from './onebot.js'
|
|
18
|
+
import { inQuietHours, isAiAuthored, uid } from './util.js'
|
|
19
|
+
import { writeAutoReply } from './analyze.js'
|
|
20
|
+
|
|
21
|
+
const HOUR = 60 * 60 * 1000
|
|
22
|
+
|
|
23
|
+
/** Messages that carry no words worth answering. */
|
|
24
|
+
const UNANSWERABLE = /^((\[(图片|表情|语音|视频|文件|红包|转账|卡片|戳一戳|合并转发|at)\])|\s|。|\.|,|,)+$/
|
|
25
|
+
|
|
26
|
+
/** Local minutes since midnight. */
|
|
27
|
+
function nowMinutes(date = new Date()) {
|
|
28
|
+
return date.getHours() * 60 + date.getMinutes()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Build the engine for one plugin instance.
|
|
33
|
+
* @param {object} options
|
|
34
|
+
* @param {object} options.ctx - Cordis context, for the model.
|
|
35
|
+
* @param {import('./store.js').Store} options.store
|
|
36
|
+
* @param {Function} [options.deliver] - send implementation, replaceable for tests.
|
|
37
|
+
*/
|
|
38
|
+
export function createCareEngine({ ctx, store, deliver: deliverOverride }) {
|
|
39
|
+
/** Per-person serialization: two fast messages produce one answer, not two. */
|
|
40
|
+
const chains = new Map()
|
|
41
|
+
/** uin -> timestamps of replies actually sent, for the hourly cap. */
|
|
42
|
+
const sent = new Map()
|
|
43
|
+
|
|
44
|
+
const sendOut = deliverOverride ?? ((settings, target, text) => sendThroughBridge(settings, target, text))
|
|
45
|
+
|
|
46
|
+
/** Run one task after the previous task for the same person settled. */
|
|
47
|
+
function serialize(uin, task) {
|
|
48
|
+
const previous = chains.get(uin) ?? Promise.resolve()
|
|
49
|
+
const next = previous.then(task, task)
|
|
50
|
+
chains.set(uin, next.then(() => undefined, () => undefined))
|
|
51
|
+
return next
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Recorded timestamps for one person inside the last hour. */
|
|
55
|
+
function recentCount(uin) {
|
|
56
|
+
const cutoff = Date.now() - HOUR
|
|
57
|
+
const kept = (sent.get(uin) ?? []).filter(at => at >= cutoff)
|
|
58
|
+
sent.set(uin, kept)
|
|
59
|
+
return kept.length
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Record one reply attempt and return its outbox row. */
|
|
63
|
+
function note(fields) {
|
|
64
|
+
return store.recordOutbox({ id: uid('o'), ...fields })
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Actually send one reply and fold it into the conversation.
|
|
69
|
+
* @returns {Promise<object>} the updated outbox row.
|
|
70
|
+
*/
|
|
71
|
+
async function dispatch(row, conversation, targetUin) {
|
|
72
|
+
const settings = store.state.settings
|
|
73
|
+
const bridge = settings.onebot
|
|
74
|
+
const target = {
|
|
75
|
+
kind: conversation.kind === 'group' ? 'group' : 'c2c',
|
|
76
|
+
peerUin: targetUin,
|
|
77
|
+
groupUin: conversation.groupUin,
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const result = await sendOut(bridge, target, row.text)
|
|
81
|
+
store.appendMessages(conversation.id, [{
|
|
82
|
+
ts: Date.now(),
|
|
83
|
+
senderName: settings.selfName === '' ? '我' : settings.selfName,
|
|
84
|
+
senderUin: settings.selfUin,
|
|
85
|
+
text: row.text,
|
|
86
|
+
aiAuto: true,
|
|
87
|
+
}])
|
|
88
|
+
sent.set(targetUin, [...(sent.get(targetUin) ?? []), Date.now()])
|
|
89
|
+
store.markStale(conversation)
|
|
90
|
+
return store.updateOutbox(row.id, {
|
|
91
|
+
status: 'sent',
|
|
92
|
+
sentAt: new Date().toISOString(),
|
|
93
|
+
decidedAt: row.decidedAt ?? new Date().toISOString(),
|
|
94
|
+
reason: '',
|
|
95
|
+
messageId: result.messageId,
|
|
96
|
+
})
|
|
97
|
+
} catch (error) {
|
|
98
|
+
return store.updateOutbox(row.id, {
|
|
99
|
+
status: 'failed',
|
|
100
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Decide what to do about one inbound message.
|
|
107
|
+
* @param {object} event - a normalized event from `lib/onebot.js`.
|
|
108
|
+
* @returns {Promise<{ action: string, reason?: string, outboxId?: string }>}
|
|
109
|
+
*/
|
|
110
|
+
async function handleEvent(event) {
|
|
111
|
+
if (event === undefined) return { action: 'ignored', reason: 'not-a-message' }
|
|
112
|
+
const settings = store.state.settings
|
|
113
|
+
if (settings.onebot.enabled !== true) return { action: 'ignored', reason: 'channel-off' }
|
|
114
|
+
|
|
115
|
+
const conversation = store.conversation(event.conversationId)
|
|
116
|
+
if (conversation === undefined || conversation.enabled !== true) {
|
|
117
|
+
// Not monitored: nothing is stored, exactly like a conversation the user
|
|
118
|
+
// never turned on.
|
|
119
|
+
return { action: 'ignored', reason: 'not-monitored' }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Reading happens here and only here, after the consent checks above.
|
|
123
|
+
store.appendMessages(event.conversationId, [{
|
|
124
|
+
ts: event.ts,
|
|
125
|
+
senderName: event.senderName,
|
|
126
|
+
// A self message is authored by me; in that case `peerUin` names the other
|
|
127
|
+
// side of the conversation, which is what selected this conversation.
|
|
128
|
+
senderUin: event.fromSelf === true ? store.state.settings.selfUin : event.peerUin,
|
|
129
|
+
text: event.text,
|
|
130
|
+
}])
|
|
131
|
+
|
|
132
|
+
// My own message: archived, never answered. Answering it would be the
|
|
133
|
+
// plugin talking to itself.
|
|
134
|
+
if (event.fromSelf === true) return { action: 'recorded', reason: 'self' }
|
|
135
|
+
|
|
136
|
+
const skip = (reason, extra = {}) => {
|
|
137
|
+
const row = note({
|
|
138
|
+
conversationId: conversation.id,
|
|
139
|
+
uin: event.peerUin,
|
|
140
|
+
inboundText: event.text,
|
|
141
|
+
inboundTs: event.ts,
|
|
142
|
+
status: 'skipped',
|
|
143
|
+
reason,
|
|
144
|
+
...extra,
|
|
145
|
+
})
|
|
146
|
+
return { action: 'skipped', reason, outboxId: row.id }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (settings.selfUin === '') return skip('还没有填写我的 QQ 号,无法区分消息方向。')
|
|
150
|
+
if (settings.careEnabled !== true) return { action: 'recorded', reason: 'care-off' }
|
|
151
|
+
|
|
152
|
+
const care = store.careFor(event.peerUin)
|
|
153
|
+
if (care === undefined || care.enabled !== true) return { action: 'recorded', reason: 'person-off' }
|
|
154
|
+
|
|
155
|
+
if (conversation.kind === 'group' && care.groupOnlyWhenMentioned && event.atSelf !== true) {
|
|
156
|
+
// Answering every line in a group would be noise; only a mention wakes it.
|
|
157
|
+
return { action: 'ignored', reason: 'not-mentioned' }
|
|
158
|
+
}
|
|
159
|
+
if (UNANSWERABLE.test(plainText(event.text))) {
|
|
160
|
+
return skip('对方只发了图片或表情,没有可以接的话。')
|
|
161
|
+
}
|
|
162
|
+
if (inQuietHours(nowMinutes(), care.quietFrom, care.quietTo)) {
|
|
163
|
+
return skip(`落在免打扰时段(${care.quietFrom}–${care.quietTo})。`)
|
|
164
|
+
}
|
|
165
|
+
// No minimum gap: the hourly cap is the only rate limit.
|
|
166
|
+
if (recentCount(event.peerUin) >= care.hourlyCap) {
|
|
167
|
+
return skip(`这一小时已经自动回复 ${care.hourlyCap} 次,先停下。`)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
let text
|
|
171
|
+
try {
|
|
172
|
+
text = await writeAutoReply(ctx, store, {
|
|
173
|
+
conversationId: conversation.id,
|
|
174
|
+
uin: event.peerUin,
|
|
175
|
+
maxChars: care.maxReplyChars,
|
|
176
|
+
})
|
|
177
|
+
} catch (error) {
|
|
178
|
+
return skip(`生成回复失败:${error instanceof Error ? error.message : String(error)}`)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const row = note({
|
|
182
|
+
conversationId: conversation.id,
|
|
183
|
+
uin: event.peerUin,
|
|
184
|
+
inboundText: event.text,
|
|
185
|
+
inboundTs: event.ts,
|
|
186
|
+
text,
|
|
187
|
+
status: care.mode === 'auto' ? 'sending' : 'draft',
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
if (care.mode !== 'auto') return { action: 'drafted', outboxId: row.id }
|
|
191
|
+
const updated = await dispatch(row, conversation, event.peerUin)
|
|
192
|
+
return { action: updated.status === 'sent' ? 'sent' : 'failed', outboxId: row.id, reason: updated.reason }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Queue one inbound event behind everything already queued for that person. */
|
|
196
|
+
function enqueue(event) {
|
|
197
|
+
const key = event?.peerUin ?? ''
|
|
198
|
+
if (key === '') return Promise.resolve({ action: 'ignored', reason: 'not-a-message' })
|
|
199
|
+
return serialize(key, () => handleEvent(event))
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Send a draft the user approved. Cooldowns do not apply to an explicit action. */
|
|
203
|
+
async function approve(id) {
|
|
204
|
+
const row = store.outbox().find(entry => entry.id === id)
|
|
205
|
+
if (row === undefined) throw new Error('找不到这条草稿。')
|
|
206
|
+
if (row.status !== 'draft') throw new Error('这条草稿已经处理过了。')
|
|
207
|
+
const conversation = store.conversation(row.conversationId)
|
|
208
|
+
if (conversation === undefined) throw new Error('对话已经不存在了。')
|
|
209
|
+
if (conversation.enabled !== true) throw new Error('这个对话已经关闭,先重新开启再发送更安全。')
|
|
210
|
+
const marked = store.updateOutbox(id, { status: 'sending', decidedAt: new Date().toISOString() })
|
|
211
|
+
const updated = await dispatch(marked, conversation, row.uin)
|
|
212
|
+
if (updated.status !== 'sent') throw new Error(updated.reason === '' ? '发送失败。' : updated.reason)
|
|
213
|
+
return updated
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Drop a draft without sending it. */
|
|
217
|
+
function cancel(id) {
|
|
218
|
+
const row = store.outbox().find(entry => entry.id === id)
|
|
219
|
+
if (row === undefined) throw new Error('找不到这条草稿。')
|
|
220
|
+
if (row.status !== 'draft') throw new Error('只有未发送的草稿可以取消。')
|
|
221
|
+
return store.updateOutbox(id, { status: 'cancelled', decidedAt: new Date().toISOString() })
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** How many automatic replies went out in the last hour, per person. */
|
|
225
|
+
function usage() {
|
|
226
|
+
const result = {}
|
|
227
|
+
for (const [uin, times] of sent.entries()) {
|
|
228
|
+
const kept = times.filter(at => at >= Date.now() - HOUR)
|
|
229
|
+
if (kept.length > 0) result[uin] = { lastHour: kept.length, lastAt: Math.max(...kept) }
|
|
230
|
+
}
|
|
231
|
+
return result
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return { handleEvent, enqueue, approve, cancel, usage }
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Count the AI-authored rows of one conversation, for the UI badge. */
|
|
238
|
+
export function aiAuthoredCount(rows) {
|
|
239
|
+
return rows.filter(row => isAiAuthored(row)).length
|
|
240
|
+
}
|
package/lib/features.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic interaction measurements and transcript rendering.
|
|
3
|
+
*
|
|
4
|
+
* The measurements anchor the model's judgement with facts it cannot count
|
|
5
|
+
* reliably, and the two transcript renderings keep AI-ghostwritten messages
|
|
6
|
+
* out of the "how much I like them" input entirely.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { formatTime, isAiAuthored, truncate } from './util.js'
|
|
10
|
+
|
|
11
|
+
const HALF_HOUR = 30 * 60 * 1000
|
|
12
|
+
const SIX_HOURS = 6 * 60 * 60 * 1000
|
|
13
|
+
|
|
14
|
+
const EMOJI = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{FE0F}\u{2764}]/gu
|
|
15
|
+
const STICKER = /\[(表情|图片|动画表情|贴图|视频|语音|文件|红包|转账)\]/g
|
|
16
|
+
|
|
17
|
+
/** Median of a numeric list, or 0. */
|
|
18
|
+
function median(values) {
|
|
19
|
+
if (values.length === 0) return 0
|
|
20
|
+
const sorted = [...values].sort((a, b) => a - b)
|
|
21
|
+
const middle = Math.floor(sorted.length / 2)
|
|
22
|
+
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Mean of a numeric list, rounded, or 0. */
|
|
26
|
+
function mean(values) {
|
|
27
|
+
if (values.length === 0) return 0
|
|
28
|
+
return Math.round(values.reduce((total, value) => total + value, 0) / values.length)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Count decorative and channel markers, which signal rapport rather than content. */
|
|
32
|
+
function decorationCount(text) {
|
|
33
|
+
const emoji = (String(text).match(EMOJI) ?? []).length
|
|
34
|
+
const stickers = (String(text).match(STICKER) ?? []).length
|
|
35
|
+
return emoji + stickers
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Whether the text asks something. */
|
|
39
|
+
function isQuestion(text) {
|
|
40
|
+
return /[??]/.test(text) || /(吗|呢|么|嘛|如何|怎么|什么|为什么|几时|多少)\s*$/.test(String(text).trim())
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Local clock hour of a timestamp. */
|
|
44
|
+
function hourOf(ts) {
|
|
45
|
+
return new Date(ts).getHours()
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Every row that concerns one person, across the conversations allowed to
|
|
50
|
+
* contribute, oldest first.
|
|
51
|
+
* @param {import('./store.js').Store} store
|
|
52
|
+
* @param {string} targetUin
|
|
53
|
+
* @returns {Array<object>}
|
|
54
|
+
*/
|
|
55
|
+
export function rowsForPerson(store, targetUin) {
|
|
56
|
+
const enabled = new Set(store.enabledConversationIds())
|
|
57
|
+
const rows = []
|
|
58
|
+
for (const conversation of store.state.conversations) {
|
|
59
|
+
if (!enabled.has(conversation.id)) continue
|
|
60
|
+
const concernsTarget = conversation.peerUin === targetUin
|
|
61
|
+
|| (conversation.participants ?? []).includes(targetUin)
|
|
62
|
+
if (!concernsTarget) continue
|
|
63
|
+
for (const row of store.messages(conversation.id)) {
|
|
64
|
+
if (row.senderUin === targetUin || row.direction === 'out') {
|
|
65
|
+
rows.push({ ...row, conversationId: conversation.id })
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
rows.sort((a, b) => a.ts - b.ts)
|
|
70
|
+
return rows
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Summarize how two people actually interact.
|
|
75
|
+
* @param {Array<object>} rows - rows from {@link rowsForPerson}.
|
|
76
|
+
* @param {string} targetUin
|
|
77
|
+
* @returns {object} plain JSON safe to put in a prompt or a response.
|
|
78
|
+
*/
|
|
79
|
+
export function measure(rows, targetUin) {
|
|
80
|
+
const theirs = targetUin === '' ? [] : rows.filter(row => row.senderUin === targetUin)
|
|
81
|
+
const mine = rows.filter(row => row.direction === 'out')
|
|
82
|
+
const mineAuthentic = mine.filter(row => !isAiAuthored(row))
|
|
83
|
+
|
|
84
|
+
const theirQuestions = theirs.filter(row => isQuestion(row.text)).length
|
|
85
|
+
const myQuestions = mineAuthentic.filter(row => isQuestion(row.text)).length
|
|
86
|
+
const theirDecoration = theirs.reduce((total, row) => total + decorationCount(row.text), 0)
|
|
87
|
+
const myDecoration = mineAuthentic.reduce((total, row) => total + decorationCount(row.text), 0)
|
|
88
|
+
|
|
89
|
+
// Initiative: a message that lands more than half an hour after anything else starts a burst.
|
|
90
|
+
let theirInitiatives = 0
|
|
91
|
+
let myInitiatives = 0
|
|
92
|
+
const myReplies = []
|
|
93
|
+
const theirReplies = []
|
|
94
|
+
for (let index = 0; index < rows.length; index += 1) {
|
|
95
|
+
const row = rows[index]
|
|
96
|
+
const previous = rows[index - 1]
|
|
97
|
+
const gap = previous === undefined ? Number.POSITIVE_INFINITY : row.ts - previous.ts
|
|
98
|
+
const starter = gap > HALF_HOUR
|
|
99
|
+
if (starter && row.senderUin === targetUin) theirInitiatives += 1
|
|
100
|
+
if (starter && row.direction === 'out') myInitiatives += 1
|
|
101
|
+
if (previous === undefined || gap > SIX_HOURS) continue
|
|
102
|
+
if (row.direction === 'out' && previous.senderUin === targetUin) myReplies.push(gap)
|
|
103
|
+
if (row.senderUin === targetUin && previous.direction === 'out') theirReplies.push(gap)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const theirNight = theirs.filter(row => hourOf(row.ts) >= 23 || hourOf(row.ts) < 5).length
|
|
107
|
+
const activeDays = new Set(rows.map(row => new Date(row.ts).toDateString())).size
|
|
108
|
+
const spanDays = rows.length === 0
|
|
109
|
+
? 0
|
|
110
|
+
: Math.max(1, Math.round((rows[rows.length - 1].ts - rows[0].ts) / (24 * 60 * 60 * 1000)))
|
|
111
|
+
const lastContactDays = rows.length === 0
|
|
112
|
+
? null
|
|
113
|
+
: Math.round((Date.now() - rows[rows.length - 1].ts) / (24 * 60 * 60 * 1000))
|
|
114
|
+
|
|
115
|
+
const theirBursts = rows.reduce((total, row, index) => {
|
|
116
|
+
const previous = rows[index - 1]
|
|
117
|
+
return previous !== undefined && previous.senderUin === targetUin && row.senderUin === targetUin ? total + 1 : total
|
|
118
|
+
}, 0)
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
totalMessages: rows.length,
|
|
122
|
+
theirMessages: theirs.length,
|
|
123
|
+
myMessages: mine.length,
|
|
124
|
+
myAuthenticMessages: mineAuthentic.length,
|
|
125
|
+
aiAdoptedMessages: mine.length - mineAuthentic.length,
|
|
126
|
+
theirAvgChars: mean(theirs.map(row => row.text.length)),
|
|
127
|
+
myAvgChars: mean(mineAuthentic.map(row => row.text.length)),
|
|
128
|
+
theirQuestionRatio: theirs.length === 0 ? 0 : Math.round((theirQuestions / theirs.length) * 100) / 100,
|
|
129
|
+
myQuestionRatio: mineAuthentic.length === 0 ? 0 : Math.round((myQuestions / mineAuthentic.length) * 100) / 100,
|
|
130
|
+
theirDecorationPerMessage: theirs.length === 0 ? 0 : Math.round((theirDecoration / theirs.length) * 100) / 100,
|
|
131
|
+
myDecorationPerMessage: mineAuthentic.length === 0 ? 0 : Math.round((myDecoration / mineAuthentic.length) * 100) / 100,
|
|
132
|
+
theirInitiativeRatio: theirs.length === 0 ? 0 : Math.round((theirInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
|
|
133
|
+
myInitiativeRatio: mineAuthentic.length === 0 ? 0 : Math.round((myInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
|
|
134
|
+
theirMedianReplySeconds: Math.round(median(theirReplies) / 1000),
|
|
135
|
+
myMedianReplySeconds: Math.round(median(myReplies.filter((_, index) => index < mineAuthentic.length)) / 1000),
|
|
136
|
+
theirNightRatio: theirs.length === 0 ? 0 : Math.round((theirNight / theirs.length) * 100) / 100,
|
|
137
|
+
theirDoubleTextCount: theirBursts,
|
|
138
|
+
activeDays,
|
|
139
|
+
spanDays,
|
|
140
|
+
lastContactDays,
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Render rows as a compact transcript.
|
|
146
|
+
* @param {Array<object>} rows
|
|
147
|
+
* @param {object} options
|
|
148
|
+
* @param {string} options.selfUin
|
|
149
|
+
* @param {string} options.targetUin
|
|
150
|
+
* @param {string} [options.targetName]
|
|
151
|
+
* @param {boolean} [options.excludeAdopted] - drop adopted messages instead of marking them.
|
|
152
|
+
* @param {boolean} [options.markAdopted] - mark adopted messages so the reader can discount them.
|
|
153
|
+
* @param {number} [options.maxChars]
|
|
154
|
+
* @returns {{ text: string, included: number, omitted: number }}
|
|
155
|
+
*/
|
|
156
|
+
export function renderTranscript(rows, options) {
|
|
157
|
+
const {
|
|
158
|
+
targetUin,
|
|
159
|
+
targetName = '对方',
|
|
160
|
+
excludeAdopted = false,
|
|
161
|
+
markAdopted = true,
|
|
162
|
+
maxChars = 12000,
|
|
163
|
+
} = options
|
|
164
|
+
const kept = []
|
|
165
|
+
let omitted = 0
|
|
166
|
+
// The newest part of a long history carries the most current signal.
|
|
167
|
+
for (let index = rows.length - 1; index >= 0; index -= 1) {
|
|
168
|
+
const row = rows[index]
|
|
169
|
+
if (excludeAdopted && isAiAuthored(row)) continue
|
|
170
|
+
const who = row.senderUin === targetUin ? targetName : '我'
|
|
171
|
+
const marker = isAiAuthored(row) && markAdopted ? '(AI代笔)' : ''
|
|
172
|
+
const body = truncate(String(row.text).replace(/\n+/g, ' / '), 240)
|
|
173
|
+
kept.push(`[${formatTime(row.ts)}] ${who}${marker}:${body}`)
|
|
174
|
+
}
|
|
175
|
+
kept.reverse()
|
|
176
|
+
let text = ''
|
|
177
|
+
for (let index = kept.length - 1; index >= 0; index -= 1) {
|
|
178
|
+
const candidate = `${kept[index]}\n${text}`
|
|
179
|
+
if (candidate.length > maxChars) {
|
|
180
|
+
omitted = index + 1
|
|
181
|
+
break
|
|
182
|
+
}
|
|
183
|
+
text = candidate
|
|
184
|
+
}
|
|
185
|
+
if (omitted > 0) text = `(更早的 ${omitted} 条已省略)\n${text}`
|
|
186
|
+
return { text: text.trim(), included: kept.length - omitted, omitted }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The last inbound message of one conversation, which is what a reply answers.
|
|
191
|
+
* @param {Array<object>} rows
|
|
192
|
+
* @param {string} targetUin
|
|
193
|
+
* @returns {object | undefined}
|
|
194
|
+
*/
|
|
195
|
+
export function lastInbound(rows, targetUin) {
|
|
196
|
+
for (let index = rows.length - 1; index >= 0; index -= 1) {
|
|
197
|
+
if (rows[index].senderUin === targetUin) return rows[index]
|
|
198
|
+
}
|
|
199
|
+
return undefined
|
|
200
|
+
}
|