@cmach_socket/opencode-qq-bot 0.3.4 → 0.6.0
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/NOTICE +69 -0
- package/README.md +370 -44
- package/package.json +21 -2
- package/src/access.ts +79 -0
- package/src/bot-lock.ts +17 -26
- package/src/chat.ts +0 -20
- package/src/commands.ts +267 -0
- package/src/config.ts +602 -48
- package/src/emoji/command.ts +184 -0
- package/src/emoji/faces.ts +136 -0
- package/src/emoji/favorite-index.ts +150 -0
- package/src/emoji/favorites.ts +161 -0
- package/src/emoji/label.ts +318 -0
- package/src/events/notice.ts +139 -0
- package/src/events/store.ts +53 -0
- package/src/home.ts +45 -0
- package/src/index.ts +437 -63
- package/src/instance.ts +30 -17
- package/src/keepalive.ts +222 -0
- package/src/logger.ts +273 -17
- package/src/media-path.ts +186 -0
- package/src/model-view.ts +136 -0
- package/src/naplink/client.ts +14 -17
- package/src/naplink/history.ts +263 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +142 -33
- package/src/outbound.ts +174 -0
- package/src/overrides.ts +312 -0
- package/src/rate-limit.ts +228 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +488 -31
- package/src/session/proactive.ts +21 -0
- package/src/session/prompt.ts +4 -1
- package/src/session/soul.ts +46 -0
- package/src/tools/ask-guard.ts +5 -5
- package/src/tools/policy-guard.ts +45 -0
- package/src/tools/policy.ts +205 -0
- package/src/tools/qq.ts +353 -41
- package/src/tools/send-guard.ts +73 -0
- package/src/trace.ts +209 -0
- package/src/tui-commands.ts +70 -0
- package/src/version.ts +12 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { lookup } from "node:dns/promises"
|
|
2
|
+
import { realpath, stat } from "node:fs/promises"
|
|
3
|
+
import { homedir } from "node:os"
|
|
4
|
+
import { isAbsolute, join, resolve, sep } from "node:path"
|
|
5
|
+
import ipaddr from "ipaddr.js"
|
|
6
|
+
import { ALLOWED_PORTS } from "./safe-fetch"
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 媒体目录:`$XDG_STATE_HOME/opencode-qq-bot/media`。
|
|
10
|
+
*
|
|
11
|
+
* 未设置 `XDG_STATE_HOME` 时用 `~/.local/state/opencode-qq-bot/media`。
|
|
12
|
+
*/
|
|
13
|
+
export function defaultMediaDir(): string {
|
|
14
|
+
const state = process.env.XDG_STATE_HOME?.trim()
|
|
15
|
+
const base = state && isAbsolute(state) ? state : join(homedir(), ".local", "state")
|
|
16
|
+
return join(base, "opencode-qq-bot", "media")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 出站媒体的路径策略。 */
|
|
20
|
+
export interface MediaPolicy {
|
|
21
|
+
/** 机器人工作目录:相对路径按它解析。 */
|
|
22
|
+
workspace: string
|
|
23
|
+
/** 允许发送媒体的目录(绝对路径或 `~/` 开头)。 */
|
|
24
|
+
allowedDirs: string[]
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 媒体被策略拒绝时抛出,错误说明直接回给模型。 */
|
|
28
|
+
export class MediaPolicyError extends Error {}
|
|
29
|
+
|
|
30
|
+
/** 出站媒体的处理计划。 */
|
|
31
|
+
export type MediaPlan = { kind: "local"; path: string } | { kind: "remote"; url: URL }
|
|
32
|
+
|
|
33
|
+
/** 展开 `~` 并去掉首尾空白。 */
|
|
34
|
+
function expand(value: string): string {
|
|
35
|
+
const trimmed = value.trim()
|
|
36
|
+
if (trimmed === "~") return homedir()
|
|
37
|
+
if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2))
|
|
38
|
+
return trimmed
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 判断路径是否位于目录之内。
|
|
43
|
+
*
|
|
44
|
+
* 按目录边界比较:`/data/qq-bot` 不会命中 `/data/qq-bot-secret`。
|
|
45
|
+
*/
|
|
46
|
+
function contains(dir: string, target: string): boolean {
|
|
47
|
+
if (dir === target) return true
|
|
48
|
+
const prefix = dir.endsWith(sep) ? dir : dir + sep
|
|
49
|
+
return target.startsWith(prefix)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 判断一个 IP 是不是公网地址。
|
|
54
|
+
*
|
|
55
|
+
* 规则与 `request-filtering-agent` 一致:只有 `unicast` 段算公网,
|
|
56
|
+
* 回环、私网、CGNAT、链路本地、组播、IPv4-mapped、6to4 等一律不算。
|
|
57
|
+
*/
|
|
58
|
+
function isPublicAddress(address: string): boolean {
|
|
59
|
+
try {
|
|
60
|
+
return ipaddr.parse(address).range() === "unicast"
|
|
61
|
+
} catch {
|
|
62
|
+
return false
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 出站媒体的路径与地址把关。
|
|
68
|
+
*
|
|
69
|
+
* 本地路径只允许机器人工作目录、媒体目录和配置里显式放开的目录;
|
|
70
|
+
* 远端地址要求解析出的地址都是公网,再交给 NapCat 自己去拉。
|
|
71
|
+
*/
|
|
72
|
+
export class OutboundMedia {
|
|
73
|
+
constructor(private readonly policy: MediaPolicy) {}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 检查媒体引用。
|
|
77
|
+
*
|
|
78
|
+
* 本地路径在这里就判定白名单,判定不过直接抛错,不占用发送额度。
|
|
79
|
+
*/
|
|
80
|
+
async check(file: string): Promise<MediaPlan> {
|
|
81
|
+
const value = expand(file)
|
|
82
|
+
if (value.startsWith("http://") || value.startsWith("https://")) {
|
|
83
|
+
let url: URL
|
|
84
|
+
try {
|
|
85
|
+
url = new URL(value)
|
|
86
|
+
} catch {
|
|
87
|
+
throw new MediaPolicyError(`媒体地址无效:${file}`)
|
|
88
|
+
}
|
|
89
|
+
await this.checkRemote(url)
|
|
90
|
+
return { kind: "remote", url }
|
|
91
|
+
}
|
|
92
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(value)) {
|
|
93
|
+
throw new MediaPolicyError(`不支持的媒体地址:${file}`)
|
|
94
|
+
}
|
|
95
|
+
return { kind: "local", path: await this.resolveLocal(value) }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 按计划拿到可以交给 NapCat 的文件字段。 */
|
|
99
|
+
materialize(plan: MediaPlan): string {
|
|
100
|
+
return plan.kind === "local" ? plan.path : plan.url.href
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 判定远端地址能不能用。
|
|
105
|
+
*
|
|
106
|
+
* 只放行常见网页端口;域名解析出来的每一个地址都必须是公网地址,
|
|
107
|
+
* 否则拒绝——不给 NapCat 留去拉内网地址的机会。
|
|
108
|
+
*
|
|
109
|
+
* 注意:实际下载由 NapCat 完成,它会自己再解析一次 DNS,
|
|
110
|
+
* 所以这里挡的是「地址本身指向内网」,挡不住 DNS 重绑定。
|
|
111
|
+
*/
|
|
112
|
+
private async checkRemote(url: URL): Promise<void> {
|
|
113
|
+
const port = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80
|
|
114
|
+
if (!ALLOWED_PORTS.includes(port)) {
|
|
115
|
+
throw new MediaPolicyError(`媒体地址的端口不在白名单内:${port}`)
|
|
116
|
+
}
|
|
117
|
+
const host = url.hostname.replace(/^\[|\]$/g, "")
|
|
118
|
+
const addresses = await resolveAddresses(host)
|
|
119
|
+
if (addresses.length === 0) {
|
|
120
|
+
throw new MediaPolicyError(`媒体地址解析不出 IP:${url.hostname}`)
|
|
121
|
+
}
|
|
122
|
+
for (const address of addresses) {
|
|
123
|
+
if (!isPublicAddress(address)) {
|
|
124
|
+
throw new MediaPolicyError(`媒体地址指向内网,不允许发送:${url.hostname}(${address})`)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 判定本地路径是否在允许的目录内。
|
|
131
|
+
*
|
|
132
|
+
* 展开 `~`、相对路径按工作目录解析,再取真实路径判定:
|
|
133
|
+
* 目录内的软链接指向目录外时同样拒绝,避免软链接绕过。
|
|
134
|
+
*/
|
|
135
|
+
private async resolveLocal(file: string): Promise<string> {
|
|
136
|
+
const expanded = expand(file)
|
|
137
|
+
const lexical = isAbsolute(expanded) ? expanded : resolve(this.policy.workspace, expanded)
|
|
138
|
+
let real: string
|
|
139
|
+
try {
|
|
140
|
+
real = await realpath(lexical)
|
|
141
|
+
} catch {
|
|
142
|
+
throw new MediaPolicyError(`媒体文件不存在或无法读取:${file}`)
|
|
143
|
+
}
|
|
144
|
+
const info = await stat(real)
|
|
145
|
+
if (!info.isFile()) {
|
|
146
|
+
throw new MediaPolicyError(`媒体路径不是普通文件:${file}`)
|
|
147
|
+
}
|
|
148
|
+
const dirs = await this.allowedDirs()
|
|
149
|
+
const inLexical = dirs.some((dir) => contains(dir.lexical, lexical))
|
|
150
|
+
const inReal = dirs.some((dir) => contains(dir.real, real) || contains(dir.lexical, real))
|
|
151
|
+
if (!inLexical || !inReal) {
|
|
152
|
+
const allowed = dirs.map((dir) => dir.lexical).join("、")
|
|
153
|
+
throw new MediaPolicyError(`媒体文件不在允许的目录内:${file}(允许:${allowed || "无"})`)
|
|
154
|
+
}
|
|
155
|
+
return real
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 允许的目录:词法路径与真实路径各一份,软链接目录也能命中。 */
|
|
159
|
+
private async allowedDirs(): Promise<{ lexical: string; real: string }[]> {
|
|
160
|
+
const dirs: { lexical: string; real: string }[] = []
|
|
161
|
+
for (const dir of this.policy.allowedDirs) {
|
|
162
|
+
const expanded = expand(dir)
|
|
163
|
+
if (!expanded) continue
|
|
164
|
+
const lexical = isAbsolute(expanded) ? expanded : resolve(this.policy.workspace, expanded)
|
|
165
|
+
let real = lexical
|
|
166
|
+
try {
|
|
167
|
+
real = await realpath(lexical)
|
|
168
|
+
} catch {
|
|
169
|
+
// 目录还不存在时先按词法路径处理。
|
|
170
|
+
}
|
|
171
|
+
dirs.push({ lexical, real })
|
|
172
|
+
}
|
|
173
|
+
return dirs
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 解析主机名,返回全部地址;本身就是 IP 时直接返回。 */
|
|
178
|
+
async function resolveAddresses(host: string): Promise<string[]> {
|
|
179
|
+
if (ipaddr.isValid(host)) return [host]
|
|
180
|
+
try {
|
|
181
|
+
const found = await lookup(host, { all: true, verbatim: true })
|
|
182
|
+
return found.map((entry) => entry.address)
|
|
183
|
+
} catch {
|
|
184
|
+
return []
|
|
185
|
+
}
|
|
186
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模型视图:把群友可控的 QQ 文本整理成能直接进提示词的形式。
|
|
3
|
+
*
|
|
4
|
+
* 群里来的文本完全可控,原样拼进提示词就能伪造段落或跨行结构;
|
|
5
|
+
* 这里统一做结构净化,并给每条消息标上绝对时间。
|
|
6
|
+
*
|
|
7
|
+
* 净化分两层:`sanitizeUntrustedText` 负责单段文本里的换行、零宽字符与全角括号,
|
|
8
|
+
* `neutralizeStructureTags` 负责拼好之后整条消息里的结构标签——
|
|
9
|
+
* 群友把 `<quote>` 拆成两段发过来,逐段净化匹配不到,只有整体净化才拦得住。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** 提示词里的结构标签;群友文本里出现同样字样时换成全角,避免伪造。 */
|
|
13
|
+
const STRUCTURE_TAG = /<\/?(quote|forward|history)>/gi
|
|
14
|
+
|
|
15
|
+
/** 换行类字符:换行、段分隔符、下一行、垂直制表、换页。 */
|
|
16
|
+
const NEWLINE_LIKE = /[\r\n\u2028\u2029\u0085\u000B\u000C]+/g
|
|
17
|
+
/** 零宽字符:可以用来把标签拆成看起来正常、匹配不上的形式。 */
|
|
18
|
+
const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
|
|
19
|
+
/** 控制字符:显示名里出现会破坏结构。 */
|
|
20
|
+
const CONTROL = /[\u0000-\u001F\u007F]+/g
|
|
21
|
+
/** 私用区字符:插件用它给结构标签占位,群友文本里的必须清掉,否则能伪造占位符。 */
|
|
22
|
+
const PRIVATE_USE = /[\uE000-\uF8FF]/g
|
|
23
|
+
/** 私用区占位符的起点。 */
|
|
24
|
+
const PLACEHOLDER_START = 0xe000
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 把结构标签换成全角。
|
|
28
|
+
*
|
|
29
|
+
* 只对一段文本调用是不够的:`<` 与 `quote>` 分处两段时匹配不到,拼起来仍是一个标签。
|
|
30
|
+
* 这里对拼好的整段文本调用,跨段拼接伪造也挡得住。
|
|
31
|
+
*/
|
|
32
|
+
export function neutralizeStructureTags(value: string): string {
|
|
33
|
+
return String(value ?? "").replace(STRUCTURE_TAG, (tag) =>
|
|
34
|
+
tag.replace(/</g, "<").replace(/>/g, ">"),
|
|
35
|
+
)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 净化群友可控文本。
|
|
40
|
+
*
|
|
41
|
+
* 换行类字符压成空格、零宽字符直接去掉,全角方括号换成半角,
|
|
42
|
+
* 提示词里的结构标签换成全角,这样群友文本再也伪造不出段落。
|
|
43
|
+
*/
|
|
44
|
+
export function sanitizeUntrustedText(value: string): string {
|
|
45
|
+
return neutralizeStructureTags(
|
|
46
|
+
String(value ?? "")
|
|
47
|
+
.replace(/【/g, "[")
|
|
48
|
+
.replace(/】/g, "]")
|
|
49
|
+
.replace(NEWLINE_LIKE, " ")
|
|
50
|
+
.replace(ZERO_WIDTH, "")
|
|
51
|
+
.replace(PRIVATE_USE, ""),
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 结构标签守卫:插件生成的结构标签在整体净化时先换成占位符。
|
|
57
|
+
*
|
|
58
|
+
* 群友文本里的 `<quote>` 之类必须中和,插件自己展开的引用块与转发块要原样保留。
|
|
59
|
+
* 占位符用私用区字符(单个码点,截断时不会被切成两半),
|
|
60
|
+
* 群友文本里的私用区字符会被净化掉,伪造不出占位符。
|
|
61
|
+
*/
|
|
62
|
+
export class StructureTagGuard {
|
|
63
|
+
private readonly tags: string[] = []
|
|
64
|
+
|
|
65
|
+
/** 登记一个插件生成的结构标签,返回可安全拼接的占位符。 */
|
|
66
|
+
protect(tag: string): string {
|
|
67
|
+
const index = this.tags.push(tag) - 1
|
|
68
|
+
return String.fromCharCode(PLACEHOLDER_START + index)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 把占位符还原成原来的标签。 */
|
|
72
|
+
restore(text: string): string {
|
|
73
|
+
return text.replace(/[\uE000-\uF8FF]/g, (char) => {
|
|
74
|
+
const tag = this.tags[char.charCodeAt(0) - PLACEHOLDER_START]
|
|
75
|
+
return tag ?? ""
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 净化发送者显示名:群名片可被伪造,去掉控制字符与结构符号。 */
|
|
81
|
+
export function sanitizeSenderName(value: string): string {
|
|
82
|
+
return (
|
|
83
|
+
String(value ?? "")
|
|
84
|
+
.replace(ZERO_WIDTH, "")
|
|
85
|
+
.replace(CONTROL, " ")
|
|
86
|
+
// 私用区字符是结构标签的占位符,群名片里出现会被还原成真正的标签。
|
|
87
|
+
.replace(PRIVATE_USE, "")
|
|
88
|
+
.replace(/[【】]/g, (char) => (char === "【" ? "[" : "]"))
|
|
89
|
+
.replace(/[<>]/g, (char) => (char === "<" ? "<" : ">"))
|
|
90
|
+
.replace(/\s+/g, " ")
|
|
91
|
+
.trim()
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const TIMESTAMP_FORMAT = new Intl.DateTimeFormat("sv-SE", {
|
|
96
|
+
year: "2-digit",
|
|
97
|
+
month: "2-digit",
|
|
98
|
+
day: "2-digit",
|
|
99
|
+
hour: "2-digit",
|
|
100
|
+
minute: "2-digit",
|
|
101
|
+
hour12: false,
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
/** 绝对时间标注:本地时区的 `YY-MM-DD HH:MM`;时间无效时返回空串。 */
|
|
105
|
+
export function formatTimestamp(seconds: number): string {
|
|
106
|
+
if (!Number.isFinite(seconds) || seconds <= 0) return ""
|
|
107
|
+
return TIMESTAMP_FORMAT.format(new Date(seconds * 1000))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
import type { Role } from "./tools/policy"
|
|
111
|
+
|
|
112
|
+
/** 一条消息的模型视图。 */
|
|
113
|
+
export interface ModelMessage {
|
|
114
|
+
/** 发送者显示名。 */
|
|
115
|
+
sender: string
|
|
116
|
+
/** 发送者 QQ 号。 */
|
|
117
|
+
userId: string
|
|
118
|
+
/** 消息正文。 */
|
|
119
|
+
text: string
|
|
120
|
+
/** 发送时间(Unix 秒)。 */
|
|
121
|
+
time: number
|
|
122
|
+
/** 发送者角色;owner / admin 会在模型视图里带上对应的角色标记。 */
|
|
123
|
+
role?: Role
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 拼成一行模型视图消息:`[绝对时间] 名字(owner): 正文`;普通成员没有角色标记。 */
|
|
127
|
+
export function formatModelMessage(message: ModelMessage): string {
|
|
128
|
+
// QQ 号来自 QQ 服务,但仍是外部输入,按显示名净化一遍。
|
|
129
|
+
const userId = sanitizeSenderName(message.userId)
|
|
130
|
+
const name = sanitizeSenderName(message.sender) || userId || "未知用户"
|
|
131
|
+
const stamp = formatTimestamp(message.time)
|
|
132
|
+
const prefix = stamp ? `[${stamp}] ` : ""
|
|
133
|
+
// 只给 owner / admin 加角色标记,让模型知道这句话是谁说的。
|
|
134
|
+
const role = message.role === "owner" ? "(owner)" : message.role === "admin" ? "(admin)" : ""
|
|
135
|
+
return `${prefix}${name}${role}: ${message.text.trim()}`
|
|
136
|
+
}
|
package/src/naplink/client.ts
CHANGED
|
@@ -2,6 +2,7 @@ import {
|
|
|
2
2
|
NapLink,
|
|
3
3
|
type GroupMessageEvent,
|
|
4
4
|
type MessageSegment,
|
|
5
|
+
type NoticeEvent,
|
|
5
6
|
type OneBotApi,
|
|
6
7
|
type PrivateMessageEvent,
|
|
7
8
|
} from "@naplink/naplink"
|
|
@@ -75,16 +76,6 @@ export async function hydrateSegment(
|
|
|
75
76
|
}
|
|
76
77
|
}
|
|
77
78
|
|
|
78
|
-
/** 补全一条消息里所有媒体段的远程直链。 */
|
|
79
|
-
export async function hydrateMedia(
|
|
80
|
-
api: OneBotApi,
|
|
81
|
-
message: MessageSegment[],
|
|
82
|
-
logger: Logger,
|
|
83
|
-
): Promise<void> {
|
|
84
|
-
if (!Array.isArray(message)) return
|
|
85
|
-
await Promise.all(message.map((segment) => hydrateSegment(api, segment, logger)))
|
|
86
|
-
}
|
|
87
|
-
|
|
88
79
|
/** NapCat 的连接与 API 门面,屏蔽 SDK 细节。 */
|
|
89
80
|
export class QQClient {
|
|
90
81
|
private readonly link: NapLink
|
|
@@ -120,6 +111,16 @@ export class QQClient {
|
|
|
120
111
|
return this.link.api
|
|
121
112
|
}
|
|
122
113
|
|
|
114
|
+
/**
|
|
115
|
+
* 调用 SDK 类型里没有声明的 OneBot 动作。
|
|
116
|
+
*
|
|
117
|
+
* 收藏表情相关的动作(`fetch_custom_face_detail`、`set_custom_face_desc`)
|
|
118
|
+
* 不在 naplink 的类型表里,只能这样透传。
|
|
119
|
+
*/
|
|
120
|
+
callApi<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T> {
|
|
121
|
+
return this.link.callApi<T>(method, params)
|
|
122
|
+
}
|
|
123
|
+
|
|
123
124
|
get connected(): boolean {
|
|
124
125
|
return this.link.isConnected()
|
|
125
126
|
}
|
|
@@ -179,13 +180,9 @@ export class QQClient {
|
|
|
179
180
|
this.link.on("message.private", handler)
|
|
180
181
|
}
|
|
181
182
|
|
|
182
|
-
/**
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
await hydrateMedia(this.api, message, this.logger)
|
|
186
|
-
} catch (error) {
|
|
187
|
-
this.logger.warn("补全媒体直链失败", error)
|
|
188
|
-
}
|
|
183
|
+
/** 订阅通知类事件(撤回、进退群、戳一戳等)。 */
|
|
184
|
+
onNotice(handler: (event: NoticeEvent) => void): void {
|
|
185
|
+
this.link.on("notice", handler)
|
|
189
186
|
}
|
|
190
187
|
|
|
191
188
|
/** 机器人自己的 QQ 号,未连接时返回 undefined。 */
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import type { MessageEvent, MessageSegment, OneBotApi } from "@naplink/naplink"
|
|
2
|
+
import type { ChatTarget } from "../chat"
|
|
3
|
+
import type { Logger } from "../logger"
|
|
4
|
+
import type { Role } from "../tools/policy"
|
|
5
|
+
import { formatModelMessage, sanitizeSenderName } from "../model-view"
|
|
6
|
+
import type { MediaStore } from "./media"
|
|
7
|
+
import { createImageBudget, renderMessage, type PromptFile, type RenderContext } from "./render"
|
|
8
|
+
|
|
9
|
+
/** 已经投递到的位置:消息 ID 与发送时间。 */
|
|
10
|
+
export interface HistoryPosition {
|
|
11
|
+
/** 消息 ID。 */
|
|
12
|
+
id: string
|
|
13
|
+
/** 发送时间(秒)。 */
|
|
14
|
+
time: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 历史回填的请求参数。 */
|
|
18
|
+
export interface HistoryOptions {
|
|
19
|
+
/** 最多补多少条历史消息。 */
|
|
20
|
+
count: number
|
|
21
|
+
/** 上次已经投递到的位置;只补它之后的消息。 */
|
|
22
|
+
since?: HistoryPosition
|
|
23
|
+
/** 本次运行已经实时处理过的消息 ID,不重复补。 */
|
|
24
|
+
exclude?: ReadonlySet<string>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 历史回填的结果。 */
|
|
28
|
+
export interface HistoryResult {
|
|
29
|
+
/** 拼在首轮消息前面的历史文本块。 */
|
|
30
|
+
text: string
|
|
31
|
+
/** 历史消息里的图片附件。 */
|
|
32
|
+
files: PromptFile[]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 历史回填的来源,会话管理只依赖这个接口。 */
|
|
36
|
+
export interface HistoryProvider {
|
|
37
|
+
/** 拉取目标的历史消息并渲染成文本块与附件。 */
|
|
38
|
+
fetch(target: ChatTarget, options: HistoryOptions): Promise<HistoryResult>
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** NapCat 历史接口返回的消息结构,只取插件用得到的字段。 */
|
|
42
|
+
interface RawMessage {
|
|
43
|
+
message_id?: number
|
|
44
|
+
message_seq?: number
|
|
45
|
+
time?: number
|
|
46
|
+
user_id?: number
|
|
47
|
+
sender?: { user_id?: number; nickname?: string; card?: string }
|
|
48
|
+
message?: MessageSegment[] | string
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 补齐历史时最多翻多少页,避免长时间离线时无限翻页。 */
|
|
52
|
+
const MAX_HISTORY_PAGES = 10
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 创建历史回填的来源。
|
|
56
|
+
*
|
|
57
|
+
* 群聊与私聊都要补,NapCat 的两个历史接口参数不同,这里按目标类型分派。
|
|
58
|
+
*/
|
|
59
|
+
export function createHistoryProvider(deps: {
|
|
60
|
+
api: OneBotApi
|
|
61
|
+
logger: Logger
|
|
62
|
+
media: MediaStore
|
|
63
|
+
names?: Map<string, { name: string; expires: number }>
|
|
64
|
+
/** 发送者角色,用来给 owner 的历史消息加同样的标记。 */
|
|
65
|
+
roleOf?: (userId: string) => Role
|
|
66
|
+
}): HistoryProvider {
|
|
67
|
+
return {
|
|
68
|
+
async fetch(target, options) {
|
|
69
|
+
const count = Math.max(0, Math.floor(options.count))
|
|
70
|
+
if (count === 0) return { text: "", files: [] }
|
|
71
|
+
|
|
72
|
+
const ctx: RenderContext = { ...deps, target }
|
|
73
|
+
const entries = options.since
|
|
74
|
+
? await fetchGap(ctx, options.since, count, options.exclude)
|
|
75
|
+
: await fetchLatest(ctx, count, options.exclude)
|
|
76
|
+
if (entries.length === 0) return { text: "", files: [] }
|
|
77
|
+
|
|
78
|
+
// 整批历史共用一份图片预算,避免单次回填塞爆上下文。
|
|
79
|
+
const budget = createImageBudget()
|
|
80
|
+
const lines: string[] = []
|
|
81
|
+
const files: PromptFile[] = []
|
|
82
|
+
for (const entry of entries) {
|
|
83
|
+
const rendered = await renderMessage(ctx, toEvent(entry), budget)
|
|
84
|
+
const text = rendered.text.trim()
|
|
85
|
+
if (!text && rendered.files.length === 0) continue
|
|
86
|
+
const userId = String(entry.sender?.user_id ?? entry.user_id ?? "")
|
|
87
|
+
lines.push(
|
|
88
|
+
formatModelMessage({
|
|
89
|
+
sender: senderName(entry),
|
|
90
|
+
userId,
|
|
91
|
+
text: rendered.text,
|
|
92
|
+
time: entry.time ?? 0,
|
|
93
|
+
...(deps.roleOf ? { role: deps.roleOf(userId) } : {}),
|
|
94
|
+
}),
|
|
95
|
+
)
|
|
96
|
+
for (const file of rendered.files) {
|
|
97
|
+
files.push({ ...file, name: `qq-history-${files.length + 1}-${file.name}` })
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (lines.length === 0) return { text: "", files: [] }
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
text: `<history>\n之前的聊天记录(按时间顺序):\n${lines.join("\n")}\n</history>`,
|
|
104
|
+
files,
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 补最近的历史消息:新建会话时用。
|
|
112
|
+
*
|
|
113
|
+
* 已经在本次运行里实时处理过的消息要排除掉,否则会在首轮里重复出现。
|
|
114
|
+
*/
|
|
115
|
+
async function fetchLatest(
|
|
116
|
+
ctx: RenderContext,
|
|
117
|
+
count: number,
|
|
118
|
+
exclude: ReadonlySet<string> | undefined,
|
|
119
|
+
): Promise<RawMessage[]> {
|
|
120
|
+
// 多要一些,用来抵消被排除的消息。
|
|
121
|
+
const wanted = count + Math.min(exclude?.size ?? 0, count)
|
|
122
|
+
// 不传 reverse_order 或传 false:取目标 seq 往当前时间的 count 条。
|
|
123
|
+
const entries = await requestHistory(ctx, "0", wanted, false)
|
|
124
|
+
const fresh = exclude
|
|
125
|
+
? entries.filter((entry) => !exclude.has(String(entry.message_id)))
|
|
126
|
+
: entries
|
|
127
|
+
return sortByTime(fresh).slice(-count)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 补上次位置之后的历史消息:从重启中恢复时用。
|
|
132
|
+
*
|
|
133
|
+
* NapCat 的历史接口方向由 `reverse_order` 决定:传 true 才是往更早的时间翻。
|
|
134
|
+
* 所以从最新一条开始往回翻(游标取页内最旧一条的 message_id),翻到上次位置为止;
|
|
135
|
+
* 翻到的消息按时间排序后就是增量。
|
|
136
|
+
*/
|
|
137
|
+
async function fetchGap(
|
|
138
|
+
ctx: RenderContext,
|
|
139
|
+
since: HistoryPosition,
|
|
140
|
+
count: number,
|
|
141
|
+
exclude: ReadonlySet<string> | undefined,
|
|
142
|
+
): Promise<RawMessage[]> {
|
|
143
|
+
const collected: RawMessage[] = []
|
|
144
|
+
const seen = new Set<string>()
|
|
145
|
+
let cursor = "0"
|
|
146
|
+
let reached = false
|
|
147
|
+
let pages = 0
|
|
148
|
+
|
|
149
|
+
for (let page = 0; page < MAX_HISTORY_PAGES; page += 1) {
|
|
150
|
+
pages += 1
|
|
151
|
+
const entries = await requestHistory(ctx, cursor, count, true)
|
|
152
|
+
if (entries.length === 0) break
|
|
153
|
+
|
|
154
|
+
let added = 0
|
|
155
|
+
for (const entry of entries) {
|
|
156
|
+
const id = String(entry.message_id)
|
|
157
|
+
if (seen.has(id)) continue
|
|
158
|
+
seen.add(id)
|
|
159
|
+
collected.push(entry)
|
|
160
|
+
added += 1
|
|
161
|
+
if (id === since.id) reached = true
|
|
162
|
+
}
|
|
163
|
+
// 这一页没有新消息,说明往前翻不动了。
|
|
164
|
+
if (added === 0) break
|
|
165
|
+
if (reached) break
|
|
166
|
+
|
|
167
|
+
const oldest = entries.reduce((min, entry) =>
|
|
168
|
+
(entry.time ?? 0) <= (min.time ?? 0) ? entry : min,
|
|
169
|
+
)
|
|
170
|
+
const next = String(oldest.message_id)
|
|
171
|
+
if (next === cursor) break
|
|
172
|
+
cursor = next
|
|
173
|
+
}
|
|
174
|
+
if (!reached && pages >= MAX_HISTORY_PAGES) {
|
|
175
|
+
ctx.logger.warn(`历史增量超过 ${MAX_HISTORY_PAGES} 页,只补最近 ${count} 条`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const sorted = sortByTime(collected)
|
|
179
|
+
// 命中上次位置就按位置切;没命中(位置已被清理)就按时间切。
|
|
180
|
+
const start = reached
|
|
181
|
+
? sorted.findIndex((entry) => String(entry.message_id) === since.id) + 1
|
|
182
|
+
: sorted.findIndex((entry) => (entry.time ?? 0) > since.time)
|
|
183
|
+
const fresh = sorted.slice(start < 0 ? sorted.length : start)
|
|
184
|
+
const withoutExclude = exclude
|
|
185
|
+
? fresh.filter((entry) => !exclude.has(String(entry.message_id)))
|
|
186
|
+
: fresh
|
|
187
|
+
return withoutExclude.slice(-count)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** 请求 NapCat 的历史接口;失败或没有历史时返回空列表。 */
|
|
191
|
+
async function requestHistory(
|
|
192
|
+
ctx: RenderContext,
|
|
193
|
+
cursor: string,
|
|
194
|
+
count: number,
|
|
195
|
+
reverseOrder: boolean,
|
|
196
|
+
): Promise<RawMessage[]> {
|
|
197
|
+
// 失败必须让调用方知道:把空数组当成“没有历史”会让 historyDone 被错误置位。
|
|
198
|
+
const response =
|
|
199
|
+
ctx.target.kind === "group"
|
|
200
|
+
? await ctx.api.getGroupMsgHistory({
|
|
201
|
+
group_id: ctx.target.id,
|
|
202
|
+
message_seq: cursor,
|
|
203
|
+
count,
|
|
204
|
+
reverse_order: reverseOrder,
|
|
205
|
+
})
|
|
206
|
+
: await ctx.api.getFriendMsgHistory({
|
|
207
|
+
user_id: ctx.target.id,
|
|
208
|
+
message_seq: cursor,
|
|
209
|
+
count,
|
|
210
|
+
reverse_order: reverseOrder,
|
|
211
|
+
})
|
|
212
|
+
return normalize(response)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** NapCat 返回 `{ messages: [...] }`,兼容裸数组。 */
|
|
216
|
+
function normalize(response: unknown): RawMessage[] {
|
|
217
|
+
if (Array.isArray(response)) return response as RawMessage[]
|
|
218
|
+
if (response && typeof response === "object") {
|
|
219
|
+
const messages = (response as { messages?: unknown }).messages
|
|
220
|
+
if (Array.isArray(messages)) return messages as RawMessage[]
|
|
221
|
+
}
|
|
222
|
+
return []
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** 按发送时间从旧到新排序,时间相同时用消息序号稳定排序。 */
|
|
226
|
+
function sortByTime(entries: readonly RawMessage[]): RawMessage[] {
|
|
227
|
+
return [...entries].sort(
|
|
228
|
+
(a, b) => (a.time ?? 0) - (b.time ?? 0) || (a.message_seq ?? 0) - (b.message_seq ?? 0),
|
|
229
|
+
)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** 把历史消息拼成渲染器能吃的消息事件。 */
|
|
233
|
+
function toEvent(entry: RawMessage): MessageEvent {
|
|
234
|
+
const message: MessageSegment[] = Array.isArray(entry.message)
|
|
235
|
+
? entry.message
|
|
236
|
+
: [{ type: "text", data: { text: String(entry.message ?? "") } }]
|
|
237
|
+
return {
|
|
238
|
+
time: entry.time ?? 0,
|
|
239
|
+
self_id: 0,
|
|
240
|
+
post_type: "message",
|
|
241
|
+
message_type: "private",
|
|
242
|
+
sub_type: "normal",
|
|
243
|
+
message_id: entry.message_id ?? 0,
|
|
244
|
+
user_id: entry.user_id ?? 0,
|
|
245
|
+
message,
|
|
246
|
+
raw_message: "",
|
|
247
|
+
font: 0,
|
|
248
|
+
sender: {
|
|
249
|
+
user_id: entry.sender?.user_id ?? entry.user_id,
|
|
250
|
+
nickname: entry.sender?.nickname,
|
|
251
|
+
card: entry.sender?.card,
|
|
252
|
+
},
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** 历史消息里的显示名,优先用群名片。 */
|
|
257
|
+
function senderName(entry: RawMessage): string {
|
|
258
|
+
const card = entry.sender?.card?.trim()
|
|
259
|
+
if (card) return sanitizeSenderName(card)
|
|
260
|
+
const nickname = entry.sender?.nickname?.trim()
|
|
261
|
+
if (nickname) return sanitizeSenderName(nickname)
|
|
262
|
+
return sanitizeSenderName(String(entry.user_id ?? "未知用户"))
|
|
263
|
+
}
|