@cmach_socket/opencode-qq-bot 0.6.6 → 0.6.7
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 +12 -8
- package/package.json +1 -1
- package/src/access.ts +0 -5
- package/src/async.ts +25 -0
- package/src/commands.ts +8 -13
- package/src/config.ts +36 -83
- package/src/emoji/command.ts +0 -2
- package/src/emoji/label.ts +10 -22
- package/src/events/notice.ts +0 -19
- package/src/home.ts +8 -6
- package/src/index.ts +92 -81
- package/src/keepalive.ts +10 -24
- package/src/logger.ts +2 -1
- package/src/media-path.ts +2 -4
- package/src/model-view.ts +2 -2
- package/src/naplink/media.ts +4 -8
- package/src/naplink/render.ts +41 -53
- package/src/overrides.ts +6 -17
- package/src/rate-limit.ts +2 -1
- package/src/safe-fetch.ts +1 -5
- package/src/sensitive.ts +3 -5
- package/src/session/find.ts +45 -0
- package/src/session/manager.ts +70 -93
- package/src/session/proactive.ts +8 -11
- package/src/session/soul.ts +54 -31
- package/src/text.ts +7 -0
- package/src/tools/policy.ts +6 -0
- package/src/tools/qq.ts +85 -67
- package/src/tui-commands.ts +1 -1
package/src/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Plugin } from "@opencode/plugin"
|
|
2
2
|
import type { GroupMessageEvent, MessageEvent, NoticeEvent } from "@naplink/naplink"
|
|
3
3
|
import { Mutex } from "async-mutex"
|
|
4
|
+
import { delay, unrefTimer } from "./async"
|
|
4
5
|
import { acquireBotLock, type BotLock, botLockPath } from "./bot-lock"
|
|
5
6
|
import { type ChatTarget, targetKey, targetLabel } from "./chat"
|
|
6
7
|
import { allowedTargets, isTargetAllowed } from "./access"
|
|
@@ -20,7 +21,7 @@ import { collectEnvSecrets, redactUrl, secretsFromUrl, SensitiveChecker } from "
|
|
|
20
21
|
import { SessionManager } from "./session/manager"
|
|
21
22
|
import { currentTimeText, PROACTIVE_HINT } from "./session/prompt"
|
|
22
23
|
import { proactiveProbability } from "./session/proactive"
|
|
23
|
-
import { packageDirectory, SoulLibrary } from "./session/soul"
|
|
24
|
+
import { packageDirectory, seedSouls, SoulLibrary } from "./session/soul"
|
|
24
25
|
import { COMMANDS, handleCommand, isCommandChat } from "./commands"
|
|
25
26
|
import {
|
|
26
27
|
chatMuted,
|
|
@@ -50,10 +51,6 @@ const RETRY_DELAY_MS = 1000
|
|
|
50
51
|
/** 机器人连接被别的实例占用时,多久重试一次接管。 */
|
|
51
52
|
const CLAIM_RETRY_MS = 30_000
|
|
52
53
|
|
|
53
|
-
function delay(ms: number): Promise<void> {
|
|
54
|
-
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
55
|
-
}
|
|
56
|
-
|
|
57
54
|
/** 迁移类告警用 error 级别输出,其余保持 warn。 */
|
|
58
55
|
function reportWarnings(warnings: readonly string[], logger: Logger): void {
|
|
59
56
|
for (const warning of warnings) {
|
|
@@ -76,6 +73,43 @@ function knownSecrets(config: QQBotConfig): string[] {
|
|
|
76
73
|
].filter((secret) => secret.length > 0)
|
|
77
74
|
}
|
|
78
75
|
|
|
76
|
+
const isGroupEvent = (event: MessageEvent): event is GroupMessageEvent =>
|
|
77
|
+
event.message_type === "group"
|
|
78
|
+
|
|
79
|
+
/** 只取消息里的文本段,用于识别管理命令。 */
|
|
80
|
+
function messageText(event: MessageEvent): string {
|
|
81
|
+
return (event.message ?? [])
|
|
82
|
+
.filter((segment) => segment.type === "text")
|
|
83
|
+
.map((segment) => String((segment.data as { text?: unknown }).text ?? ""))
|
|
84
|
+
.join(" ")
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 必回原因对应给模型的一句话。 */
|
|
88
|
+
function wakeHint(reason: WakeReason | undefined): string {
|
|
89
|
+
switch (reason) {
|
|
90
|
+
case "private":
|
|
91
|
+
return "这是一条私聊消息,必须回复。"
|
|
92
|
+
case "all":
|
|
93
|
+
return "这个群要求每条消息都回复,必须回复。"
|
|
94
|
+
case "mention":
|
|
95
|
+
return "你被 @ 了,必须回复。"
|
|
96
|
+
case "prefix":
|
|
97
|
+
return "这条消息命中了唤醒前缀,必须回复。"
|
|
98
|
+
case "at_all":
|
|
99
|
+
return "这条消息 @ 了全体成员,必须回复。"
|
|
100
|
+
case "reply":
|
|
101
|
+
return "这条消息回复了你,必须回复。"
|
|
102
|
+
default:
|
|
103
|
+
return "这条消息没有要求你回复,可以选择不回复。"
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function eventTarget(event: MessageEvent): ChatTarget {
|
|
108
|
+
return isGroupEvent(event)
|
|
109
|
+
? { kind: "group", id: event.group_id }
|
|
110
|
+
: { kind: "private", id: event.user_id }
|
|
111
|
+
}
|
|
112
|
+
|
|
79
113
|
export default Plugin.define({
|
|
80
114
|
id: "opencode-qq-bot",
|
|
81
115
|
async setup(ctx) {
|
|
@@ -236,16 +270,16 @@ export default Plugin.define({
|
|
|
236
270
|
if (disposed) return
|
|
237
271
|
runtimeStarted = true
|
|
238
272
|
|
|
239
|
-
//
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
)
|
|
273
|
+
// 角色设定:先把随包分发的初始文件补进工作目录,之后一直读工作目录里的副本,
|
|
274
|
+
// 升级插件不会覆盖掉用户改过的设定。默认档之外还能按聊天覆盖,改完下一轮即生效。
|
|
275
|
+
const soulOptions = {
|
|
276
|
+
soulPath: config.soulPath,
|
|
277
|
+
soulName: config.soulName,
|
|
278
|
+
home: home.directory,
|
|
279
|
+
moduleDir: packageDirectory(),
|
|
280
|
+
}
|
|
281
|
+
await seedSouls(soulOptions, logger)
|
|
282
|
+
const souls = new SoulLibrary(soulOptions, logger)
|
|
249
283
|
cleanup.add("停止角色设定热重载", () => souls.dispose(), CleanupOrder.souls)
|
|
250
284
|
await souls.loadDefault()
|
|
251
285
|
|
|
@@ -259,6 +293,15 @@ export default Plugin.define({
|
|
|
259
293
|
allowedDirs: [home.directory, mediaDir, ...config.media.allowedDirs],
|
|
260
294
|
})
|
|
261
295
|
const nameCache = new Map<string, { name: string; expires: number }>()
|
|
296
|
+
/** 渲染上下文:上游 API、媒体存储与昵称缓存都在这里一次性绑定。 */
|
|
297
|
+
const renderContext = (target: ChatTarget, selfId?: string) => ({
|
|
298
|
+
api: client.api,
|
|
299
|
+
target,
|
|
300
|
+
logger,
|
|
301
|
+
media,
|
|
302
|
+
names: nameCache,
|
|
303
|
+
...(selfId ? { selfId } : {}),
|
|
304
|
+
})
|
|
262
305
|
const history = createHistoryProvider({
|
|
263
306
|
api: client.api,
|
|
264
307
|
logger,
|
|
@@ -335,8 +378,7 @@ export default Plugin.define({
|
|
|
335
378
|
},
|
|
336
379
|
60 * 60 * 1000,
|
|
337
380
|
)
|
|
338
|
-
|
|
339
|
-
mediaHandle.unref?.()
|
|
381
|
+
unrefTimer(mediaCleanup)
|
|
340
382
|
cleanup.add("停止媒体清理定时器", () => clearInterval(mediaCleanup), CleanupOrder.events)
|
|
341
383
|
// 收藏表情:标签只存在 NapCat 侧,插件不保存副本;编号由插件自己维护。
|
|
342
384
|
const favorites = new FavoriteStore(
|
|
@@ -538,22 +580,25 @@ export default Plugin.define({
|
|
|
538
580
|
],
|
|
539
581
|
signal: idleAbort.signal,
|
|
540
582
|
})) {
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
sessionID
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
583
|
+
// 单条事件处理失败只记日志:连带把订阅循环拆掉会让缓存消息再也发不出去。
|
|
584
|
+
try {
|
|
585
|
+
const sessionID = event.data.sessionID
|
|
586
|
+
logger.debug(`上游事件:${event.type}`, {
|
|
587
|
+
sessionID,
|
|
588
|
+
...(event.type === "session.status" ? { status: event.data.status.type } : {}),
|
|
589
|
+
})
|
|
590
|
+
if (event.type === "session.status") {
|
|
591
|
+
if (event.data.status.type === "idle") await manager.flushBuffered(sessionID)
|
|
592
|
+
} else if (event.type === "session.execution.succeeded") {
|
|
593
|
+
await manager.flushBuffered(sessionID)
|
|
594
|
+
} else {
|
|
595
|
+
// 失败事件带上游错误信息,只进日志(logger 会脱敏),不进聊天。
|
|
596
|
+
const detail =
|
|
597
|
+
event.type === "session.execution.failed" ? event.data.error.message : undefined
|
|
598
|
+
await manager.handleExecutionEnd(sessionID, event.type, detail)
|
|
549
599
|
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
} else {
|
|
553
|
-
// 失败事件带上游错误信息,只进日志(logger 会脱敏),不进聊天。
|
|
554
|
-
const detail =
|
|
555
|
-
event.type === "session.execution.failed" ? event.data.error.message : undefined
|
|
556
|
-
await manager.handleExecutionEnd(event.data.sessionID, event.type, detail)
|
|
600
|
+
} catch (error) {
|
|
601
|
+
logger.warn("处理会话事件失败", error)
|
|
557
602
|
}
|
|
558
603
|
}
|
|
559
604
|
} catch (error) {
|
|
@@ -564,41 +609,6 @@ export default Plugin.define({
|
|
|
564
609
|
}
|
|
565
610
|
})()
|
|
566
611
|
|
|
567
|
-
const isGroupEvent = (event: MessageEvent): event is GroupMessageEvent =>
|
|
568
|
-
event.message_type === "group"
|
|
569
|
-
|
|
570
|
-
/** 只取消息里的文本段,用于识别管理命令。 */
|
|
571
|
-
const messageText = (event: MessageEvent): string =>
|
|
572
|
-
(event.message ?? [])
|
|
573
|
-
.filter((segment) => segment.type === "text")
|
|
574
|
-
.map((segment) => String((segment.data as { text?: unknown }).text ?? ""))
|
|
575
|
-
.join(" ")
|
|
576
|
-
|
|
577
|
-
/** 必回原因对应给模型的一句话。 */
|
|
578
|
-
const wakeHint = (reason: WakeReason | undefined): string => {
|
|
579
|
-
switch (reason) {
|
|
580
|
-
case "private":
|
|
581
|
-
return "这是一条私聊消息,必须回复。"
|
|
582
|
-
case "all":
|
|
583
|
-
return "这个群要求每条消息都回复,必须回复。"
|
|
584
|
-
case "mention":
|
|
585
|
-
return "你被 @ 了,必须回复。"
|
|
586
|
-
case "prefix":
|
|
587
|
-
return "这条消息命中了唤醒前缀,必须回复。"
|
|
588
|
-
case "at_all":
|
|
589
|
-
return "这条消息 @ 了全体成员,必须回复。"
|
|
590
|
-
case "reply":
|
|
591
|
-
return "这条消息回复了你,必须回复。"
|
|
592
|
-
default:
|
|
593
|
-
return "这条消息没有要求你回复,可以选择不回复。"
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
const eventTarget = (event: MessageEvent): ChatTarget =>
|
|
598
|
-
isGroupEvent(event)
|
|
599
|
-
? { kind: "group", id: event.group_id }
|
|
600
|
-
: { kind: "private", id: event.user_id }
|
|
601
|
-
|
|
602
612
|
const handleMessage = async (
|
|
603
613
|
event: MessageEvent,
|
|
604
614
|
target: ChatTarget,
|
|
@@ -629,14 +639,7 @@ export default Plugin.define({
|
|
|
629
639
|
}
|
|
630
640
|
if (!shouldProcess(event.message, selfId)) return
|
|
631
641
|
|
|
632
|
-
const renderCtx =
|
|
633
|
-
api: client.api,
|
|
634
|
-
target,
|
|
635
|
-
logger,
|
|
636
|
-
media,
|
|
637
|
-
names: nameCache,
|
|
638
|
-
selfId,
|
|
639
|
-
}
|
|
642
|
+
const renderCtx = renderContext(target, selfId)
|
|
640
643
|
const rendered = await renderMessage(renderCtx, event)
|
|
641
644
|
if (!rendered.text.trim()) return
|
|
642
645
|
|
|
@@ -657,6 +660,12 @@ export default Plugin.define({
|
|
|
657
660
|
config.wake,
|
|
658
661
|
)
|
|
659
662
|
|
|
663
|
+
logger.info(`${targetLabel(target)} 消息交给模型`, {
|
|
664
|
+
user: String(event.user_id),
|
|
665
|
+
role: senderRole,
|
|
666
|
+
required: decision.required,
|
|
667
|
+
...(decision.reason ? { reason: decision.reason } : {}),
|
|
668
|
+
})
|
|
660
669
|
await manager.enqueue(target, {
|
|
661
670
|
text: formatModelMessage({
|
|
662
671
|
sender: userName,
|
|
@@ -702,6 +711,10 @@ export default Plugin.define({
|
|
|
702
711
|
return
|
|
703
712
|
}
|
|
704
713
|
manager.touch(target)
|
|
714
|
+
logger.info(`${targetLabel(target)} 收到 QQ 消息`, {
|
|
715
|
+
user: String(event.user_id),
|
|
716
|
+
message_id: String(event.message_id),
|
|
717
|
+
})
|
|
705
718
|
|
|
706
719
|
// 一条入站消息一个追踪 id,后面各个节点都挂在它下面。
|
|
707
720
|
const traceId = tracer?.startTrace()
|
|
@@ -731,9 +744,9 @@ export default Plugin.define({
|
|
|
731
744
|
if (!target || !isTargetAllowed(config.access, target, config.ownerQQ)) return
|
|
732
745
|
void (async () => {
|
|
733
746
|
try {
|
|
734
|
-
const renderCtx = { api: client.api, target, logger, media, names: nameCache }
|
|
735
747
|
const text = await describeNotice(event, {
|
|
736
|
-
nameOf: async (userId) =>
|
|
748
|
+
nameOf: async (userId) =>
|
|
749
|
+
await resolveUserName(renderContext(target), String(userId)),
|
|
737
750
|
})
|
|
738
751
|
if (!text) return
|
|
739
752
|
logger.info(`${targetLabel(target)} 收到通知:${text}`)
|
|
@@ -793,8 +806,7 @@ export default Plugin.define({
|
|
|
793
806
|
proactiveTimer = setInterval(() => {
|
|
794
807
|
void tick().catch((error: unknown) => logger.error("主动说话心跳失败", error))
|
|
795
808
|
}, config.proactive.tickSeconds * 1000)
|
|
796
|
-
|
|
797
|
-
handle.unref?.()
|
|
809
|
+
unrefTimer(proactiveTimer)
|
|
798
810
|
}
|
|
799
811
|
|
|
800
812
|
// 工具先注册,模型这一轮就能看到 qq_*;再连 NapCat 开始消费。
|
|
@@ -827,8 +839,7 @@ export default Plugin.define({
|
|
|
827
839
|
})
|
|
828
840
|
.catch((error: unknown) => logger.error("接管机器人连接失败", error))
|
|
829
841
|
}, CLAIM_RETRY_MS)
|
|
830
|
-
|
|
831
|
-
claimHandle.unref?.()
|
|
842
|
+
unrefTimer(claimTimer)
|
|
832
843
|
cleanup.add(
|
|
833
844
|
"停止接管重试定时器",
|
|
834
845
|
() => {
|
package/src/keepalive.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import { unrefTimer } from "./async"
|
|
2
3
|
import type { QQBotConfig } from "./config"
|
|
3
4
|
import type { Logger } from "./logger"
|
|
5
|
+
import { findSession } from "./session/find"
|
|
4
6
|
|
|
5
7
|
/** 插件存储里保存保活会话 ID 的键。 */
|
|
6
8
|
export const KEEP_ALIVE_SESSION_KEY = "keepalive-session"
|
|
@@ -9,8 +11,6 @@ export const KEEP_ALIVE_SESSION_MARKER = "qqKeepAliveSession"
|
|
|
9
11
|
/** 保活会话标题。 */
|
|
10
12
|
export const KEEP_ALIVE_TITLE = "QQ 保活"
|
|
11
13
|
|
|
12
|
-
type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
|
|
13
|
-
|
|
14
14
|
/**
|
|
15
15
|
* 保活心跳:让 OpenCode 不要因为长时间没有会话活动而卸载插件。
|
|
16
16
|
*
|
|
@@ -38,8 +38,7 @@ export class KeepAlive {
|
|
|
38
38
|
this.timer = setInterval(() => {
|
|
39
39
|
void this.ping()
|
|
40
40
|
}, this.config.keepAlive.seconds * 1000)
|
|
41
|
-
|
|
42
|
-
handle.unref?.()
|
|
41
|
+
unrefTimer(this.timer)
|
|
43
42
|
}
|
|
44
43
|
|
|
45
44
|
/**
|
|
@@ -179,26 +178,13 @@ export class KeepAlive {
|
|
|
179
178
|
|
|
180
179
|
/** 查找带保活标记的历史会话。 */
|
|
181
180
|
private async findKeepAliveSession(): Promise<string | undefined> {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
...(cursor ? { cursor } : {}),
|
|
190
|
-
})
|
|
191
|
-
const hit = result.data.find(
|
|
192
|
-
(session) => session.metadata?.[KEEP_ALIVE_SESSION_MARKER] === true,
|
|
193
|
-
)
|
|
194
|
-
if (hit) return hit.id
|
|
195
|
-
cursor = result.cursor.next ?? undefined
|
|
196
|
-
if (!cursor) break
|
|
197
|
-
}
|
|
198
|
-
} catch (error) {
|
|
199
|
-
this.logger.warn("查找保活会话失败", error)
|
|
200
|
-
}
|
|
201
|
-
return undefined
|
|
181
|
+
return await findSession(
|
|
182
|
+
this.ctx,
|
|
183
|
+
this.ctx.location.directory,
|
|
184
|
+
(session) => session.metadata?.[KEEP_ALIVE_SESSION_MARKER] === true,
|
|
185
|
+
this.logger,
|
|
186
|
+
"查找保活会话失败",
|
|
187
|
+
)
|
|
202
188
|
}
|
|
203
189
|
|
|
204
190
|
private async writeStoredSession(sessionID: string): Promise<void> {
|
package/src/logger.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { isAbsolute, join } from "node:path"
|
|
|
4
4
|
import { inspect } from "node:util"
|
|
5
5
|
import winston from "winston"
|
|
6
6
|
import DailyRotateFile from "winston-daily-rotate-file"
|
|
7
|
+
import { unrefTimer } from "./async"
|
|
7
8
|
import { maskSecrets } from "./sensitive"
|
|
8
9
|
|
|
9
10
|
/** 日志级别。 */
|
|
@@ -240,7 +241,7 @@ export function createLogger(prefix: string, options: LoggerOptions | LogLevel =
|
|
|
240
241
|
function waitFinish(transport: DailyRotateFile): Promise<void> {
|
|
241
242
|
return new Promise<void>((resolve) => {
|
|
242
243
|
const timer = setTimeout(() => resolve(), CLOSE_TIMEOUT_MS)
|
|
243
|
-
timer
|
|
244
|
+
unrefTimer(timer)
|
|
244
245
|
transport.once("finish", () => {
|
|
245
246
|
clearTimeout(timer)
|
|
246
247
|
resolve()
|
package/src/media-path.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { realpath, stat } from "node:fs/promises"
|
|
|
3
3
|
import { homedir } from "node:os"
|
|
4
4
|
import { isAbsolute, join, resolve, sep } from "node:path"
|
|
5
5
|
import ipaddr from "ipaddr.js"
|
|
6
|
+
import { expandTilde } from "./home"
|
|
6
7
|
import { ALLOWED_PORTS } from "./safe-fetch"
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -32,10 +33,7 @@ export type MediaPlan = { kind: "local"; path: string } | { kind: "remote"; url:
|
|
|
32
33
|
|
|
33
34
|
/** 展开 `~` 并去掉首尾空白。 */
|
|
34
35
|
function expand(value: string): string {
|
|
35
|
-
|
|
36
|
-
if (trimmed === "~") return homedir()
|
|
37
|
-
if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2))
|
|
38
|
-
return trimmed
|
|
36
|
+
return expandTilde(value.trim())
|
|
39
37
|
}
|
|
40
38
|
|
|
41
39
|
/**
|
package/src/model-view.ts
CHANGED
|
@@ -9,13 +9,13 @@
|
|
|
9
9
|
* 群友把 `<quote>` 拆成两段发过来,逐段净化匹配不到,只有整体净化才拦得住。
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { ZERO_WIDTH } from "./text"
|
|
13
|
+
|
|
12
14
|
/** 提示词里的结构标签;群友文本里出现同样字样时换成全角,避免伪造。 */
|
|
13
15
|
const STRUCTURE_TAG = /<\/?(quote|forward|history)>/gi
|
|
14
16
|
|
|
15
17
|
/** 换行类字符:换行、段分隔符、下一行、垂直制表、换页。 */
|
|
16
18
|
const NEWLINE_LIKE = /[\r\n\u2028\u2029\u0085\u000B\u000C]+/g
|
|
17
|
-
/** 零宽字符:可以用来把标签拆成看起来正常、匹配不上的形式。 */
|
|
18
|
-
const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
|
|
19
19
|
/** 控制字符:显示名里出现会破坏结构。 */
|
|
20
20
|
const CONTROL = /[\u0000-\u001F\u007F]+/g
|
|
21
21
|
/** 私用区字符:插件用它给结构标签占位,群友文本里的必须清掉,否则能伪造占位符。 */
|
package/src/naplink/media.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { pathToFileURL } from "node:url"
|
|
|
5
5
|
import type { Logger } from "../logger"
|
|
6
6
|
import { defaultMediaDir } from "../media-path"
|
|
7
7
|
import { type SafeFetcher, safeFetchBytes } from "../safe-fetch"
|
|
8
|
+
import { truncateForLog } from "../text"
|
|
8
9
|
|
|
9
10
|
/** 单张图片下载与落盘的字节上限。 */
|
|
10
11
|
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
|
@@ -84,12 +85,7 @@ function truncateCodePoints(text: string, max: number): string {
|
|
|
84
85
|
return Array.from(text).slice(0, max).join("")
|
|
85
86
|
}
|
|
86
87
|
|
|
87
|
-
|
|
88
|
-
function truncateForLog(value: string, max = 120): string {
|
|
89
|
-
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function decodeBase64(value: string): Uint8Array | undefined {
|
|
88
|
+
function decodeBase64Bytes(value: string): Uint8Array | undefined {
|
|
93
89
|
if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(value)) return undefined
|
|
94
90
|
const bytes = Buffer.from(value, "base64")
|
|
95
91
|
return bytes.byteLength > MAX_IMAGE_BYTES ? undefined : new Uint8Array(bytes)
|
|
@@ -98,7 +94,7 @@ function decodeBase64(value: string): Uint8Array | undefined {
|
|
|
98
94
|
function parseDataUrl(uri: string, logger: Logger): ImageBytes | undefined {
|
|
99
95
|
const match = /^data:([^;,]+)?(?:;[^,]*)*;base64,(.*)$/s.exec(uri)
|
|
100
96
|
if (!match) return undefined
|
|
101
|
-
const bytes =
|
|
97
|
+
const bytes = decodeBase64Bytes(match[2] ?? "")
|
|
102
98
|
if (!bytes) return undefined
|
|
103
99
|
// 以魔数嗅探为准:URI 里声明的类型由消息发送方控制,不能直接信任。
|
|
104
100
|
const mime = mimeFromBytes(bytes)
|
|
@@ -143,7 +139,7 @@ export class MediaStore {
|
|
|
143
139
|
|
|
144
140
|
private async readImage(url: string): Promise<ImageBytes | undefined> {
|
|
145
141
|
if (url.startsWith("base64://")) {
|
|
146
|
-
const bytes =
|
|
142
|
+
const bytes = decodeBase64Bytes(url.slice("base64://".length))
|
|
147
143
|
if (!bytes) {
|
|
148
144
|
this.logger.warn("base64 图片无效或超过大小上限")
|
|
149
145
|
return undefined
|
package/src/naplink/render.ts
CHANGED
|
@@ -20,7 +20,6 @@ import {
|
|
|
20
20
|
type StoredImage,
|
|
21
21
|
} from "./media"
|
|
22
22
|
|
|
23
|
-
export { MAX_IMAGE_BYTES, inlineImageBytes }
|
|
24
23
|
export type { PromptFile } from "./media"
|
|
25
24
|
|
|
26
25
|
/** 合并转发的解析上限,避免撑爆上下文。 */
|
|
@@ -227,6 +226,36 @@ function createForwardBudget(): ForwardBudget {
|
|
|
227
226
|
return { nodes: MAX_FORWARD_TOTAL_NODES, chars: MAX_FORWARD_TOTAL_CHARS }
|
|
228
227
|
}
|
|
229
228
|
|
|
229
|
+
/**
|
|
230
|
+
* 只产出文字、不涉及媒体与上游的消息段描述。
|
|
231
|
+
*
|
|
232
|
+
* 转发内容与普通消息共用,保证两边对同一种段落的措辞一致。
|
|
233
|
+
*
|
|
234
|
+
* @returns 段落文本;需要特殊处理(@、图片、语音、引用、转发)时返回 `undefined`。
|
|
235
|
+
*/
|
|
236
|
+
function describeSegment(segment: Segment): string | undefined {
|
|
237
|
+
switch (segment.type) {
|
|
238
|
+
case "text":
|
|
239
|
+
return sanitizeUntrustedText(segment.data.text)
|
|
240
|
+
case "video":
|
|
241
|
+
return "[视频]"
|
|
242
|
+
case "audio":
|
|
243
|
+
return "[音频]"
|
|
244
|
+
case "file":
|
|
245
|
+
return `[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`
|
|
246
|
+
case "face":
|
|
247
|
+
return renderFace(segment.data.id)
|
|
248
|
+
case "json":
|
|
249
|
+
return "[卡片消息]"
|
|
250
|
+
case "xml":
|
|
251
|
+
return "[XML消息]"
|
|
252
|
+
case "markdown":
|
|
253
|
+
return "[Markdown消息]"
|
|
254
|
+
default:
|
|
255
|
+
return undefined
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
230
259
|
async function renderForwardSegments(
|
|
231
260
|
ctx: RenderContext,
|
|
232
261
|
message: readonly MessageSegment[],
|
|
@@ -239,10 +268,12 @@ async function renderForwardSegments(
|
|
|
239
268
|
const images: StoredImage[] = []
|
|
240
269
|
for (const segment of segments(message)) {
|
|
241
270
|
try {
|
|
271
|
+
const described = describeSegment(segment)
|
|
272
|
+
if (described !== undefined) {
|
|
273
|
+
parts.push(described)
|
|
274
|
+
continue
|
|
275
|
+
}
|
|
242
276
|
switch (segment.type) {
|
|
243
|
-
case "text":
|
|
244
|
-
parts.push(sanitizeUntrustedText(segment.data.text))
|
|
245
|
-
break
|
|
246
277
|
case "at":
|
|
247
278
|
parts.push(`@${segment.data.qq} `)
|
|
248
279
|
break
|
|
@@ -260,27 +291,6 @@ async function renderForwardSegments(
|
|
|
260
291
|
case "record":
|
|
261
292
|
parts.push("[语音]")
|
|
262
293
|
break
|
|
263
|
-
case "video":
|
|
264
|
-
parts.push("[视频]")
|
|
265
|
-
break
|
|
266
|
-
case "audio":
|
|
267
|
-
parts.push("[音频]")
|
|
268
|
-
break
|
|
269
|
-
case "file":
|
|
270
|
-
parts.push(`[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`)
|
|
271
|
-
break
|
|
272
|
-
case "face":
|
|
273
|
-
parts.push(renderFace(segment.data.id))
|
|
274
|
-
break
|
|
275
|
-
case "json":
|
|
276
|
-
parts.push("[卡片消息]")
|
|
277
|
-
break
|
|
278
|
-
case "xml":
|
|
279
|
-
parts.push("[XML消息]")
|
|
280
|
-
break
|
|
281
|
-
case "markdown":
|
|
282
|
-
parts.push("[Markdown消息]")
|
|
283
|
-
break
|
|
284
294
|
case "reply":
|
|
285
295
|
// 转发节点里的引用没有上下文,跳过
|
|
286
296
|
break
|
|
@@ -387,10 +397,7 @@ export async function renderForward(
|
|
|
387
397
|
}
|
|
388
398
|
|
|
389
399
|
/** 把语音消息转成文字,转写失败时返回空字符串。 */
|
|
390
|
-
|
|
391
|
-
ctx: RenderContext,
|
|
392
|
-
messageId: number | undefined,
|
|
393
|
-
): Promise<string> {
|
|
400
|
+
async function fetchVoiceText(ctx: RenderContext, messageId: number | undefined): Promise<string> {
|
|
394
401
|
if (messageId === undefined) return ""
|
|
395
402
|
try {
|
|
396
403
|
const result = await ctx.api.fetchPttText(messageId)
|
|
@@ -461,10 +468,12 @@ export async function renderMessage(
|
|
|
461
468
|
|
|
462
469
|
for (const segment of message) {
|
|
463
470
|
try {
|
|
471
|
+
const described = describeSegment(segment)
|
|
472
|
+
if (described !== undefined) {
|
|
473
|
+
textBuffer.push(described)
|
|
474
|
+
continue
|
|
475
|
+
}
|
|
464
476
|
switch (segment.type) {
|
|
465
|
-
case "text":
|
|
466
|
-
textBuffer.push(sanitizeUntrustedText(segment.data.text))
|
|
467
|
-
break
|
|
468
477
|
case "at":
|
|
469
478
|
textBuffer.push(
|
|
470
479
|
`@${sanitizeSenderName(await resolveUserName(ctx, String(segment.data.qq)))} `,
|
|
@@ -516,27 +525,6 @@ export async function renderMessage(
|
|
|
516
525
|
}
|
|
517
526
|
break
|
|
518
527
|
}
|
|
519
|
-
case "video":
|
|
520
|
-
textBuffer.push("[视频]")
|
|
521
|
-
break
|
|
522
|
-
case "audio":
|
|
523
|
-
textBuffer.push("[音频]")
|
|
524
|
-
break
|
|
525
|
-
case "file":
|
|
526
|
-
textBuffer.push(`[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`)
|
|
527
|
-
break
|
|
528
|
-
case "face":
|
|
529
|
-
textBuffer.push(renderFace(segment.data.id))
|
|
530
|
-
break
|
|
531
|
-
case "json":
|
|
532
|
-
textBuffer.push("[卡片消息]")
|
|
533
|
-
break
|
|
534
|
-
case "xml":
|
|
535
|
-
textBuffer.push("[XML消息]")
|
|
536
|
-
break
|
|
537
|
-
case "markdown":
|
|
538
|
-
textBuffer.push("[Markdown消息]")
|
|
539
|
-
break
|
|
540
528
|
default:
|
|
541
529
|
ctx.logger.debug(`跳过未知消息段 type=${(segment as { type: string }).type}`)
|
|
542
530
|
break
|
package/src/overrides.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFile, stat } from "node:fs/promises"
|
|
2
2
|
import { join } from "node:path"
|
|
3
3
|
import { type ChatTarget, targetKey } from "./chat"
|
|
4
|
-
import { parseModelRef, type ModelRef } from "./config"
|
|
4
|
+
import { DEFAULT_CONFIG, parseModelRef, type ModelRef, type WakeConfig } from "./config"
|
|
5
5
|
import type { Logger } from "./logger"
|
|
6
6
|
|
|
7
7
|
/** 唤醒方式:决定群里的消息要不要让模型必须回复。 */
|
|
@@ -27,24 +27,13 @@ export interface WakeContext {
|
|
|
27
27
|
text: string
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
/**
|
|
31
|
-
export
|
|
32
|
-
/** 全局唤醒前缀,命中即必回。 */
|
|
33
|
-
prefixes: string[]
|
|
34
|
-
/** 是否忽略 @全体成员。 */
|
|
35
|
-
ignoreAtAll: boolean
|
|
36
|
-
/** 回复机器人自己的消息是否必回。 */
|
|
37
|
-
replyToSelf: boolean
|
|
38
|
-
/** 群里第一个 @ 指向别人时是否不唤醒机器人。 */
|
|
39
|
-
ignoreAtOthers: boolean
|
|
40
|
-
}
|
|
30
|
+
/** 全局唤醒策略:与配置项 `wake` 同构。 */
|
|
31
|
+
export type WakePolicy = WakeConfig
|
|
41
32
|
|
|
42
|
-
/**
|
|
33
|
+
/** 内置的全局唤醒策略,取自配置默认值。 */
|
|
43
34
|
export const DEFAULT_WAKE_POLICY: WakePolicy = {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
replyToSelf: true,
|
|
47
|
-
ignoreAtOthers: true,
|
|
35
|
+
...DEFAULT_CONFIG.wake,
|
|
36
|
+
prefixes: [...DEFAULT_CONFIG.wake.prefixes],
|
|
48
37
|
}
|
|
49
38
|
|
|
50
39
|
/** 唤醒判定的结果。 */
|
package/src/rate-limit.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Mutex } from "async-mutex"
|
|
2
|
+
import { delay } from "./async"
|
|
2
3
|
import { type ChatTarget, targetKey } from "./chat"
|
|
3
4
|
import type { RateLimitConfig } from "./config"
|
|
4
5
|
|
|
@@ -77,7 +78,7 @@ export class SendRateLimiter {
|
|
|
77
78
|
}
|
|
78
79
|
|
|
79
80
|
private get wait(): (ms: number) => Promise<void> {
|
|
80
|
-
return this.options.sleep ??
|
|
81
|
+
return this.options.sleep ?? delay
|
|
81
82
|
}
|
|
82
83
|
|
|
83
84
|
private lock(scope: string): Mutex {
|
package/src/safe-fetch.ts
CHANGED
|
@@ -2,6 +2,7 @@ import http from "node:http"
|
|
|
2
2
|
import https from "node:https"
|
|
3
3
|
import { useAgent } from "request-filtering-agent"
|
|
4
4
|
import type { Logger } from "./logger"
|
|
5
|
+
import { truncateForLog } from "./text"
|
|
5
6
|
|
|
6
7
|
/** 允许的出站端口:只放行常见的网页端口,其余一律拒绝。 */
|
|
7
8
|
export const ALLOWED_PORTS: readonly number[] = [80, 443, 8080, 8443]
|
|
@@ -36,11 +37,6 @@ export type SafeFetcher = (
|
|
|
36
37
|
options: SafeFetchOptions,
|
|
37
38
|
) => Promise<SafeFetchResult | undefined>
|
|
38
39
|
|
|
39
|
-
/** 截断过长的地址,避免日志被超长 URL 淹没。 */
|
|
40
|
-
function truncateForLog(value: string, max = 120): string {
|
|
41
|
-
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
42
|
-
}
|
|
43
|
-
|
|
44
40
|
/**
|
|
45
41
|
* 下载一个远端文件,挡住指向内网的请求。
|
|
46
42
|
*
|