@cmach_socket/opencode-qq-bot 1.0.1 → 2.0.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/README.md +15 -319
- package/chat-overrides.example.json +13 -3
- package/package.json +4 -1
- package/src/commands.ts +7 -7
- package/src/config/fields.ts +3 -27
- package/src/config/live.ts +2 -2
- package/src/config/store.ts +9 -0
- package/src/config/types.ts +2 -8
- package/src/config.ts +5 -12
- package/src/diary/command.ts +10 -8
- package/src/diary/scheduler.ts +11 -11
- package/src/diary/scope.ts +14 -23
- package/src/diary/summary.ts +91 -57
- package/src/fs/atomic.ts +17 -5
- package/src/home.ts +7 -7
- package/src/index.ts +57 -41
- package/src/media-path.ts +2 -12
- package/src/naplink/client.ts +50 -1
- package/src/naplink/history.ts +9 -2
- package/src/naplink/media.ts +3 -5
- package/src/naplink/render.ts +10 -3
- package/src/overrides.ts +43 -36
- package/src/panel/documents.ts +32 -44
- package/src/panel/status.ts +7 -1
- package/src/session/find.ts +2 -3
- package/src/session/manager.ts +27 -40
- package/src/tools/policy-guard.ts +9 -5
- package/src/tools/policy.ts +59 -37
- package/src/tools/qq.ts +132 -41
- package/src/user/inject.ts +66 -0
- package/src/user/store.ts +93 -0
- package/src/workspace.ts +113 -0
- package/tool-profiles.example.json +0 -4
- package/web/dist/assets/{index-B-3ZGYMq.js → index-Be9cCNMT.js} +2 -2
- package/web/dist/index.html +1 -1
package/src/index.ts
CHANGED
|
@@ -4,22 +4,22 @@ import type { GroupMessageEvent, MessageEvent, NoticeEvent } from "@naplink/napl
|
|
|
4
4
|
import { Mutex } from "async-mutex"
|
|
5
5
|
import { delay, unrefTimer } from "./async"
|
|
6
6
|
import { acquireBotLock, type BotLock, botLockPath } from "./bot-lock"
|
|
7
|
-
import { type ChatTarget, targetKey, targetLabel } from "./chat"
|
|
8
|
-
import {
|
|
7
|
+
import { type ChatTarget, parseTargetKey, targetKey, targetLabel } from "./chat"
|
|
8
|
+
import { isTargetAllowed } from "./access"
|
|
9
9
|
import type { QQBotConfig } from "./config"
|
|
10
10
|
import { ConfigController } from "./config/live"
|
|
11
|
-
import { ConfigStore,
|
|
11
|
+
import { ConfigStore, defaultConfigPath } from "./config/store"
|
|
12
12
|
import { DiaryCollector, isSelfSpeaker } from "./diary/collector"
|
|
13
13
|
import { createDiaryRunner, diaryCommand } from "./diary/command"
|
|
14
14
|
import { DiaryScheduler } from "./diary/scheduler"
|
|
15
|
-
import {
|
|
15
|
+
import { diaryEnabled } from "./diary/scope"
|
|
16
16
|
import { DiaryStore } from "./diary/store"
|
|
17
17
|
import { DiarySummarizer } from "./diary/summary"
|
|
18
18
|
import { resolveHome } from "./home"
|
|
19
19
|
import { claimInstance, takeHandover } from "./instance"
|
|
20
20
|
import { KeepAlive } from "./keepalive"
|
|
21
21
|
import { createLogger, closeLogger, defaultLogDir, flushLogger, setLogLevel } from "./logger"
|
|
22
|
-
import {
|
|
22
|
+
import { OutboundMedia } from "./media-path"
|
|
23
23
|
import { formatModelMessage } from "./model-view"
|
|
24
24
|
import { QQClient } from "./naplink/client"
|
|
25
25
|
import { createHistoryProvider } from "./naplink/history"
|
|
@@ -52,6 +52,7 @@ import {
|
|
|
52
52
|
ChatOverrides,
|
|
53
53
|
ignoredByPrefix,
|
|
54
54
|
proactiveAllowed,
|
|
55
|
+
proactiveScopeChats,
|
|
55
56
|
resolveChatOverridesPath,
|
|
56
57
|
wakeDecision,
|
|
57
58
|
type WakeReason,
|
|
@@ -78,6 +79,9 @@ import { FavoriteStore } from "./emoji/favorites"
|
|
|
78
79
|
import { FavoriteIndex } from "./emoji/favorite-index"
|
|
79
80
|
import { CollectionStore, RecentImages } from "./emoji/collection"
|
|
80
81
|
import { EmojiLabeler } from "./emoji/label"
|
|
82
|
+
import { UserInjector } from "./user/inject"
|
|
83
|
+
import { UserStore } from "./user/store"
|
|
84
|
+
import { ChatWorkspaces } from "./workspace"
|
|
81
85
|
|
|
82
86
|
const RETRY_DELAY_MS = 1000
|
|
83
87
|
/** 机器人连接被别的实例占用时,多久重试一次接管。 */
|
|
@@ -158,7 +162,7 @@ interface PluginCarry {
|
|
|
158
162
|
/**
|
|
159
163
|
* 跑一遍插件初始化。
|
|
160
164
|
*
|
|
161
|
-
* 面板触发重启时这一份会再跑一次:上一代先完整卸载,再从 `config.json`
|
|
165
|
+
* 面板触发重启时这一份会再跑一次:上一代先完整卸载,再从 `config/config.json`
|
|
162
166
|
* 重新读取配置。`carry` 用来把面板会话与在途状态带到新一代,
|
|
163
167
|
* 令牌没变的话已登录的浏览器不用重新登录。
|
|
164
168
|
*/
|
|
@@ -180,7 +184,7 @@ const initializer = {
|
|
|
180
184
|
}
|
|
181
185
|
// 工作目录固定:配置文件就在工作目录里,位置固定才不会自举。
|
|
182
186
|
const home = await resolveHome(bootstrap)
|
|
183
|
-
const store = new ConfigStore(
|
|
187
|
+
const store = new ConfigStore(defaultConfigPath(home.directory))
|
|
184
188
|
const agent = agentFromOptions(ctx.options)
|
|
185
189
|
const controller = new ConfigController({
|
|
186
190
|
store,
|
|
@@ -216,7 +220,9 @@ const initializer = {
|
|
|
216
220
|
config.access.allow.users.length === 0 &&
|
|
217
221
|
!config.access.allowAllWhenEmpty
|
|
218
222
|
) {
|
|
219
|
-
logger.warn(
|
|
223
|
+
logger.warn(
|
|
224
|
+
"未配置放行目标,插件不会响应任何消息(请在 config/config.json 里配置 access.allow)",
|
|
225
|
+
)
|
|
220
226
|
}
|
|
221
227
|
|
|
222
228
|
// 状态面板:默认开启,自带 HTTP 服务,只监听本机。
|
|
@@ -413,17 +419,18 @@ const initializer = {
|
|
|
413
419
|
const client = new QQClient(config.napcat, logger)
|
|
414
420
|
cleanup.add("断开 NapCat", () => client.dispose(), CleanupOrder.napcat)
|
|
415
421
|
panelRuntime.client = client
|
|
416
|
-
|
|
417
|
-
const
|
|
418
|
-
|
|
422
|
+
// 每个聊天各自的工作目录:会话与入站媒体都按聊天隔离,出站白名单也按角色收窄。
|
|
423
|
+
const workspaces = new ChatWorkspaces(home.directory, logger, config.media.allowedDirs)
|
|
424
|
+
await workspaces.cleanup()
|
|
425
|
+
// 用户档案(USER.md,用户自己写)与用户画像(模型自己维护):都按聊天隔离。
|
|
426
|
+
const users = new UserStore(home.directory, logger)
|
|
427
|
+
const userInjector = new UserInjector(users)
|
|
428
|
+
// 机器人共用媒体目录:收藏表情这类不属于任何聊天的文件。
|
|
429
|
+
const media = await createMediaStore(logger, { root: workspaces.sharedMediaDir })
|
|
430
|
+
// 插件自己发的文件(日记等)不经过模型,按工作目录整体放行。
|
|
419
431
|
const outbound = new OutboundMedia({
|
|
420
432
|
workspace: home.directory,
|
|
421
|
-
allowedDirs: [home.directory,
|
|
422
|
-
})
|
|
423
|
-
// 普通群成员与主动说话只允许媒体目录:模型能调 send_image 不等于能读整台机器。
|
|
424
|
-
const outboundMember = new OutboundMedia({
|
|
425
|
-
workspace: home.directory,
|
|
426
|
-
allowedDirs: [mediaDir],
|
|
433
|
+
allowedDirs: [home.directory, ...config.media.allowedDirs],
|
|
427
434
|
})
|
|
428
435
|
const nameCache = new Map<string, { name: string; expires: number }>()
|
|
429
436
|
/** 渲染上下文:上游 API、媒体存储与昵称缓存都在这里一次性绑定。 */
|
|
@@ -431,14 +438,14 @@ const initializer = {
|
|
|
431
438
|
api: client.api,
|
|
432
439
|
target,
|
|
433
440
|
logger,
|
|
434
|
-
media,
|
|
441
|
+
media: workspaces.mediaFor(target),
|
|
435
442
|
names: nameCache,
|
|
436
443
|
...(selfId ? { selfId } : {}),
|
|
437
444
|
})
|
|
438
445
|
const history = createHistoryProvider({
|
|
439
446
|
api: client.api,
|
|
440
447
|
logger,
|
|
441
|
-
|
|
448
|
+
mediaFor: (target) => workspaces.mediaFor(target),
|
|
442
449
|
names: nameCache,
|
|
443
450
|
timeZone: config.timezone,
|
|
444
451
|
roleOf: (userId) => roleOf(config, userId),
|
|
@@ -534,6 +541,7 @@ const initializer = {
|
|
|
534
541
|
const mediaCleanup = setInterval(
|
|
535
542
|
() => {
|
|
536
543
|
void media.cleanup()
|
|
544
|
+
void workspaces.cleanup()
|
|
537
545
|
},
|
|
538
546
|
60 * 60 * 1000,
|
|
539
547
|
)
|
|
@@ -546,7 +554,7 @@ const initializer = {
|
|
|
546
554
|
)
|
|
547
555
|
const favoriteIndex = new FavoriteIndex(ctx.storage, logger)
|
|
548
556
|
// 本机收集的表情:QQ 收藏表情写不进 NapCat,收集的动图自己存在媒体目录里。
|
|
549
|
-
const collection = new CollectionStore(ctx.storage,
|
|
557
|
+
const collection = new CollectionStore(ctx.storage, workspaces.sharedMediaDir, logger)
|
|
550
558
|
// 各聊天最近收到的图片:收藏表情时从中挑素材。
|
|
551
559
|
const recentImages = new RecentImages()
|
|
552
560
|
const labeler = new EmojiLabeler({ ctx, config, home, logger, media, favorites })
|
|
@@ -583,6 +591,7 @@ const initializer = {
|
|
|
583
591
|
store: diaryStore,
|
|
584
592
|
collector: diaryCollector,
|
|
585
593
|
summarizer: diarySummarizer,
|
|
594
|
+
overrides,
|
|
586
595
|
})
|
|
587
596
|
cleanup.add("停止日记调度", () => diaryScheduler.dispose(), CleanupOrder.events)
|
|
588
597
|
panelRuntime.diary = diaryScheduler
|
|
@@ -605,10 +614,10 @@ const initializer = {
|
|
|
605
614
|
recentImages,
|
|
606
615
|
limiter,
|
|
607
616
|
sensitive,
|
|
608
|
-
|
|
609
|
-
outboundMember,
|
|
610
|
-
media,
|
|
617
|
+
workspaces,
|
|
611
618
|
diary: diaryStore,
|
|
619
|
+
users,
|
|
620
|
+
overrides,
|
|
612
621
|
tracer,
|
|
613
622
|
// 没有机器级锁的实例不能发送:那是别的实例的机器人。
|
|
614
623
|
canSend: () => botLock !== undefined,
|
|
@@ -668,7 +677,13 @@ const initializer = {
|
|
|
668
677
|
// 禁止连续调用发送工具,避免同一条消息被重复发送。
|
|
669
678
|
const sendGuardRegistration = await registerSendGuard({ ctx, logger, manager })
|
|
670
679
|
// 按聊天与角色收窄工具:上下文里先删,执行前再挡一次。
|
|
671
|
-
const toolPolicyRegistration = await registerToolPolicy({
|
|
680
|
+
const toolPolicyRegistration = await registerToolPolicy({
|
|
681
|
+
ctx,
|
|
682
|
+
logger,
|
|
683
|
+
manager,
|
|
684
|
+
policy,
|
|
685
|
+
overrides,
|
|
686
|
+
})
|
|
672
687
|
cleanup.add(
|
|
673
688
|
"注销工具守卫",
|
|
674
689
|
async () => {
|
|
@@ -692,9 +707,10 @@ const initializer = {
|
|
|
692
707
|
// 日记生成会话的输入是群友可控的聊天记录,同样不带任何工具;
|
|
693
708
|
// 但它仍是一轮正常对话,先注入角色设定,日记才有人格。
|
|
694
709
|
if (await diarySummarizer.isSummarySession(event.sessionID)) {
|
|
695
|
-
//
|
|
696
|
-
const
|
|
697
|
-
const
|
|
710
|
+
// 人格取这个生成会话所属聊天上的覆盖,没有覆盖就用默认档。
|
|
711
|
+
const chat = await diarySummarizer.chatForSession(event.sessionID)
|
|
712
|
+
const scopeTarget = chat ? parseTargetKey(chat) : undefined
|
|
713
|
+
const override = scopeTarget ? await overrides.for(scopeTarget) : undefined
|
|
698
714
|
const soul = await souls.at(override?.soulPath, override?.soulName)
|
|
699
715
|
// 只注入角色设定正文:`soul.prompt` 还带着「必须调用 qq_send_message」
|
|
700
716
|
// 的 QQ 守则,而生成会话没有任何工具,带上会让模型无所适从。
|
|
@@ -712,6 +728,11 @@ const initializer = {
|
|
|
712
728
|
type: "text",
|
|
713
729
|
text: `当前时间:${currentTimeText(config.timezone)}`,
|
|
714
730
|
})
|
|
731
|
+
// 用户档案与画像:每个会话只在开头注入一次,之后模型自己按需用工具取。
|
|
732
|
+
const userContext = await userInjector.injectOnce(event.sessionID, target)
|
|
733
|
+
if (userContext) {
|
|
734
|
+
event.system.push({ type: "text", text: userContext })
|
|
735
|
+
}
|
|
715
736
|
const active = manager.activeTurn(event.sessionID)
|
|
716
737
|
const turn = active?.turn
|
|
717
738
|
const role = active?.role ?? manager.currentRole(event.sessionID)
|
|
@@ -762,7 +783,7 @@ const initializer = {
|
|
|
762
783
|
// 本轮发送者的角色决定工具档:owner / admin 全开,其他按聊天配置。
|
|
763
784
|
// 角色按会话保留,没有在途轮次(重启、TUI 驱动)时也照样收窄。
|
|
764
785
|
{
|
|
765
|
-
const allowed = await policy.allow(role,
|
|
786
|
+
const allowed = await policy.allow(role, override.profile, Object.keys(event.tools))
|
|
766
787
|
const removed: string[] = []
|
|
767
788
|
for (const name of Object.keys(event.tools)) {
|
|
768
789
|
// 申请回复权限的工具必须一直留着:不然模型永远拿不到发送权限。
|
|
@@ -772,7 +793,7 @@ const initializer = {
|
|
|
772
793
|
delete event.tools[name]
|
|
773
794
|
}
|
|
774
795
|
}
|
|
775
|
-
const profile = await policy.profileOf(role,
|
|
796
|
+
const profile = await policy.profileOf(role, override.profile)
|
|
776
797
|
// 模型这一轮实际能用的 QQ 工具:模型只认这些名字,缺一个就发不出消息。
|
|
777
798
|
const qqTools = Object.keys(event.tools).filter((name) =>
|
|
778
799
|
name.startsWith(`${TOOL_NAMESPACE}_`),
|
|
@@ -967,12 +988,12 @@ const initializer = {
|
|
|
967
988
|
selfId: string,
|
|
968
989
|
): void => {
|
|
969
990
|
if (!config.diary.enabled) return
|
|
970
|
-
// 日记只记 owner 自己的私聊,群聊与别人的私聊都不进素材。
|
|
971
|
-
if (!isDiaryScopeChat(config, target)) return
|
|
972
991
|
const content = extractDiaryText(event.message)
|
|
973
992
|
if (!content) return
|
|
974
993
|
const userId = String(event.user_id)
|
|
975
994
|
void (async () => {
|
|
995
|
+
// 只有会话覆盖里开了日记的聊天才采集素材。
|
|
996
|
+
if (!diaryEnabled(await overrides.for(target))) return
|
|
976
997
|
let name = ""
|
|
977
998
|
try {
|
|
978
999
|
name = await resolveUserName(renderContext(target, selfId), userId)
|
|
@@ -1082,19 +1103,14 @@ const initializer = {
|
|
|
1082
1103
|
const tick = async () => {
|
|
1083
1104
|
if (tickMutex.isLocked()) return
|
|
1084
1105
|
await tickMutex.runExclusive(async () => {
|
|
1085
|
-
for (const target of
|
|
1106
|
+
for (const target of proactiveScopeChats(await overrides.current())) {
|
|
1086
1107
|
// 没有机器人连接就发不出去,不主动发起话题。
|
|
1087
1108
|
if (!botLock) continue
|
|
1109
|
+
// 不在准入名单里的聊天不主动说话。
|
|
1110
|
+
if (!isTargetAllowed(config.access, target, config.ownerQQ)) continue
|
|
1088
1111
|
const override = await overrides.for(target)
|
|
1089
|
-
//
|
|
1090
|
-
if (
|
|
1091
|
-
!proactiveAllowed(override, target, {
|
|
1092
|
-
allowGroups: config.proactive.allowGroups,
|
|
1093
|
-
allowUsers: config.proactive.allowUsers,
|
|
1094
|
-
})
|
|
1095
|
-
) {
|
|
1096
|
-
continue
|
|
1097
|
-
}
|
|
1112
|
+
// 被覆盖成不主动说话的聊天跳过。
|
|
1113
|
+
if (!proactiveAllowed(override, target)) continue
|
|
1098
1114
|
// 聊天自己写了概率就用它,否则按全局公式随沉默时长增长。
|
|
1099
1115
|
const probability = proactiveProbability(
|
|
1100
1116
|
override,
|
package/src/media-path.ts
CHANGED
|
@@ -1,20 +1,10 @@
|
|
|
1
1
|
import { lookup } from "node:dns/promises"
|
|
2
2
|
import { realpath, stat } from "node:fs/promises"
|
|
3
|
-
import { isAbsolute,
|
|
3
|
+
import { isAbsolute, resolve, sep } from "node:path"
|
|
4
4
|
import ipaddr from "ipaddr.js"
|
|
5
|
-
import {
|
|
5
|
+
import { expandTilde } from "./home"
|
|
6
6
|
import { ALLOWED_PORTS } from "./safe-fetch"
|
|
7
7
|
|
|
8
|
-
/**
|
|
9
|
-
* 媒体目录:机器人工作目录下的 `media`。
|
|
10
|
-
*
|
|
11
|
-
* 工作目录由 {@link defaultHome} 固定,媒体和会话在同一棵目录树里,
|
|
12
|
-
* 模型读到的相对路径与出站白名单的口径一致。
|
|
13
|
-
*/
|
|
14
|
-
export function defaultMediaDir(): string {
|
|
15
|
-
return join(defaultHome(), "media")
|
|
16
|
-
}
|
|
17
|
-
|
|
18
8
|
/** 出站媒体的路径策略。 */
|
|
19
9
|
export interface MediaPolicy {
|
|
20
10
|
/** 机器人工作目录:相对路径按它解析。 */
|
package/src/naplink/client.ts
CHANGED
|
@@ -25,6 +25,14 @@ interface MediaFileLike {
|
|
|
25
25
|
url?: unknown
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
/** 补全直链时的上下文:文件链接要带上会话对端,普通 `get_file` 拿不到。 */
|
|
29
|
+
export interface HydrateOptions {
|
|
30
|
+
/** 私聊对端 QQ 号。 */
|
|
31
|
+
privateUserId?: number | string
|
|
32
|
+
/** 群号。 */
|
|
33
|
+
groupId?: number | string
|
|
34
|
+
}
|
|
35
|
+
|
|
28
36
|
function isMediaSegmentType(type: string): type is MediaSegmentType {
|
|
29
37
|
return (MEDIA_SEGMENT_TYPES as readonly string[]).includes(type)
|
|
30
38
|
}
|
|
@@ -58,6 +66,7 @@ export async function hydrateSegment(
|
|
|
58
66
|
api: OneBotApi,
|
|
59
67
|
segment: MessageSegment,
|
|
60
68
|
logger: Logger,
|
|
69
|
+
options: HydrateOptions = {},
|
|
61
70
|
): Promise<void> {
|
|
62
71
|
if (!isMediaSegmentType(segment.type)) return
|
|
63
72
|
const data = segment.data as MediaSegmentData
|
|
@@ -68,11 +77,51 @@ export async function hydrateSegment(
|
|
|
68
77
|
if (typeof fileId !== "string" || fileId.length === 0) return
|
|
69
78
|
if (/^(file|base64|data):/i.test(fileId)) return
|
|
70
79
|
|
|
80
|
+
// 直链接口失败后走了通用接口:结果可能还能用,但要在日志里留痕。
|
|
81
|
+
let degraded = false
|
|
71
82
|
try {
|
|
83
|
+
// 文件的直链要拿会话对端与 file_id 去换,普通 get_file 拿不到。
|
|
84
|
+
if (segment.type === "file" && options.privateUserId) {
|
|
85
|
+
try {
|
|
86
|
+
const shared = (await api.raw.get_private_file_url({
|
|
87
|
+
user_id: options.privateUserId,
|
|
88
|
+
file_id: fileId,
|
|
89
|
+
})) as (MediaFileLike & { data?: MediaFileLike }) | undefined
|
|
90
|
+
const sharedUrl = pickRemoteUrl(shared?.url, shared?.file, shared?.data?.url)
|
|
91
|
+
if (sharedUrl) {
|
|
92
|
+
data.url = sharedUrl
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
} catch (error) {
|
|
96
|
+
degraded = true
|
|
97
|
+
logger.warn(
|
|
98
|
+
`换私聊文件链接失败,改用通用接口 user=${options.privateUserId} file=${fileId}`,
|
|
99
|
+
error,
|
|
100
|
+
)
|
|
101
|
+
}
|
|
102
|
+
} else if (segment.type === "file" && options.groupId) {
|
|
103
|
+
try {
|
|
104
|
+
const busid = (data as { busid?: unknown }).busid
|
|
105
|
+
const shared = (await api.getGroupFileUrl(
|
|
106
|
+
options.groupId,
|
|
107
|
+
fileId,
|
|
108
|
+
typeof busid === "number" ? busid : undefined,
|
|
109
|
+
)) as (MediaFileLike & { data?: MediaFileLike }) | undefined
|
|
110
|
+
const sharedUrl = pickRemoteUrl(shared?.url, shared?.file, shared?.data?.url)
|
|
111
|
+
if (sharedUrl) {
|
|
112
|
+
data.url = sharedUrl
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
} catch (error) {
|
|
116
|
+
degraded = true
|
|
117
|
+
logger.warn(`换群文件链接失败,改用通用接口 group=${options.groupId} file=${fileId}`, error)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
72
120
|
const file = (await api.getFile(fileId)) as MediaFileLike | undefined
|
|
73
121
|
const direct = pickRemoteUrl(file?.url, file?.file)
|
|
74
122
|
if (direct) {
|
|
75
123
|
data.url = direct
|
|
124
|
+
if (degraded) logger.warn(`文件直链已降级到通用接口 file=${fileId}`)
|
|
76
125
|
return
|
|
77
126
|
}
|
|
78
127
|
if (segment.type === "image") {
|
|
@@ -85,7 +134,7 @@ export async function hydrateSegment(
|
|
|
85
134
|
if (recordUrl) data.url = recordUrl
|
|
86
135
|
}
|
|
87
136
|
} catch (error) {
|
|
88
|
-
logger.
|
|
137
|
+
logger.warn(`补全媒体直链失败 type=${segment.type} file=${fileId}`, error)
|
|
89
138
|
}
|
|
90
139
|
}
|
|
91
140
|
|
package/src/naplink/history.ts
CHANGED
|
@@ -59,7 +59,8 @@ const MAX_HISTORY_PAGES = 10
|
|
|
59
59
|
export function createHistoryProvider(deps: {
|
|
60
60
|
api: OneBotApi
|
|
61
61
|
logger: Logger
|
|
62
|
-
|
|
62
|
+
/** 按聊天取媒体存储:每个聊天各自一个媒体目录。 */
|
|
63
|
+
mediaFor: (target: ChatTarget) => MediaStore
|
|
63
64
|
names?: Map<string, { name: string; expires: number }>
|
|
64
65
|
/** 时间标注使用的 IANA 时区;留空用默认时区。 */
|
|
65
66
|
timeZone?: string
|
|
@@ -71,7 +72,13 @@ export function createHistoryProvider(deps: {
|
|
|
71
72
|
const count = Math.max(0, Math.floor(options.count))
|
|
72
73
|
if (count === 0) return { text: "", files: [] }
|
|
73
74
|
|
|
74
|
-
const ctx: RenderContext = {
|
|
75
|
+
const ctx: RenderContext = {
|
|
76
|
+
api: deps.api,
|
|
77
|
+
logger: deps.logger,
|
|
78
|
+
target,
|
|
79
|
+
media: deps.mediaFor(target),
|
|
80
|
+
...(deps.names ? { names: deps.names } : {}),
|
|
81
|
+
}
|
|
75
82
|
const entries = options.since
|
|
76
83
|
? await fetchGap(ctx, options.since, count, options.exclude)
|
|
77
84
|
: await fetchLatest(ctx, count, options.exclude)
|
package/src/naplink/media.ts
CHANGED
|
@@ -3,7 +3,6 @@ import { access, mkdir, readdir, stat, unlink, writeFile } from "node:fs/promise
|
|
|
3
3
|
import { join } from "node:path"
|
|
4
4
|
import { pathToFileURL } from "node:url"
|
|
5
5
|
import type { Logger } from "../logger"
|
|
6
|
-
import { defaultMediaDir } from "../media-path"
|
|
7
6
|
import { type SafeFetcher, safeFetchBytes } from "../safe-fetch"
|
|
8
7
|
import { truncateForLog } from "../text"
|
|
9
8
|
|
|
@@ -366,13 +365,12 @@ export class MediaStore {
|
|
|
366
365
|
}
|
|
367
366
|
}
|
|
368
367
|
|
|
369
|
-
/**
|
|
368
|
+
/** 创建媒体存储,并立即清理一次过期文件。 */
|
|
370
369
|
export async function createMediaStore(
|
|
371
370
|
logger: Logger,
|
|
372
|
-
options: { root
|
|
371
|
+
options: { root: string; ttlMs?: number; fetcher?: SafeFetcher },
|
|
373
372
|
): Promise<MediaStore> {
|
|
374
|
-
const
|
|
375
|
-
const store = new MediaStore(root, logger, options.ttlMs, options.fetcher)
|
|
373
|
+
const store = new MediaStore(options.root, logger, options.ttlMs, options.fetcher)
|
|
376
374
|
await store.cleanup()
|
|
377
375
|
return store
|
|
378
376
|
}
|
package/src/naplink/render.ts
CHANGED
|
@@ -363,6 +363,13 @@ function describeSegment(segment: Segment): string | undefined {
|
|
|
363
363
|
}
|
|
364
364
|
}
|
|
365
365
|
|
|
366
|
+
/** 补全直链时的上下文:按会话类型带上对端号码。 */
|
|
367
|
+
function hydrateOptions(ctx: RenderContext): { privateUserId?: number; groupId?: number } {
|
|
368
|
+
return ctx.target.kind === "private"
|
|
369
|
+
? { privateUserId: ctx.target.id }
|
|
370
|
+
: { groupId: ctx.target.id }
|
|
371
|
+
}
|
|
372
|
+
|
|
366
373
|
/**
|
|
367
374
|
* 渲染一条文件消息:文本内联进提示词,其余作为附件交出。
|
|
368
375
|
*
|
|
@@ -377,7 +384,7 @@ async function renderDocument(
|
|
|
377
384
|
const data = segment.data as { file?: string; name?: string; url?: string }
|
|
378
385
|
const name = safeDocumentName(data.name || data.file || "文件")
|
|
379
386
|
const label = `[文件]${sanitizeUntrustedText(name)}`
|
|
380
|
-
await hydrateSegment(ctx.api, segment, ctx.logger)
|
|
387
|
+
await hydrateSegment(ctx.api, segment, ctx.logger, hydrateOptions(ctx))
|
|
381
388
|
const url = data.url || data.file
|
|
382
389
|
// `file` 字段常常只是文件名或 NapCat 本地路径,拿不到直链时只留占位文本。
|
|
383
390
|
if (!url || !/^(https?:|data:|base64:\/\/)/i.test(url)) return { text: label }
|
|
@@ -447,7 +454,7 @@ async function renderForwardSegments(
|
|
|
447
454
|
parts.push(imagePlaceholder(segment))
|
|
448
455
|
// 额度在下载前扣掉:额度用尽就不再下载。
|
|
449
456
|
if (!reserveImage(budget)) break
|
|
450
|
-
await hydrateSegment(ctx.api, segment, ctx.logger)
|
|
457
|
+
await hydrateSegment(ctx.api, segment, ctx.logger, hydrateOptions(ctx))
|
|
451
458
|
const url = segment.data.url || segment.data.file
|
|
452
459
|
if (!url) break
|
|
453
460
|
const stored = await ctx.media.storeImage(url)
|
|
@@ -670,7 +677,7 @@ export async function renderMessage(
|
|
|
670
677
|
textBuffer.push(`${imagePlaceholder(segment)} `)
|
|
671
678
|
// 额度在下载前扣掉:额度用尽就不再下载。
|
|
672
679
|
if (!reserveImage(budget)) break
|
|
673
|
-
await hydrateSegment(ctx.api, segment, ctx.logger)
|
|
680
|
+
await hydrateSegment(ctx.api, segment, ctx.logger, hydrateOptions(ctx))
|
|
674
681
|
const url = segment.data.url || segment.data.file
|
|
675
682
|
if (!url) break
|
|
676
683
|
const stored = await ctx.media.storeImage(url)
|
package/src/overrides.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFile, stat } from "node:fs/promises"
|
|
2
2
|
import { join, resolve } from "node:path"
|
|
3
|
-
import { type ChatTarget, targetKey } from "./chat"
|
|
3
|
+
import { type ChatTarget, parseTargetKey, targetKey } from "./chat"
|
|
4
4
|
import {
|
|
5
5
|
DEFAULT_CONFIG,
|
|
6
6
|
parseModelRef,
|
|
@@ -63,18 +63,10 @@ export interface WakeDecision {
|
|
|
63
63
|
ignored?: boolean
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
/** 主动说话的白名单。 */
|
|
67
|
-
export interface ProactiveScope {
|
|
68
|
-
/** 只在这些群里主动说话;为空表示一个都不放行。 */
|
|
69
|
-
allowGroups: number[]
|
|
70
|
-
/** 只在这些私聊里主动说话;为空表示一个都不放行。 */
|
|
71
|
-
allowUsers: number[]
|
|
72
|
-
}
|
|
73
|
-
|
|
74
66
|
/**
|
|
75
67
|
* 单个聊天的行为覆盖。
|
|
76
68
|
*
|
|
77
|
-
* 键名与全局配置项一致:会话能改哪一项,就用那一项在 `config.json` 里的名字。
|
|
69
|
+
* 键名与全局配置项一致:会话能改哪一项,就用那一项在 `config/config.json` 里的名字。
|
|
78
70
|
*/
|
|
79
71
|
export interface ChatOverride {
|
|
80
72
|
/** 唤醒方式,缺省按被 @ 才必回;全局没有对应项,只在会话层出现。 */
|
|
@@ -83,10 +75,12 @@ export interface ChatOverride {
|
|
|
83
75
|
"wake.prefixes"?: string[]
|
|
84
76
|
/** 忽略前缀,命中即整条不理;与全局 `wake.ignorePrefixes` 同名同形。 */
|
|
85
77
|
"wake.ignorePrefixes"?: string[]
|
|
86
|
-
/** 是否允许主动说话,对应全局 `proactive.enabled
|
|
78
|
+
/** 是否允许主动说话,对应全局 `proactive.enabled`;不写表示不参与。 */
|
|
87
79
|
"proactive.enabled"?: boolean
|
|
88
80
|
/** 这个聊天单次心跳的触发概率,对应全局 `proactive.startProbability`。 */
|
|
89
81
|
"proactive.startProbability"?: number
|
|
82
|
+
/** 是否给这个聊天生成日记;不写表示不生成。 */
|
|
83
|
+
"diary.enabled"?: boolean
|
|
90
84
|
/** 私聊的消息收集窗口(毫秒),对应全局 `collect.privateMs`。 */
|
|
91
85
|
"collect.privateMs"?: number
|
|
92
86
|
/** 群聊的消息收集窗口(毫秒),对应全局 `collect.groupMs`。 */
|
|
@@ -99,9 +93,11 @@ export interface ChatOverride {
|
|
|
99
93
|
soulPath?: string
|
|
100
94
|
/** 覆盖该聊天使用的角色设定文件名,对应全局 `soulName`。 */
|
|
101
95
|
soulName?: string
|
|
96
|
+
/** 覆盖该聊天使用的工具配置档名,取自 `config/tool-profiles.json` 的配置档。 */
|
|
97
|
+
profile?: string
|
|
102
98
|
}
|
|
103
99
|
|
|
104
|
-
/** `chat-overrides.json` 的结构。 */
|
|
100
|
+
/** `config/chat-overrides.json` 的结构。 */
|
|
105
101
|
export interface ChatOverridesFile {
|
|
106
102
|
/** 按聊天指定的行为覆盖:`group:100` / `private:200`。 */
|
|
107
103
|
chats: Record<string, ChatOverride>
|
|
@@ -112,9 +108,9 @@ export function defaultChatOverrides(): ChatOverridesFile {
|
|
|
112
108
|
return { chats: {} }
|
|
113
109
|
}
|
|
114
110
|
|
|
115
|
-
/**
|
|
111
|
+
/** 默认的配置文件位置:工作目录 `config/` 下的 `chat-overrides.json`。 */
|
|
116
112
|
export function defaultChatOverridesPath(home: string): string {
|
|
117
|
-
return join(home, "chat-overrides.json")
|
|
113
|
+
return join(home, "config", "chat-overrides.json")
|
|
118
114
|
}
|
|
119
115
|
|
|
120
116
|
/**
|
|
@@ -256,6 +252,13 @@ export function parseChatOverrides(
|
|
|
256
252
|
warn(`会话覆盖 ${key} 的 proactive.enabled 必须是布尔值,已忽略`)
|
|
257
253
|
}
|
|
258
254
|
}
|
|
255
|
+
if (record["diary.enabled"] !== undefined) {
|
|
256
|
+
if (typeof record["diary.enabled"] === "boolean") {
|
|
257
|
+
override["diary.enabled"] = record["diary.enabled"]
|
|
258
|
+
} else {
|
|
259
|
+
warn(`会话覆盖 ${key} 的 diary.enabled 必须是布尔值,已忽略`)
|
|
260
|
+
}
|
|
261
|
+
}
|
|
259
262
|
if (record["proactive.startProbability"] !== undefined) {
|
|
260
263
|
const raw = record["proactive.startProbability"]
|
|
261
264
|
const value =
|
|
@@ -302,6 +305,14 @@ export function parseChatOverrides(
|
|
|
302
305
|
override.soulName = value
|
|
303
306
|
}
|
|
304
307
|
}
|
|
308
|
+
if (record.profile !== undefined) {
|
|
309
|
+
const value = typeof record.profile === "string" ? record.profile.trim() : ""
|
|
310
|
+
if (!value) {
|
|
311
|
+
warn(`会话覆盖 ${key} 的 profile 必须是非空字符串,已忽略`)
|
|
312
|
+
} else {
|
|
313
|
+
override.profile = value
|
|
314
|
+
}
|
|
315
|
+
}
|
|
305
316
|
if (record["collect.privateMs"] !== undefined) {
|
|
306
317
|
const value = parseCollectMs(record["collect.privateMs"])
|
|
307
318
|
if (value === undefined) {
|
|
@@ -447,22 +458,22 @@ export function wakeDecision(
|
|
|
447
458
|
/**
|
|
448
459
|
* 这个聊天允不允许主动说话。
|
|
449
460
|
*
|
|
450
|
-
*
|
|
451
|
-
* 聊天自己的覆盖里写了 `proactive.enabled: true` 才算显式打开,那一条不受白名单限制。
|
|
461
|
+
* 默认拒绝:必须在这个聊天的会话覆盖里显式写 `proactive.enabled: true` 才会主动开口。
|
|
452
462
|
*/
|
|
453
|
-
export function proactiveAllowed(
|
|
454
|
-
override
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
463
|
+
export function proactiveAllowed(override: ChatOverride, target: ChatTarget): boolean {
|
|
464
|
+
if (override["proactive.enabled"] !== true) return false
|
|
465
|
+
return !chatMuted(override, target)
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** 主动说话范围:会话覆盖里打开主动说话、且聊天键合法的那些聊天。 */
|
|
469
|
+
export function proactiveScopeChats(file: ChatOverridesFile): ChatTarget[] {
|
|
470
|
+
const chats: ChatTarget[] = []
|
|
471
|
+
for (const [key, override] of Object.entries(file.chats)) {
|
|
472
|
+
if (override["proactive.enabled"] !== true) continue
|
|
473
|
+
const target = parseTargetKey(key)
|
|
474
|
+
if (target) chats.push(target)
|
|
475
|
+
}
|
|
476
|
+
return chats
|
|
466
477
|
}
|
|
467
478
|
|
|
468
479
|
/**
|
|
@@ -503,17 +514,13 @@ export function describeOverride(
|
|
|
503
514
|
if (override["wake.ignorePrefixes"]?.length) {
|
|
504
515
|
parts.push(`忽略前缀 ${override["wake.ignorePrefixes"].join(" / ")}`)
|
|
505
516
|
}
|
|
506
|
-
parts.push(
|
|
507
|
-
override["proactive.enabled"] === true
|
|
508
|
-
? "主动说话"
|
|
509
|
-
: override["proactive.enabled"] === false
|
|
510
|
-
? "不主动说话"
|
|
511
|
-
: "主动说话跟随白名单",
|
|
512
|
-
)
|
|
517
|
+
parts.push(override["proactive.enabled"] === true ? "主动说话" : "不主动说话")
|
|
513
518
|
if (override["proactive.startProbability"] !== undefined) {
|
|
514
519
|
parts.push(`主动概率 ${override["proactive.startProbability"]}`)
|
|
515
520
|
}
|
|
521
|
+
if (override["diary.enabled"] === true) parts.push("日记")
|
|
516
522
|
if (override.agent) parts.push(`agent ${override.agent}`)
|
|
523
|
+
if (override.profile) parts.push(`配置档 ${override.profile}`)
|
|
517
524
|
if (override.model) parts.push(`模型 ${override.model.providerID}/${override.model.id}`)
|
|
518
525
|
if (override.soulPath) parts.push(`角色设定 ${override.soulPath}`)
|
|
519
526
|
else if (override.soulName) parts.push(`角色设定 ${override.soulName}`)
|