@cmach_socket/opencode-qq-bot 0.9.0 → 0.10.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 +0 -1
- package/README.md +152 -494
- package/chat-overrides.example.json +3 -3
- package/config.example.json +12 -0
- package/package.json +7 -2
- package/src/chat.ts +5 -0
- package/src/commands.ts +88 -1
- package/src/config/fields.ts +48 -5
- package/src/config/live.ts +61 -3
- package/src/config/store.ts +6 -11
- package/src/config/types.ts +24 -0
- package/src/config.ts +3 -0
- package/src/diary/command.ts +13 -12
- package/src/diary/format.ts +17 -0
- package/src/diary/scheduler.ts +1 -1
- package/src/diary/summary.ts +6 -5
- package/src/emoji/collection.ts +321 -0
- package/src/emoji/favorite-index.ts +40 -3
- package/src/emoji/favorites.ts +7 -1
- package/src/fs/atomic.ts +82 -0
- package/src/home.ts +6 -2
- package/src/index.ts +41 -36
- package/src/keepalive.ts +60 -2
- package/src/known-secrets.ts +20 -0
- package/src/logger.ts +2 -1
- package/src/overrides.ts +209 -47
- package/src/panel/api.ts +61 -7
- package/src/panel/documents.ts +621 -0
- package/src/panel/server.ts +66 -25
- package/src/panel/status.ts +8 -1
- package/src/safe-object.ts +48 -0
- package/src/sensitive.ts +31 -2
- package/src/session/find.ts +3 -2
- package/src/session/manager.ts +646 -43
- package/src/session/proactive.ts +3 -1
- package/src/session/soul-guard.ts +162 -0
- package/src/session/soul.ts +78 -13
- package/src/state-lock.ts +74 -0
- package/src/tools/policy.ts +65 -24
- package/src/tools/qq.ts +103 -22
- package/web/dist/assets/index-C5lRsdbz.css +1 -0
- package/web/dist/assets/index-YqorZD0I.js +8 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-7eMQEM7-.css +0 -1
- package/web/dist/assets/index-DCkgUY7y.js +0 -15
package/src/index.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { join, resolve } from "node:path"
|
|
2
|
-
import { randomBytes } from "node:crypto"
|
|
3
2
|
import { Plugin } from "@opencode/plugin"
|
|
4
3
|
import type { GroupMessageEvent, MessageEvent, NoticeEvent } from "@naplink/naplink"
|
|
5
4
|
import { Mutex } from "async-mutex"
|
|
@@ -13,7 +12,7 @@ import { ConfigStore, CONFIG_FILE_NAME } from "./config/store"
|
|
|
13
12
|
import { DiaryCollector, isSelfSpeaker } from "./diary/collector"
|
|
14
13
|
import { createDiaryRunner, diaryCommand } from "./diary/command"
|
|
15
14
|
import { DiaryScheduler } from "./diary/scheduler"
|
|
16
|
-
import { isDiaryScopeChat } from "./diary/scope"
|
|
15
|
+
import { diaryScopeChat, isDiaryScopeChat } from "./diary/scope"
|
|
17
16
|
import { DiaryStore } from "./diary/store"
|
|
18
17
|
import { DiarySummarizer } from "./diary/summary"
|
|
19
18
|
import { resolveHome } from "./home"
|
|
@@ -39,7 +38,8 @@ import { SendRateLimiter } from "./rate-limit"
|
|
|
39
38
|
import { startClaimTimer } from "./runtime/claim"
|
|
40
39
|
import { RuntimeStart } from "./runtime/start"
|
|
41
40
|
import { packageRoot, seedFile } from "./seed"
|
|
42
|
-
import {
|
|
41
|
+
import { redactUrl, SensitiveChecker } from "./sensitive"
|
|
42
|
+
import { knownSecrets } from "./known-secrets"
|
|
43
43
|
import { SessionManager } from "./session/manager"
|
|
44
44
|
import { currentTimeText, PROACTIVE_HINT } from "./session/prompt"
|
|
45
45
|
import { proactiveProbability } from "./session/proactive"
|
|
@@ -48,15 +48,15 @@ import { COMMANDS, handleCommand, isCommandChat } from "./commands"
|
|
|
48
48
|
import {
|
|
49
49
|
chatMuted,
|
|
50
50
|
ChatOverrides,
|
|
51
|
-
defaultChatOverridesPath,
|
|
52
51
|
proactiveAllowed,
|
|
52
|
+
resolveChatOverridesPath,
|
|
53
53
|
wakeDecision,
|
|
54
54
|
type WakeReason,
|
|
55
55
|
} from "./overrides"
|
|
56
56
|
import { Tracer } from "./trace"
|
|
57
57
|
import { Cleanup, CleanupOrder } from "./cleanup"
|
|
58
58
|
import { registerAskGuard } from "./tools/ask-guard"
|
|
59
|
-
import {
|
|
59
|
+
import { resolveToolProfilesPath, roleOf, ToolPolicy } from "./tools/policy"
|
|
60
60
|
import { registerToolPolicy } from "./tools/policy-guard"
|
|
61
61
|
import { registerSendGuard } from "./tools/send-guard"
|
|
62
62
|
import {
|
|
@@ -73,6 +73,7 @@ import { registerTuiCommands } from "./tui-commands"
|
|
|
73
73
|
import { pluginVersion } from "./version"
|
|
74
74
|
import { FavoriteStore } from "./emoji/favorites"
|
|
75
75
|
import { FavoriteIndex } from "./emoji/favorite-index"
|
|
76
|
+
import { CollectionStore, RecentImages } from "./emoji/collection"
|
|
76
77
|
import { EmojiLabeler } from "./emoji/label"
|
|
77
78
|
|
|
78
79
|
const RETRY_DELAY_MS = 1000
|
|
@@ -99,15 +100,7 @@ function agentFromOptions(options: unknown): string | undefined {
|
|
|
99
100
|
* 除了环境变量与 NapCat 令牌,地址查询串里挂着的 token 也要算进来,
|
|
100
101
|
* 否则它会原样落进日志文件。面板令牌同样算进来:它能进日志文件就等于面板失守。
|
|
101
102
|
*/
|
|
102
|
-
export
|
|
103
|
-
return [
|
|
104
|
-
...collectEnvSecrets(process.env),
|
|
105
|
-
config.napcat.token ?? "",
|
|
106
|
-
// 面板令牌能进日志文件就等于面板失守,日志里一律掩码。
|
|
107
|
-
config.panel.token ?? "",
|
|
108
|
-
...secretsFromUrl(config.napcat.url),
|
|
109
|
-
].filter((secret) => secret.length > 0)
|
|
110
|
-
}
|
|
103
|
+
export { knownSecrets }
|
|
111
104
|
|
|
112
105
|
const isGroupEvent = (event: MessageEvent): event is GroupMessageEvent =>
|
|
113
106
|
event.message_type === "group"
|
|
@@ -200,18 +193,7 @@ export default Plugin.define({
|
|
|
200
193
|
logger.warn("未配置放行目标,插件不会响应任何消息(请在 config.json 里配置 access.allow)")
|
|
201
194
|
}
|
|
202
195
|
|
|
203
|
-
//
|
|
204
|
-
if (config.panel.enabled) {
|
|
205
|
-
if (!config.panel.token) {
|
|
206
|
-
const token = randomBytes(32).toString("hex")
|
|
207
|
-
await controller.applyPatch({ "panel.token": token })
|
|
208
|
-
logger.warn("面板访问令牌已生成,请查看 config.json 里的 panel.token")
|
|
209
|
-
} else if (config.panel.token.length < 16) {
|
|
210
|
-
logger.warn("面板访问令牌太短,建议至少 16 个字符")
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
// 状态面板:默认关闭,启用后自带 HTTP 服务。
|
|
196
|
+
// 状态面板:默认开启,自带 HTTP 服务,只监听本机。
|
|
215
197
|
const panelRuntime = new PanelRuntime({ config, home, logger })
|
|
216
198
|
panelRuntime.version = version
|
|
217
199
|
panelRuntime.agent = config.agent
|
|
@@ -384,6 +366,10 @@ export default Plugin.define({
|
|
|
384
366
|
soulName: config.soulName,
|
|
385
367
|
home: home.directory,
|
|
386
368
|
moduleDir: packageDirectory(),
|
|
369
|
+
// 允许根之外的目录要显式放开;角色设定的内容会随每一轮发给模型服务商。
|
|
370
|
+
allowedPaths: config.soul.allowedPaths,
|
|
371
|
+
// 已知凭证明文:人格文件里出现就拒绝加载或掩码。
|
|
372
|
+
secrets: knownSecrets(config),
|
|
387
373
|
}
|
|
388
374
|
await seedSouls(soulOptions, logger)
|
|
389
375
|
const souls = new SoulLibrary(soulOptions, logger)
|
|
@@ -439,22 +425,21 @@ export default Plugin.define({
|
|
|
439
425
|
const noticeStore = new NoticeStore()
|
|
440
426
|
// 工具配置:按聊天与角色决定模型能看到、能调用哪些工具。
|
|
441
427
|
// 走默认位置时把随包的示例复制过去,占位目标得自己改成真实的群 / 私聊。
|
|
442
|
-
const profilesPath = config.
|
|
443
|
-
? resolve(home.directory, config.toolProfilesPath)
|
|
444
|
-
: defaultToolProfilesPath(home.directory)
|
|
428
|
+
const profilesPath = resolveToolProfilesPath(config, home.directory)
|
|
445
429
|
if (!config.toolProfilesPath) {
|
|
446
430
|
await seedFile(join(packageRoot, "tool-profiles.example.json"), profilesPath, logger)
|
|
447
431
|
}
|
|
448
432
|
const policy = new ToolPolicy(profilesPath, logger)
|
|
449
433
|
panelRuntime.policy = policy
|
|
450
434
|
// 会话行为覆盖:按聊天决定怎么唤醒、要不要主动说话。
|
|
451
|
-
const overridesPath = config.
|
|
452
|
-
? resolve(home.directory, config.chatOverridesPath)
|
|
453
|
-
: defaultChatOverridesPath(home.directory)
|
|
435
|
+
const overridesPath = resolveChatOverridesPath(config, home.directory)
|
|
454
436
|
if (!config.chatOverridesPath) {
|
|
455
437
|
await seedFile(join(packageRoot, "chat-overrides.example.json"), overridesPath, logger)
|
|
456
438
|
}
|
|
457
|
-
const overrides = new ChatOverrides(overridesPath, logger
|
|
439
|
+
const overrides = new ChatOverrides(overridesPath, logger, {
|
|
440
|
+
home: home.directory,
|
|
441
|
+
allowedPaths: config.soul.allowedPaths,
|
|
442
|
+
})
|
|
458
443
|
panelRuntime.overrides = overrides
|
|
459
444
|
// 调用链追踪:一条入站消息拿一个 trace_id,事后能把这轮串起来。
|
|
460
445
|
// 追踪文件与日志放在一起,容量与保留天数都有上限。
|
|
@@ -480,6 +465,9 @@ export default Plugin.define({
|
|
|
480
465
|
},
|
|
481
466
|
overrides,
|
|
482
467
|
tracer,
|
|
468
|
+
// 只有独占机器的实例才能写共享状态:机器锁已经易主时,
|
|
469
|
+
// 旧实例写出去的状态会把接管者刚建的绑定冲掉。
|
|
470
|
+
() => botLock !== undefined,
|
|
483
471
|
)
|
|
484
472
|
cleanup.add("停止会话管理", () => manager.dispose(), CleanupOrder.manager)
|
|
485
473
|
panelRuntime.manager = manager
|
|
@@ -519,6 +507,10 @@ export default Plugin.define({
|
|
|
519
507
|
logger,
|
|
520
508
|
)
|
|
521
509
|
const favoriteIndex = new FavoriteIndex(ctx.storage, logger)
|
|
510
|
+
// 本机收集的表情:QQ 收藏表情写不进 NapCat,收集的动图自己存在媒体目录里。
|
|
511
|
+
const collection = new CollectionStore(ctx.storage, mediaDir, logger)
|
|
512
|
+
// 各聊天最近收到的图片:收藏表情时从中挑素材。
|
|
513
|
+
const recentImages = new RecentImages()
|
|
522
514
|
const labeler = new EmojiLabeler({ ctx, config, home, logger, media, favorites })
|
|
523
515
|
cleanup.add("注销表情标注", () => labeler.dispose(), CleanupOrder.labeler)
|
|
524
516
|
// 日记:素材累积在 raw/ 下,成品是按天一个的 Markdown 文件。
|
|
@@ -571,6 +563,8 @@ export default Plugin.define({
|
|
|
571
563
|
client,
|
|
572
564
|
favorites,
|
|
573
565
|
favoriteIndex,
|
|
566
|
+
collection,
|
|
567
|
+
recentImages,
|
|
574
568
|
limiter,
|
|
575
569
|
sensitive,
|
|
576
570
|
outbound,
|
|
@@ -656,15 +650,24 @@ export default Plugin.define({
|
|
|
656
650
|
for (const name of Object.keys(event.tools)) delete event.tools[name]
|
|
657
651
|
return
|
|
658
652
|
}
|
|
659
|
-
//
|
|
653
|
+
// 日记总结会话的输入是群友可控的聊天记录,同样不带任何工具;
|
|
654
|
+
// 但它仍是一轮正常对话,先注入角色设定,日记才有人格。
|
|
660
655
|
if (await diarySummarizer.isSummarySession(event.sessionID)) {
|
|
656
|
+
// 人格取日记范围那条私聊(owner 私聊)上的覆盖,没有覆盖就用默认档。
|
|
657
|
+
const scope = diaryScopeChat(config)
|
|
658
|
+
const override = scope ? await overrides.for(scope) : undefined
|
|
659
|
+
const soul = await souls.at(override?.soulPath, override?.soulName)
|
|
660
|
+
// 只注入角色设定正文:`soul.prompt` 还带着「必须调用 qq_send_message」
|
|
661
|
+
// 的 QQ 守则,而总结会话没有任何工具,带上会让模型无所适从。
|
|
662
|
+
const persona = soul.text.trim()
|
|
663
|
+
if (persona) event.system.push({ type: "text", text: persona })
|
|
661
664
|
for (const name of Object.keys(event.tools)) delete event.tools[name]
|
|
662
665
|
}
|
|
663
666
|
return
|
|
664
667
|
}
|
|
665
|
-
//
|
|
668
|
+
// 角色设定可以按聊天覆盖:先看覆盖里写的 soulPath / soulName,没有就用默认档。
|
|
666
669
|
const override = await overrides.for(target)
|
|
667
|
-
const soul = await souls.at(override.
|
|
670
|
+
const soul = await souls.at(override.soulPath, override.soulName)
|
|
668
671
|
event.system.push({ type: "text", text: soul.prompt })
|
|
669
672
|
event.system.push({ type: "text", text: `当前时间:${currentTimeText()}` })
|
|
670
673
|
const active = manager.activeTurn(event.sessionID)
|
|
@@ -842,6 +845,8 @@ export default Plugin.define({
|
|
|
842
845
|
const renderCtx = renderContext(target, selfId)
|
|
843
846
|
const rendered = await renderMessage(renderCtx, event)
|
|
844
847
|
if (!rendered.text.trim()) return
|
|
848
|
+
// 记下这张消息里的图片:收藏表情时从中挑最近收到的那张动图。
|
|
849
|
+
await recentImages.record(target, rendered.files, String(event.message_id))
|
|
845
850
|
|
|
846
851
|
const senderRole = roleOf(config, String(event.user_id))
|
|
847
852
|
const userName = await resolveUserName(renderCtx, String(event.user_id))
|
package/src/keepalive.ts
CHANGED
|
@@ -10,6 +10,20 @@ export const KEEP_ALIVE_SESSION_KEY = "keepalive-session"
|
|
|
10
10
|
export const KEEP_ALIVE_SESSION_MARKER = "qqKeepAliveSession"
|
|
11
11
|
/** 保活会话标题。 */
|
|
12
12
|
export const KEEP_ALIVE_TITLE = "QQ 保活"
|
|
13
|
+
/** 上游表示“会话不存在”的错误名。 */
|
|
14
|
+
const SESSION_NOT_FOUND = "Session.NotFoundError"
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 判断错误是不是上游的“会话不存在”。
|
|
18
|
+
*
|
|
19
|
+
* 上游的 Session.NotFoundError 没有 message,只有 name 和 _tag,
|
|
20
|
+
* 所以只能靠名字判断,不然日志里只剩一段没有内容的栈。
|
|
21
|
+
*/
|
|
22
|
+
function isSessionNotFound(error: unknown): boolean {
|
|
23
|
+
if (typeof error !== "object" || error === null) return false
|
|
24
|
+
const candidate = error as { name?: unknown; _tag?: unknown }
|
|
25
|
+
return candidate.name === SESSION_NOT_FOUND || candidate._tag === SESSION_NOT_FOUND
|
|
26
|
+
}
|
|
13
27
|
|
|
14
28
|
/**
|
|
15
29
|
* 保活心跳:让 OpenCode 不要因为长时间没有会话活动而卸载插件。
|
|
@@ -84,7 +98,13 @@ export class KeepAlive {
|
|
|
84
98
|
const info = await this.ctx.session.get({ sessionID })
|
|
85
99
|
metadata = info?.metadata ?? { [KEEP_ALIVE_SESSION_MARKER]: true }
|
|
86
100
|
} catch (error) {
|
|
87
|
-
|
|
101
|
+
if (isSessionNotFound(error)) {
|
|
102
|
+
// 会话已经被删掉了:当场重建,不等下一个心跳。
|
|
103
|
+
this.logger.warn(`保活会话 ${sessionID} 已不存在,正在重建`)
|
|
104
|
+
await this.rebuild(sessionID)
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
// 会话暂时读不出来:丢掉缓存,下一次心跳重建一个。
|
|
88
108
|
this.logger.warn("保活会话已失效,将重建", error)
|
|
89
109
|
this.sessionID = undefined
|
|
90
110
|
return
|
|
@@ -94,10 +114,38 @@ export class KeepAlive {
|
|
|
94
114
|
await this.ctx.session.update({ sessionID, metadata })
|
|
95
115
|
this.logger.debug(`保活心跳已刷新会话 ${sessionID}`)
|
|
96
116
|
} catch (error) {
|
|
117
|
+
if (isSessionNotFound(error)) {
|
|
118
|
+
this.logger.warn(`保活会话 ${sessionID} 已不存在,正在重建`)
|
|
119
|
+
await this.rebuild(sessionID)
|
|
120
|
+
return
|
|
121
|
+
}
|
|
97
122
|
this.logger.warn("保活心跳失败", error)
|
|
98
123
|
}
|
|
99
124
|
}
|
|
100
125
|
|
|
126
|
+
/**
|
|
127
|
+
* 保活会话已经不存在时的重建。
|
|
128
|
+
*
|
|
129
|
+
* 不当场重建的话要等到下一个心跳才补上,这段时间里插件可能被 OpenCode 当成空闲卸载,
|
|
130
|
+
* 保活也就失效了,所以当场重建并刷新一次元数据。
|
|
131
|
+
*/
|
|
132
|
+
private async rebuild(staleSessionID: string): Promise<void> {
|
|
133
|
+
this.sessionID = undefined
|
|
134
|
+
await this.clearStoredSession(staleSessionID)
|
|
135
|
+
try {
|
|
136
|
+
const sessionID = await this.resolveSession()
|
|
137
|
+
if (this.stopped) return
|
|
138
|
+
const info = await this.ctx.session.get({ sessionID })
|
|
139
|
+
await this.ctx.session.update({
|
|
140
|
+
sessionID,
|
|
141
|
+
metadata: info?.metadata ?? { [KEEP_ALIVE_SESSION_MARKER]: true },
|
|
142
|
+
})
|
|
143
|
+
this.logger.debug(`保活心跳已刷新会话 ${sessionID}`)
|
|
144
|
+
} catch (error) {
|
|
145
|
+
this.logger.warn("重建保活会话失败", error)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
101
149
|
/** 取得(必要时创建)保活会话;并发调用串行执行,避免重复建会话。 */
|
|
102
150
|
private async ensureSession(): Promise<string> {
|
|
103
151
|
if (this.sessionID) return this.sessionID
|
|
@@ -143,6 +191,10 @@ export class KeepAlive {
|
|
|
143
191
|
try {
|
|
144
192
|
await this.ctx.session.update({ sessionID, archived: true })
|
|
145
193
|
} catch (error) {
|
|
194
|
+
if (isSessionNotFound(error)) {
|
|
195
|
+
this.logger.debug(`保活会话 ${sessionID} 已不存在,跳过归档`)
|
|
196
|
+
return
|
|
197
|
+
}
|
|
146
198
|
this.logger.debug("归档保活会话失败", error)
|
|
147
199
|
return
|
|
148
200
|
}
|
|
@@ -160,8 +212,9 @@ export class KeepAlive {
|
|
|
160
212
|
|
|
161
213
|
/** 读取上次保存的保活会话;会话已经不存在或属于别的目录时返回 undefined。 */
|
|
162
214
|
private async readStoredSession(): Promise<string | undefined> {
|
|
215
|
+
let stored: unknown
|
|
163
216
|
try {
|
|
164
|
-
|
|
217
|
+
stored = await this.ctx.storage.get(KEEP_ALIVE_SESSION_KEY)
|
|
165
218
|
if (typeof stored !== "string" || stored.length === 0) return undefined
|
|
166
219
|
const info = await this.ctx.session.get({ sessionID: stored })
|
|
167
220
|
// 插件存储是机器级共享的,别的目录留下的会话不能拿来用。
|
|
@@ -171,6 +224,11 @@ export class KeepAlive {
|
|
|
171
224
|
}
|
|
172
225
|
return stored
|
|
173
226
|
} catch (error) {
|
|
227
|
+
if (isSessionNotFound(error)) {
|
|
228
|
+
this.logger.debug(`存储里的保活会话 ${String(stored)} 已不存在,将新建会话`)
|
|
229
|
+
await this.clearStoredSession(String(stored))
|
|
230
|
+
return undefined
|
|
231
|
+
}
|
|
174
232
|
this.logger.debug("读取保活会话失败,将新建会话", error)
|
|
175
233
|
return undefined
|
|
176
234
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { QQBotConfig } from "./config"
|
|
2
|
+
import { collectEnvSecrets, secretsFromUrl } from "./sensitive"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 已知凭证明文:日志逐行打码与出站拦截都靠它。
|
|
6
|
+
*
|
|
7
|
+
* 除了环境变量与 NapCat 令牌,地址查询串里挂着的 token 也要算进来,
|
|
8
|
+
* 否则它会原样落进日志文件。面板令牌同样算进来:它能进日志文件就等于面板失守。
|
|
9
|
+
*
|
|
10
|
+
* 单独成模块是为了让面板也能用:面板不需要把整个插件入口拉进来。
|
|
11
|
+
*/
|
|
12
|
+
export function knownSecrets(config: QQBotConfig): string[] {
|
|
13
|
+
return [
|
|
14
|
+
...collectEnvSecrets(process.env),
|
|
15
|
+
config.napcat.token ?? "",
|
|
16
|
+
// 面板令牌能进日志文件就等于面板失守,日志里一律掩码。
|
|
17
|
+
config.panel.token ?? "",
|
|
18
|
+
...secretsFromUrl(config.napcat.url),
|
|
19
|
+
].filter((secret) => secret.length > 0)
|
|
20
|
+
}
|
package/src/logger.ts
CHANGED
|
@@ -181,7 +181,8 @@ function normalizeValue(value: unknown, depth: number): unknown {
|
|
|
181
181
|
if (value instanceof Error) {
|
|
182
182
|
return {
|
|
183
183
|
name: value.name,
|
|
184
|
-
|
|
184
|
+
// 有些上游错误(例如 opencode 的 Session.NotFoundError)没有 message,只能用名字顶上。
|
|
185
|
+
message: value.message || value.name,
|
|
185
186
|
stack: value.stack ? value.stack.replace(/\s*\n\s*/g, " ") : undefined,
|
|
186
187
|
}
|
|
187
188
|
}
|