@cmach_socket/opencode-qq-bot 0.6.7 → 0.7.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 +143 -76
- package/chat-overrides.example.json +7 -0
- package/package.json +3 -1
- package/src/config.ts +156 -4
- package/src/diary/collector.ts +187 -0
- package/src/diary/command.ts +277 -0
- package/src/diary/format.ts +157 -0
- package/src/diary/scheduler.ts +169 -0
- package/src/diary/store.ts +144 -0
- package/src/diary/summary.ts +380 -0
- package/src/index.ts +137 -9
- package/src/naplink/render.ts +42 -0
- package/src/overrides.ts +3 -3
- package/src/seed.ts +31 -0
- package/src/session/manager.ts +43 -1
- package/src/session/soul.ts +4 -10
- package/src/tools/policy-guard.ts +3 -0
- package/src/tools/policy.ts +14 -6
- package/src/tools/qq.ts +296 -0
- package/tool-profiles.example.json +25 -0
package/src/index.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { join, resolve } from "node:path"
|
|
1
2
|
import { Plugin } from "@opencode/plugin"
|
|
2
3
|
import type { GroupMessageEvent, MessageEvent, NoticeEvent } from "@naplink/naplink"
|
|
3
4
|
import { Mutex } from "async-mutex"
|
|
@@ -6,6 +7,11 @@ import { acquireBotLock, type BotLock, botLockPath } from "./bot-lock"
|
|
|
6
7
|
import { type ChatTarget, targetKey, targetLabel } from "./chat"
|
|
7
8
|
import { allowedTargets, isTargetAllowed } from "./access"
|
|
8
9
|
import { MIGRATION_WARNING_PREFIX, resolveConfig, type QQBotConfig } from "./config"
|
|
10
|
+
import { DiaryCollector } from "./diary/collector"
|
|
11
|
+
import { createDiaryRunner, diaryCommand } from "./diary/command"
|
|
12
|
+
import { DiaryScheduler } from "./diary/scheduler"
|
|
13
|
+
import { DiaryStore } from "./diary/store"
|
|
14
|
+
import { DiarySummarizer } from "./diary/summary"
|
|
9
15
|
import { resolveHome } from "./home"
|
|
10
16
|
import { claimInstance, takeHandover } from "./instance"
|
|
11
17
|
import { KeepAlive } from "./keepalive"
|
|
@@ -15,8 +21,15 @@ import { formatModelMessage } from "./model-view"
|
|
|
15
21
|
import { QQClient } from "./naplink/client"
|
|
16
22
|
import { createHistoryProvider } from "./naplink/history"
|
|
17
23
|
import { createMediaStore } from "./naplink/media"
|
|
18
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
describeMentions,
|
|
26
|
+
extractDiaryText,
|
|
27
|
+
renderMessage,
|
|
28
|
+
resolveUserName,
|
|
29
|
+
shouldProcess,
|
|
30
|
+
} from "./naplink/render"
|
|
19
31
|
import { SendRateLimiter } from "./rate-limit"
|
|
32
|
+
import { packageRoot, seedFile } from "./seed"
|
|
20
33
|
import { collectEnvSecrets, redactUrl, secretsFromUrl, SensitiveChecker } from "./sensitive"
|
|
21
34
|
import { SessionManager } from "./session/manager"
|
|
22
35
|
import { currentTimeText, PROACTIVE_HINT } from "./session/prompt"
|
|
@@ -37,7 +50,13 @@ import { registerAskGuard } from "./tools/ask-guard"
|
|
|
37
50
|
import { defaultToolProfilesPath, roleOf, ToolPolicy } from "./tools/policy"
|
|
38
51
|
import { registerToolPolicy } from "./tools/policy-guard"
|
|
39
52
|
import { registerSendGuard } from "./tools/send-guard"
|
|
40
|
-
import {
|
|
53
|
+
import {
|
|
54
|
+
createPlainSender,
|
|
55
|
+
QQ_REQUEST_REPLY_TOOL,
|
|
56
|
+
registerTools,
|
|
57
|
+
sendPlainMessage,
|
|
58
|
+
TOOL_NAMESPACE,
|
|
59
|
+
} from "./tools/qq"
|
|
41
60
|
import { createEmojiRunner, emojiCommand } from "./emoji/command"
|
|
42
61
|
import { describeNotice, noticeMatches, noticeTarget } from "./events/notice"
|
|
43
62
|
import { NoticeStore } from "./events/store"
|
|
@@ -319,12 +338,22 @@ export default Plugin.define({
|
|
|
319
338
|
// 通知缓存:通知不自己起一轮,只在下一次该聊天的上下文里附带出现。
|
|
320
339
|
const noticeStore = new NoticeStore()
|
|
321
340
|
// 工具配置:按聊天与角色决定模型能看到、能调用哪些工具。
|
|
322
|
-
|
|
341
|
+
// 走默认位置时把随包的示例复制过去,占位目标得自己改成真实的群 / 私聊。
|
|
342
|
+
const profilesPath = config.toolProfilesPath
|
|
343
|
+
? resolve(home.directory, config.toolProfilesPath)
|
|
344
|
+
: defaultToolProfilesPath(home.directory)
|
|
345
|
+
if (!config.toolProfilesPath) {
|
|
346
|
+
await seedFile(join(packageRoot, "tool-profiles.example.json"), profilesPath, logger)
|
|
347
|
+
}
|
|
348
|
+
const policy = new ToolPolicy(profilesPath, logger)
|
|
323
349
|
// 会话行为覆盖:按聊天决定怎么唤醒、要不要主动说话。
|
|
324
|
-
const
|
|
325
|
-
config.chatOverridesPath
|
|
326
|
-
|
|
327
|
-
)
|
|
350
|
+
const overridesPath = config.chatOverridesPath
|
|
351
|
+
? resolve(home.directory, config.chatOverridesPath)
|
|
352
|
+
: defaultChatOverridesPath(home.directory)
|
|
353
|
+
if (!config.chatOverridesPath) {
|
|
354
|
+
await seedFile(join(packageRoot, "chat-overrides.example.json"), overridesPath, logger)
|
|
355
|
+
}
|
|
356
|
+
const overrides = new ChatOverrides(overridesPath, logger)
|
|
328
357
|
// 调用链追踪:一条入站消息拿一个 trace_id,事后能把这轮串起来。
|
|
329
358
|
// 追踪文件与日志放在一起,容量与保留天数都有上限。
|
|
330
359
|
const tracer = config.trace.enabled
|
|
@@ -388,6 +417,40 @@ export default Plugin.define({
|
|
|
388
417
|
const favoriteIndex = new FavoriteIndex(ctx.storage, logger)
|
|
389
418
|
const labeler = new EmojiLabeler({ ctx, config, home, logger, media, favorites })
|
|
390
419
|
cleanup.add("注销表情标注", () => labeler.dispose(), CleanupOrder.labeler)
|
|
420
|
+
// 日记:素材累积在 raw/ 下,成品是按天一个的 Markdown 文件。
|
|
421
|
+
// 日记目录默认落在机器人工作目录里,因此天然在出站媒体白名单内。
|
|
422
|
+
const diaryRoot = config.diary.path.trim()
|
|
423
|
+
? resolve(home.directory, config.diary.path)
|
|
424
|
+
: join(home.directory, "diary")
|
|
425
|
+
const diaryStore = new DiaryStore({ root: diaryRoot, logger })
|
|
426
|
+
const diaryCollector = new DiaryCollector({
|
|
427
|
+
root: diaryRoot,
|
|
428
|
+
logger,
|
|
429
|
+
maxLineChars: config.diary.maxLineChars,
|
|
430
|
+
maxLinesPerDay: config.diary.maxLinesPerDay,
|
|
431
|
+
})
|
|
432
|
+
const diarySummarizer = new DiarySummarizer({
|
|
433
|
+
ctx,
|
|
434
|
+
config,
|
|
435
|
+
home,
|
|
436
|
+
logger,
|
|
437
|
+
collector: diaryCollector,
|
|
438
|
+
store: diaryStore,
|
|
439
|
+
timeoutMs: config.diary.timeoutMs,
|
|
440
|
+
})
|
|
441
|
+
cleanup.add("注销日记总结", () => diarySummarizer.dispose(), CleanupOrder.labeler)
|
|
442
|
+
const diaryScheduler = new DiaryScheduler({
|
|
443
|
+
config,
|
|
444
|
+
logger,
|
|
445
|
+
client,
|
|
446
|
+
limiter,
|
|
447
|
+
outbound,
|
|
448
|
+
sensitive,
|
|
449
|
+
store: diaryStore,
|
|
450
|
+
collector: diaryCollector,
|
|
451
|
+
summarizer: diarySummarizer,
|
|
452
|
+
})
|
|
453
|
+
cleanup.add("停止日记调度", () => diaryScheduler.dispose(), CleanupOrder.events)
|
|
391
454
|
// QQ 工具只有持有机器级锁的实例才注册:工具表在进程内共享,
|
|
392
455
|
// 没锁的实例注册了会覆盖持有者的实现,模型就会调到没有连接的那一份。
|
|
393
456
|
let toolRegistration: { dispose(): Promise<void> } | undefined
|
|
@@ -406,6 +469,7 @@ export default Plugin.define({
|
|
|
406
469
|
limiter,
|
|
407
470
|
sensitive,
|
|
408
471
|
outbound,
|
|
472
|
+
diary: diaryStore,
|
|
409
473
|
tracer,
|
|
410
474
|
// 没有机器级锁的实例不能发送:那是别的实例的机器人。
|
|
411
475
|
canSend: () => botLock !== undefined,
|
|
@@ -413,7 +477,7 @@ export default Plugin.define({
|
|
|
413
477
|
toolRegistration = registration
|
|
414
478
|
cleanup.add("注销工具", () => registration.dispose(), CleanupOrder.tools)
|
|
415
479
|
}
|
|
416
|
-
// 命令表:管理命令 +
|
|
480
|
+
// 命令表:管理命令 + 表情标注 + 日记,QQ 私聊与 TUI 共用同一套实现。
|
|
417
481
|
const commands = [
|
|
418
482
|
...COMMANDS,
|
|
419
483
|
emojiCommand(
|
|
@@ -427,6 +491,19 @@ export default Plugin.define({
|
|
|
427
491
|
limiter,
|
|
428
492
|
}),
|
|
429
493
|
),
|
|
494
|
+
diaryCommand(
|
|
495
|
+
createDiaryRunner({
|
|
496
|
+
config,
|
|
497
|
+
logger,
|
|
498
|
+
client,
|
|
499
|
+
limiter,
|
|
500
|
+
outbound,
|
|
501
|
+
sensitive,
|
|
502
|
+
store: diaryStore,
|
|
503
|
+
collector: diaryCollector,
|
|
504
|
+
summarizer: diarySummarizer,
|
|
505
|
+
}),
|
|
506
|
+
),
|
|
430
507
|
]
|
|
431
508
|
// 命令结果统一走限流;发送失败只记日志,不影响命令本身。
|
|
432
509
|
const replyTo = createPlainSender(client, {
|
|
@@ -471,6 +548,11 @@ export default Plugin.define({
|
|
|
471
548
|
// 它的输入是一张图片,工具一律摘掉,只让模型输出标签。
|
|
472
549
|
if (await labeler.isLabelSession(event.sessionID)) {
|
|
473
550
|
for (const name of Object.keys(event.tools)) delete event.tools[name]
|
|
551
|
+
return
|
|
552
|
+
}
|
|
553
|
+
// 日记总结会话的输入是群友可控的聊天记录,同样不带任何工具。
|
|
554
|
+
if (await diarySummarizer.isSummarySession(event.sessionID)) {
|
|
555
|
+
for (const name of Object.keys(event.tools)) delete event.tools[name]
|
|
474
556
|
}
|
|
475
557
|
return
|
|
476
558
|
}
|
|
@@ -504,7 +586,7 @@ export default Plugin.define({
|
|
|
504
586
|
event.system.push({
|
|
505
587
|
type: "text",
|
|
506
588
|
text: turn?.proactive
|
|
507
|
-
? `这是一次主动发起话题,必须调用 qq_send_message 把话题发到${destination}
|
|
589
|
+
? `这是一次主动发起话题,必须调用 qq_send_message 把话题发到${destination}。${target.kind === "group" && config.reply.requirePermission ? "群里要先调用 qq_request_reply 说明为什么要回复,拿到权限后才能发送。" : ""}`
|
|
508
590
|
: turn?.atMe
|
|
509
591
|
? wakeHint(turn.wake)
|
|
510
592
|
: turn?.suppress
|
|
@@ -519,12 +601,21 @@ export default Plugin.define({
|
|
|
519
601
|
text: `聊天里发生过的通知(不需要回复):\n${notices.map((item) => `- ${item}`).join("\n")}`,
|
|
520
602
|
})
|
|
521
603
|
}
|
|
604
|
+
// 群里默认没有发送权限:模型得先想清楚该不该回复,说明理由才拿得到权限。
|
|
605
|
+
if (target.kind === "group" && config.reply.requirePermission) {
|
|
606
|
+
event.system.push({
|
|
607
|
+
type: "text",
|
|
608
|
+
text: `默认你没有向用户发消息的权限。要回复,先判断该不该回复,再调用 ${QQ_REQUEST_REPLY_TOOL} 说明为什么要回复;拿到权限后才能调用 qq_send_message,权限只在本轮有效。`,
|
|
609
|
+
})
|
|
610
|
+
}
|
|
522
611
|
// 本轮发送者的角色决定工具档:owner / admin 全开,其他按聊天配置。
|
|
523
612
|
// 角色按会话保留,没有在途轮次(重启、TUI 驱动)时也照样收窄。
|
|
524
613
|
{
|
|
525
614
|
const allowed = await policy.allow(role, targetKey(target), Object.keys(event.tools))
|
|
526
615
|
const removed: string[] = []
|
|
527
616
|
for (const name of Object.keys(event.tools)) {
|
|
617
|
+
// 申请回复权限的工具必须一直留着:不然模型永远拿不到发送权限。
|
|
618
|
+
if (name === QQ_REQUEST_REPLY_TOOL) continue
|
|
528
619
|
if (!allowed.has(name)) {
|
|
529
620
|
removed.push(name)
|
|
530
621
|
delete event.tools[name]
|
|
@@ -698,6 +789,35 @@ export default Plugin.define({
|
|
|
698
789
|
}
|
|
699
790
|
return mutex
|
|
700
791
|
}
|
|
792
|
+
/**
|
|
793
|
+
* 采集一条入站消息的日记素材。
|
|
794
|
+
*
|
|
795
|
+
* 落盘是异步的,不挡消息处理:写失败只记日志,不影响聊天。
|
|
796
|
+
*/
|
|
797
|
+
const collectDiaryLine = (event: MessageEvent, target: ChatTarget, selfId: string): void => {
|
|
798
|
+
if (!config.diary.enabled) return
|
|
799
|
+
const content = extractDiaryText(event.message)
|
|
800
|
+
if (!content) return
|
|
801
|
+
const userId = String(event.user_id)
|
|
802
|
+
void (async () => {
|
|
803
|
+
let name = ""
|
|
804
|
+
try {
|
|
805
|
+
name = await resolveUserName(renderContext(target, selfId), userId)
|
|
806
|
+
} catch {
|
|
807
|
+
// 取不到显示名就退回 QQ 号。
|
|
808
|
+
}
|
|
809
|
+
await diaryCollector.append(targetKey(target), {
|
|
810
|
+
id: String(event.message_id),
|
|
811
|
+
time: event.time,
|
|
812
|
+
userId,
|
|
813
|
+
name: name || userId,
|
|
814
|
+
text: content,
|
|
815
|
+
self: Boolean(selfId) && userId === selfId,
|
|
816
|
+
backfilled: false,
|
|
817
|
+
})
|
|
818
|
+
})().catch((error: unknown) => logger.error("采集日记素材失败", error))
|
|
819
|
+
}
|
|
820
|
+
|
|
701
821
|
const scheduleMessage = (event: MessageEvent) => {
|
|
702
822
|
// 没有占用机器人连接时不消费消息,避免和别的实例重复投递。
|
|
703
823
|
if (!botLock) return
|
|
@@ -711,6 +831,8 @@ export default Plugin.define({
|
|
|
711
831
|
return
|
|
712
832
|
}
|
|
713
833
|
manager.touch(target)
|
|
834
|
+
// 日记素材:放在去重之后,重复投递的消息只会被记一次。
|
|
835
|
+
collectDiaryLine(event, target, selfId)
|
|
714
836
|
logger.info(`${targetLabel(target)} 收到 QQ 消息`, {
|
|
715
837
|
user: String(event.user_id),
|
|
716
838
|
message_id: String(event.message_id),
|
|
@@ -809,6 +931,12 @@ export default Plugin.define({
|
|
|
809
931
|
unrefTimer(proactiveTimer)
|
|
810
932
|
}
|
|
811
933
|
|
|
934
|
+
// 日记调度:到点生成当天的日记并推送。定时器随插件一起卸载,
|
|
935
|
+
// 要保证它一直跑需要 experimental.location_idle_timeout: false。
|
|
936
|
+
if (config.diary.enabled) {
|
|
937
|
+
diaryScheduler.start()
|
|
938
|
+
}
|
|
939
|
+
|
|
812
940
|
// 工具先注册,模型这一轮就能看到 qq_*;再连 NapCat 开始消费。
|
|
813
941
|
await registerRuntime()
|
|
814
942
|
await startConsuming()
|
package/src/naplink/render.ts
CHANGED
|
@@ -108,6 +108,48 @@ export function shouldProcess(message: readonly MessageSegment[], userId?: strin
|
|
|
108
108
|
})
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
/**
|
|
112
|
+
* 轻量提取一条消息的文本。
|
|
113
|
+
*
|
|
114
|
+
* 日记素材用:只出占位文本,不下载图片、不转写语音,
|
|
115
|
+
* 因此不需要任何 API 调用,可以在入站链路上同步跑完。
|
|
116
|
+
*/
|
|
117
|
+
export function extractDiaryText(message: readonly MessageSegment[]): string {
|
|
118
|
+
const parts: string[] = []
|
|
119
|
+
for (const segment of segments(message)) {
|
|
120
|
+
switch (segment.type) {
|
|
121
|
+
case "text": {
|
|
122
|
+
const content = sanitizeUntrustedText(segment.data.text ?? "").trim()
|
|
123
|
+
if (content) parts.push(content)
|
|
124
|
+
break
|
|
125
|
+
}
|
|
126
|
+
case "at":
|
|
127
|
+
parts.push(`@${String(segment.data.qq)}`)
|
|
128
|
+
break
|
|
129
|
+
case "face":
|
|
130
|
+
parts.push("[表情]")
|
|
131
|
+
break
|
|
132
|
+
case "image":
|
|
133
|
+
parts.push("[图片]")
|
|
134
|
+
break
|
|
135
|
+
case "record":
|
|
136
|
+
case "audio":
|
|
137
|
+
parts.push("[语音]")
|
|
138
|
+
break
|
|
139
|
+
case "video":
|
|
140
|
+
parts.push("[视频]")
|
|
141
|
+
break
|
|
142
|
+
case "file":
|
|
143
|
+
parts.push("[文件]")
|
|
144
|
+
break
|
|
145
|
+
default:
|
|
146
|
+
// 引用、转发与结构化段不进素材。
|
|
147
|
+
break
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return parts.join(" ").trim()
|
|
151
|
+
}
|
|
152
|
+
|
|
111
153
|
/** 判断消息里是否 @ 了指定 QQ 号。 */
|
|
112
154
|
export function mentionsUser(
|
|
113
155
|
message: readonly MessageSegment[],
|
package/src/overrides.ts
CHANGED
|
@@ -83,9 +83,9 @@ export function defaultChatOverrides(): ChatOverridesFile {
|
|
|
83
83
|
return { chats: {} }
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
-
/**
|
|
87
|
-
export function defaultChatOverridesPath(): string {
|
|
88
|
-
return join(
|
|
86
|
+
/** 默认的配置文件位置:工作目录下的 `chat-overrides.json`。 */
|
|
87
|
+
export function defaultChatOverridesPath(home: string): string {
|
|
88
|
+
return join(home, "chat-overrides.json")
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
/**
|
package/src/seed.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { existsSync } from "node:fs"
|
|
2
|
+
import { copyFile, mkdir } from "node:fs/promises"
|
|
3
|
+
import { dirname, resolve } from "node:path"
|
|
4
|
+
import type { Logger } from "./logger"
|
|
5
|
+
|
|
6
|
+
/** 随包分发文件所在目录:种子文件只从这里取。 */
|
|
7
|
+
export const packageRoot = resolve(import.meta.dirname, "..")
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 把随包分发的模板复制到工作目录。
|
|
11
|
+
*
|
|
12
|
+
* 目标已存在时原样保留:用户的改动不会被升级或重启覆盖。
|
|
13
|
+
*
|
|
14
|
+
* @returns 是否真的复制了。
|
|
15
|
+
*/
|
|
16
|
+
export async function seedFile(
|
|
17
|
+
source: string,
|
|
18
|
+
destination: string,
|
|
19
|
+
logger: Logger,
|
|
20
|
+
): Promise<boolean> {
|
|
21
|
+
if (existsSync(destination)) return false
|
|
22
|
+
try {
|
|
23
|
+
await mkdir(dirname(destination), { recursive: true, mode: 0o700 })
|
|
24
|
+
await copyFile(source, destination)
|
|
25
|
+
logger.info(`已放到工作目录:${destination}`)
|
|
26
|
+
return true
|
|
27
|
+
} catch (error) {
|
|
28
|
+
logger.warn(`复制 ${source} 失败`, error)
|
|
29
|
+
return false
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/session/manager.ts
CHANGED
|
@@ -172,6 +172,10 @@ interface ChatState {
|
|
|
172
172
|
lastRetireAt: number
|
|
173
173
|
/** 最近一次清空当前轮次的原因与时间,仅供排查。 */
|
|
174
174
|
lastClear?: { reason: string; at: number; role?: Role; traceId?: string }
|
|
175
|
+
/** 本轮是否已批准发送:模型先说明理由才拿到这个权限,轮次结束即失效。 */
|
|
176
|
+
replyAllowed: boolean
|
|
177
|
+
/** 批准发送的理由,仅供日志与排查。 */
|
|
178
|
+
replyReason?: string
|
|
175
179
|
}
|
|
176
180
|
|
|
177
181
|
/** 插件存储接受的值类型。 */
|
|
@@ -605,6 +609,7 @@ export class SessionManager {
|
|
|
605
609
|
reminders: 0,
|
|
606
610
|
lastUserMessageAt: this.activity[key] ?? Date.now(),
|
|
607
611
|
lastRetireAt: 0,
|
|
612
|
+
replyAllowed: false,
|
|
608
613
|
}
|
|
609
614
|
this.states.set(key, state)
|
|
610
615
|
}
|
|
@@ -875,6 +880,9 @@ export class SessionManager {
|
|
|
875
880
|
...(state.lastClear.traceId ? { trace_id: state.lastClear.traceId } : {}),
|
|
876
881
|
})
|
|
877
882
|
state.current = undefined
|
|
883
|
+
// 发送权限只在本轮有效:轮次结束就收回,下一轮要重新说明理由。
|
|
884
|
+
state.replyAllowed = false
|
|
885
|
+
state.replyReason = undefined
|
|
878
886
|
// 在途轮次落盘,重启后不会把已经结束的一轮又恢复出来。
|
|
879
887
|
this.scheduleSave()
|
|
880
888
|
}
|
|
@@ -909,6 +917,8 @@ export class SessionManager {
|
|
|
909
917
|
lastDispatchAt: state.lastDispatchAt,
|
|
910
918
|
idleAt: state.idleAt,
|
|
911
919
|
lastClear: state.lastClear,
|
|
920
|
+
replyAllowed: state.replyAllowed,
|
|
921
|
+
replyReason: state.replyReason,
|
|
912
922
|
now: Date.now(),
|
|
913
923
|
}
|
|
914
924
|
}
|
|
@@ -922,6 +932,33 @@ export class SessionManager {
|
|
|
922
932
|
this.scheduleSave()
|
|
923
933
|
}
|
|
924
934
|
|
|
935
|
+
/**
|
|
936
|
+
* 模型申请本轮的发送权限。
|
|
937
|
+
*
|
|
938
|
+
* 默认不给发送权限:模型得先说明为什么回复,拿到权限后才能调用发送工具。
|
|
939
|
+
* 权限只在本轮有效,轮次结束就失效。
|
|
940
|
+
*
|
|
941
|
+
* @returns 是否批准。会话没有绑定或已经有权限时不算失败。
|
|
942
|
+
*/
|
|
943
|
+
requestReply(sessionID: string, reason: string): { granted: boolean; reason: string } {
|
|
944
|
+
const state = this.sessions.get(sessionID)
|
|
945
|
+
if (!state) return { granted: false, reason }
|
|
946
|
+
// 权限只在本轮有效:没有进行中的轮次就不给。
|
|
947
|
+
if (!state.current) {
|
|
948
|
+
this.logger.warn(`${targetLabel(state.target)} 没有进行中的轮次,不给发送权限`)
|
|
949
|
+
return { granted: false, reason }
|
|
950
|
+
}
|
|
951
|
+
state.replyAllowed = true
|
|
952
|
+
state.replyReason = reason
|
|
953
|
+
this.logger.info(`${targetLabel(state.target)} 模型申请本轮发送权限:${reason}`)
|
|
954
|
+
return { granted: true, reason }
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/** 本轮是否已经拿到发送权限。 */
|
|
958
|
+
canReply(sessionID: string): boolean {
|
|
959
|
+
return this.sessions.get(sessionID)?.replyAllowed === true
|
|
960
|
+
}
|
|
961
|
+
|
|
925
962
|
/** 记录一条机器人发出的消息,撤回工具只能操作这些消息。 */
|
|
926
963
|
rememberOutgoing(target: ChatTarget, messageId: string): void {
|
|
927
964
|
this.track(this.outgoing, target, messageId)
|
|
@@ -1266,10 +1303,15 @@ export class SessionManager {
|
|
|
1266
1303
|
...(reminderRole ? { role: reminderRole } : {}),
|
|
1267
1304
|
}
|
|
1268
1305
|
this.logger.warn(`${label} 模型未调用发送工具,提醒第 ${state.reminders} 次`)
|
|
1306
|
+
// 群里默认没有发送权限,提醒里得说清楚先申请再发。
|
|
1307
|
+
const permissionHint =
|
|
1308
|
+
this.config.reply.requirePermission && state.target.kind === "group"
|
|
1309
|
+
? "群里要先调用 qq_request_reply 说明为什么要回复,拿到权限后才能发送。"
|
|
1310
|
+
: ""
|
|
1269
1311
|
try {
|
|
1270
1312
|
await this.ctx.session.synthetic({
|
|
1271
1313
|
sessionID,
|
|
1272
|
-
text: `[提醒] 你这一轮没有调用任何发送工具,直接输出的文字会被丢弃。请调用 qq_send_message 工具:想回复就 reply=true 并给出 content,不想回复就 reply=false
|
|
1314
|
+
text: `[提醒] 你这一轮没有调用任何发送工具,直接输出的文字会被丢弃。请调用 qq_send_message 工具:想回复就 reply=true 并给出 content,不想回复就 reply=false;发送图片、语音、转发或戳一戳也视为已回复。${permissionHint}`,
|
|
1273
1315
|
})
|
|
1274
1316
|
} catch (error) {
|
|
1275
1317
|
state.awaitingSend = false
|
package/src/session/soul.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mkdir, readdir, readFile } from "node:fs/promises"
|
|
2
2
|
import { existsSync, statSync, watch, type FSWatcher } from "node:fs"
|
|
3
3
|
import { dirname, isAbsolute, join, resolve } from "node:path"
|
|
4
4
|
import { unrefTimer } from "../async"
|
|
5
|
+
import { seedFile } from "../seed"
|
|
5
6
|
import type { Logger } from "../logger"
|
|
6
7
|
import { buildSystemPrompt } from "./prompt"
|
|
7
8
|
|
|
@@ -65,15 +66,8 @@ export async function seedSouls(
|
|
|
65
66
|
}
|
|
66
67
|
for (const entry of entries) {
|
|
67
68
|
if (!entry.isFile()) continue
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (existsSync(destination)) continue
|
|
71
|
-
try {
|
|
72
|
-
await copyFile(join(template, entry.name), destination)
|
|
73
|
-
logger.info(`角色设定已就位:${destination}`)
|
|
74
|
-
} catch (error) {
|
|
75
|
-
logger.warn(`复制角色设定失败:${entry.name}`, error)
|
|
76
|
-
}
|
|
69
|
+
// 已有同名文件说明用户改过或换过,seedFile 不会动它。
|
|
70
|
+
await seedFile(join(template, entry.name), join(target, entry.name), logger)
|
|
77
71
|
}
|
|
78
72
|
}
|
|
79
73
|
|
|
@@ -3,6 +3,7 @@ import { targetKey, targetLabel } from "../chat"
|
|
|
3
3
|
import type { Logger } from "../logger"
|
|
4
4
|
import type { SessionManager } from "../session/manager"
|
|
5
5
|
import type { ToolPolicy } from "./policy"
|
|
6
|
+
import { QQ_REQUEST_REPLY_TOOL } from "./qq"
|
|
6
7
|
|
|
7
8
|
/** 会开启独立会话的工具名;不同版本分别叫 subagent 与 task。 */
|
|
8
9
|
const SUBAGENT_TOOLS = new Set(["subagent", "task"])
|
|
@@ -35,6 +36,8 @@ export async function registerToolPolicy(
|
|
|
35
36
|
logger.warn(`${targetLabel(target)} 会话里拒绝创建子代理 ${event.tool}`)
|
|
36
37
|
throw new Error("QQ 聊天会话里不能创建子代理:子会话不会继承按聊天的工具限制。")
|
|
37
38
|
}
|
|
39
|
+
// 申请回复权限的工具必须一直放行:不然模型永远拿不到发送权限。
|
|
40
|
+
if (event.tool === QQ_REQUEST_REPLY_TOOL) return
|
|
38
41
|
const allowed = await policy.allow(role, targetKey(target), [event.tool])
|
|
39
42
|
logger.debug(`${targetLabel(target)} 工具策略检查`, {
|
|
40
43
|
role,
|
package/src/tools/policy.ts
CHANGED
|
@@ -41,24 +41,32 @@ export interface ToolPolicyFile {
|
|
|
41
41
|
chats: Record<string, string>
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
/**
|
|
45
|
+
* 只对 owner 与 admin 开放的工具。
|
|
46
|
+
*
|
|
47
|
+
* 日记记录聊天内容,发文件能把本地文件送出去:两者都只给管理档。
|
|
48
|
+
* 用 deny 而不是不放进 allow,是为了用户自定义配置档时也不会误放开。
|
|
49
|
+
*/
|
|
50
|
+
const DIARY_DENY = ["qq_diary_*", "qq_send_file"]
|
|
51
|
+
|
|
44
52
|
/** 内置默认值:普通聊天只留联网搜索、网页抓取和发消息工具,管理档全开。 */
|
|
45
53
|
export function defaultToolPolicy(): ToolPolicyFile {
|
|
46
54
|
return {
|
|
47
55
|
defaultProfile: "chat",
|
|
48
56
|
profiles: {
|
|
49
|
-
chat: { allow: ["websearch", "webfetch", "qq_*"], deny: [] },
|
|
50
|
-
readonly: { allow: ["read", "glob", "grep", "qq_*"], deny: [] },
|
|
57
|
+
chat: { allow: ["websearch", "webfetch", "qq_*"], deny: [...DIARY_DENY] },
|
|
58
|
+
readonly: { allow: ["read", "glob", "grep", "qq_*"], deny: [...DIARY_DENY] },
|
|
51
59
|
// 主动说话没有人参与,权限不能跟着聊天内容走:与普通聊天同档。
|
|
52
|
-
proactive: { allow: ["websearch", "webfetch", "qq_*"], deny: [] },
|
|
60
|
+
proactive: { allow: ["websearch", "webfetch", "qq_*"], deny: [...DIARY_DENY] },
|
|
53
61
|
admin: { allow: ["*"], deny: [] },
|
|
54
62
|
},
|
|
55
63
|
chats: {},
|
|
56
64
|
}
|
|
57
65
|
}
|
|
58
66
|
|
|
59
|
-
/**
|
|
60
|
-
export function defaultToolProfilesPath(): string {
|
|
61
|
-
return join(
|
|
67
|
+
/** 默认的配置文件位置:工作目录下的 `tool-profiles.json`。 */
|
|
68
|
+
export function defaultToolProfilesPath(home: string): string {
|
|
69
|
+
return join(home, "tool-profiles.json")
|
|
62
70
|
}
|
|
63
71
|
|
|
64
72
|
/**
|