@cmach_socket/opencode-qq-bot 0.6.8 → 0.8.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.
@@ -0,0 +1,180 @@
1
+ import { Mutex } from "async-mutex"
2
+ import { isTargetAllowed } from "../access"
3
+ import { type ChatTarget, targetKey, targetLabel } from "../chat"
4
+ import type { QQBotConfig } from "../config"
5
+ import type { Logger } from "../logger"
6
+ import type { OutboundMedia } from "../media-path"
7
+ import type { QQClient } from "../naplink/client"
8
+ import type { SendRateLimiter } from "../rate-limit"
9
+ import type { SensitiveChecker } from "../sensitive"
10
+ import { sendFileMessage, sendPlainMessage } from "../tools/qq"
11
+ import type { DiaryCollector } from "./collector"
12
+ import { dateKey } from "./format"
13
+ import { diaryScopeChat } from "./scope"
14
+ import { readDiaryHead, type DiaryStore } from "./store"
15
+ import type { DiarySummarizer } from "./summary"
16
+
17
+ /** 日记调度器的依赖。 */
18
+ export interface DiarySchedulerDeps {
19
+ config: QQBotConfig
20
+ logger: Logger
21
+ client: QQClient
22
+ limiter: SendRateLimiter
23
+ /** 出站媒体的路径把关,发送日记文件时用。 */
24
+ outbound: OutboundMedia
25
+ /** 出站敏感信息检查。 */
26
+ sensitive: SensitiveChecker
27
+ /** 日记读写。 */
28
+ store: DiaryStore
29
+ /** 素材读取。 */
30
+ collector: DiaryCollector
31
+ /** 自动总结。 */
32
+ summarizer: DiarySummarizer
33
+ }
34
+
35
+ /**
36
+ * 时刻转成当天第几分钟。
37
+ *
38
+ * 格式不对时按 0 处理:调度器会因此认为还没到点,不会误触发。
39
+ */
40
+ export function minutesOfDay(time: string): number {
41
+ const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(time.trim())
42
+ if (!match) return 0
43
+ const hour = Number(match[1])
44
+ const minute = Number(match[2])
45
+ if (!Number.isFinite(hour) || !Number.isFinite(minute)) return 0
46
+ return hour * 60 + minute
47
+ }
48
+
49
+ /**
50
+ * 定时生成当天的日记并推送。
51
+ *
52
+ * 定时器随插件一起卸载:要保证定时跑,需要
53
+ * `experimental.location_idle_timeout: false`。
54
+ */
55
+ export class DiaryScheduler {
56
+ private timer: ReturnType<typeof setInterval> | undefined
57
+ /** 整个调度只允许一个任务在跑。 */
58
+ private readonly mutex = new Mutex()
59
+ /** 正在生成中的聊天,同一聊天同一时刻只跑一个任务。 */
60
+ private readonly running = new Set<string>()
61
+
62
+ constructor(private readonly deps: DiarySchedulerDeps) {}
63
+
64
+ /** 开始轮询。 */
65
+ start(): void {
66
+ if (this.timer) return
67
+ const seconds = Math.max(60, this.deps.config.diary.tickSeconds)
68
+ this.timer = setInterval(() => {
69
+ void this.tick().catch((error: unknown) => this.deps.logger.error("日记调度失败", error))
70
+ }, seconds * 1000)
71
+ const handle = this.timer as { unref?: () => void }
72
+ handle.unref?.()
73
+ this.deps.logger.info(`日记调度已启动,轮询间隔 ${seconds} 秒`)
74
+ }
75
+
76
+ /** 停止轮询。 */
77
+ async dispose(): Promise<void> {
78
+ if (this.timer) {
79
+ clearInterval(this.timer)
80
+ this.timer = undefined
81
+ }
82
+ }
83
+
84
+ /**
85
+ * 跑一轮调度。
86
+ *
87
+ * 已经过了总结时刻、该聊天今天还没有自动日记时才动手;
88
+ * 当天没有素材就跳过,不调用模型也不推送。
89
+ */
90
+ async tick(now: Date = new Date()): Promise<void> {
91
+ if (!this.deps.config.diary.enabled) return
92
+ if (this.mutex.isLocked()) return
93
+ await this.mutex.runExclusive(async () => {
94
+ // 素材是中间产物,过期就清掉;日记成品不动。
95
+ await this.deps.collector.cleanup(this.deps.config.diary.retentionDays)
96
+ const target = minutesOfDay(this.deps.config.diary.summaryTime)
97
+ const current = now.getHours() * 60 + now.getMinutes()
98
+ if (current < target) return
99
+ const date = dateKey(now)
100
+ for (const chat of this.targets()) {
101
+ await this.runFor(chat, date)
102
+ }
103
+ })
104
+ }
105
+
106
+ /** 本轮要处理的目标聊天:日记只服务 owner 自己的私聊。 */
107
+ private targets(): ChatTarget[] {
108
+ const scope = diaryScopeChat(this.deps.config)
109
+ if (!scope) {
110
+ this.deps.logger.warn("没有配置 ownerQQ,日记不做总结也不推送")
111
+ return []
112
+ }
113
+ if (!isTargetAllowed(this.deps.config.access, scope, this.deps.config.ownerQQ)) return []
114
+ return [scope]
115
+ }
116
+
117
+ /** 为一个聊天生成当天的日记。 */
118
+ private async runFor(chat: ChatTarget, date: string): Promise<void> {
119
+ const key = targetKey(chat)
120
+ if (this.running.has(key)) return
121
+ if (await this.deps.store.hasAuto(key, date)) return
122
+ if (!(await this.deps.collector.has(key, date))) return
123
+ this.running.add(key)
124
+ try {
125
+ const title = await this.deps.summarizer.summarize(key, date)
126
+ if (!title) return
127
+ await this.push(chat, date)
128
+ } catch (error) {
129
+ this.deps.logger.error(`${targetLabel(chat)} 的日记生成失败`, error)
130
+ } finally {
131
+ this.running.delete(key)
132
+ }
133
+ }
134
+
135
+ /** 按配置推送日记产物。 */
136
+ private async push(chat: ChatTarget, date: string): Promise<void> {
137
+ const mode = this.deps.config.diary.push
138
+ if (mode === "none") return
139
+ const file = this.deps.store.filePath(targetKey(chat), date)
140
+ const owner = this.deps.config.ownerQQ
141
+ const toOwner = mode === "owner"
142
+ let target: ChatTarget = chat
143
+ if (toOwner) {
144
+ if (owner === undefined) {
145
+ this.deps.logger.warn("没有配置 ownerQQ,日记生成后不推送")
146
+ return
147
+ }
148
+ target = { kind: "private", id: owner }
149
+ }
150
+ const text = toOwner
151
+ ? `${targetLabel(chat)} ${date} 的日记已生成\n文件:${file}`
152
+ : `${date} 的日记已生成`
153
+ // 推送走插件自己的通道,不经过模型侧的出站检查,这里自己过一遍。
154
+ const verdict = this.deps.sensitive.check(text)
155
+ if (!verdict.allowed) {
156
+ this.deps.logger.warn(`${targetLabel(target)} 的日记推送包含敏感信息,已拦截`)
157
+ return
158
+ }
159
+ // 日记正文是模型写的,可能带进群友原文里的敏感信息;发文件前必须过一遍内容。
160
+ let body: string
161
+ try {
162
+ body = await readDiaryHead(file)
163
+ } catch (error) {
164
+ this.deps.logger.error(`${targetLabel(target)} 的日记文件读取失败,放弃推送`, error)
165
+ return
166
+ }
167
+ const bodyVerdict = this.deps.sensitive.check(body)
168
+ if (!bodyVerdict.allowed) {
169
+ this.deps.logger.warn(`${targetLabel(target)} 的日记正文包含敏感信息,已拦截`)
170
+ return
171
+ }
172
+ await sendFileMessage(this.deps.client, target, file, {
173
+ name: `日记-${date}.md`,
174
+ limiter: this.deps.limiter,
175
+ outbound: this.deps.outbound,
176
+ sensitive: this.deps.sensitive,
177
+ })
178
+ await sendPlainMessage(this.deps.client, target, text, { limiter: this.deps.limiter })
179
+ }
180
+ }
@@ -0,0 +1,27 @@
1
+ import { type ChatTarget, targetKey } from "../chat"
2
+ import type { QQBotConfig } from "../config"
3
+
4
+ /**
5
+ * 日记的范围:只有 owner 与机器人的那条私聊。
6
+ *
7
+ * 维护者裁定(日记范围收窄到 owner 的会话):
8
+ * 采集、总结、工具、命令与推送都只认这一条会话,
9
+ * 剩下的会话一旦只有一条,跨聊天串档的前提就不存在了。
10
+ */
11
+ export function diaryScopeChat(config: QQBotConfig): ChatTarget | undefined {
12
+ if (config.ownerQQ === undefined) return undefined
13
+ return { kind: "private", id: config.ownerQQ }
14
+ }
15
+
16
+ /** 日记范围的会话键;没有配置 owner 时返回 undefined。 */
17
+ export function diaryScopeKey(config: QQBotConfig): string | undefined {
18
+ const chat = diaryScopeChat(config)
19
+ return chat ? targetKey(chat) : undefined
20
+ }
21
+
22
+ /** 某个聊天是否在日记范围内。 */
23
+ export function isDiaryScopeChat(config: QQBotConfig, target: ChatTarget): boolean {
24
+ const scope = diaryScopeChat(config)
25
+ if (!scope) return false
26
+ return scope.kind === target.kind && scope.id === target.id
27
+ }
@@ -0,0 +1,188 @@
1
+ import { mkdir, open, readFile, readdir, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import type { Logger } from "../logger"
4
+ import {
5
+ chatSlug,
6
+ dateKey,
7
+ diaryFileName,
8
+ fallbackTitle,
9
+ isDateKey,
10
+ parseDiary,
11
+ serializeDiary,
12
+ type DiaryEntry,
13
+ type DiarySource,
14
+ } from "./format"
15
+ import { isInside, realDir, realExisting } from "./paths"
16
+
17
+ /** 日记正文扫描时最多读这么多字节。 */
18
+ export const DIARY_SCAN_BYTES = 4096
19
+
20
+ /**
21
+ * 读取日记文件开头的一段,用于出站敏感信息扫描。
22
+ *
23
+ * 只读开头:日记正文有长度上限,4KB 足够覆盖一篇完整的日记。
24
+ */
25
+ export async function readDiaryHead(file: string, maxBytes = DIARY_SCAN_BYTES): Promise<string> {
26
+ const handle = await open(file, "r")
27
+ try {
28
+ const buffer = Buffer.alloc(maxBytes)
29
+ const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0)
30
+ return buffer.subarray(0, bytesRead).toString("utf8")
31
+ } finally {
32
+ await handle.close()
33
+ }
34
+ }
35
+
36
+ /** 日记列表里的摘要:只要日期与标题,不带正文。 */
37
+ export interface DiarySummary {
38
+ /** 日期键。 */
39
+ date: string
40
+ /** 标题。 */
41
+ title: string
42
+ /** 来源。 */
43
+ source: DiarySource
44
+ }
45
+
46
+ /** 日记存储的依赖。 */
47
+ export interface DiaryStoreDeps {
48
+ /** 日记根目录。 */
49
+ root: string
50
+ logger: Logger
51
+ }
52
+
53
+ /**
54
+ * 日记的读写。
55
+ *
56
+ * 日记是文件而不是数据库条目:一个聊天一个目录,一天一个文件。
57
+ * 成品不设条数上限,也不自动清理。
58
+ */
59
+ export class DiaryStore {
60
+ constructor(private readonly deps: DiaryStoreDeps) {}
61
+
62
+ /** 某个聊天的日记目录。 */
63
+ chatDir(chat: string): string {
64
+ return join(this.deps.root, chatSlug(chat))
65
+ }
66
+
67
+ /** 某篇日记的文件路径。 */
68
+ filePath(chat: string, date: string): string {
69
+ return join(this.chatDir(chat), diaryFileName(date))
70
+ }
71
+
72
+ /**
73
+ * 读一篇日记。
74
+ *
75
+ * 文件不存在或读不出来都按「没有日记」处理,不缓存失败结果。
76
+ */
77
+ async read(chat: string, date: string): Promise<DiaryEntry | undefined> {
78
+ if (!isDateKey(date)) {
79
+ this.deps.logger.warn(`${chat} 的日记日期不合法:${date}`)
80
+ return undefined
81
+ }
82
+ const root = await realDir(this.deps.root)
83
+ const file = await realExisting(this.filePath(chat, date))
84
+ if (!file) return undefined
85
+ if (!isInside(root, file)) {
86
+ this.deps.logger.warn(`${chat} ${date} 的日记路径落在日记目录之外,拒绝读取`)
87
+ return undefined
88
+ }
89
+ let content: string
90
+ try {
91
+ content = await readFile(file, "utf8")
92
+ } catch {
93
+ return undefined
94
+ }
95
+ const parsed = parseDiary(content)
96
+ if (!parsed) {
97
+ this.deps.logger.warn(`${chat} ${date} 的日记格式无法解析,按没有日记处理`)
98
+ return undefined
99
+ }
100
+ return {
101
+ ...parsed.meta,
102
+ date: parsed.meta.date || date,
103
+ chat: parsed.meta.chat || chat,
104
+ title: parsed.title,
105
+ body: parsed.body,
106
+ }
107
+ }
108
+
109
+ /**
110
+ * 写入一篇日记,同一天同一聊天只保留一篇。
111
+ *
112
+ * `created` 在首次写入时定下,覆盖写保持不变;`updated` 每次刷新。
113
+ */
114
+ async write(
115
+ chat: string,
116
+ date: string,
117
+ input: { title: string; body: string; source: DiarySource },
118
+ ): Promise<DiaryEntry> {
119
+ if (!isDateKey(date)) throw new Error(`日期格式不对:${date}`)
120
+ const dir = this.chatDir(chat)
121
+ // 目录与文件都显式收紧权限:日记里是私聊原文,不能沿用 umask 的默认值。
122
+ await mkdir(dir, { recursive: true, mode: 0o700 })
123
+ const root = await realDir(this.deps.root)
124
+ const realDirectory = await realExisting(dir)
125
+ if (!realDirectory || !isInside(root, realDirectory)) {
126
+ throw new Error(`日记目录不在日记根目录内:${dir}`)
127
+ }
128
+ const file = this.filePath(chat, date)
129
+ const realFile = await realExisting(file)
130
+ if (realFile && !isInside(root, realFile)) {
131
+ throw new Error(`日记文件不在日记根目录内:${file}`)
132
+ }
133
+ const existing = await this.read(chat, date)
134
+ const now = new Date().toISOString()
135
+ const entry: DiaryEntry = {
136
+ date,
137
+ chat,
138
+ source: input.source,
139
+ created: existing?.created || now,
140
+ updated: now,
141
+ title: input.title.trim() || fallbackTitle(date),
142
+ body: input.body.trim(),
143
+ }
144
+ await writeFile(file, serializeDiary(entry), { encoding: "utf8", mode: 0o600 })
145
+ return entry
146
+ }
147
+
148
+ /**
149
+ * 列出最近的日记,按日期倒序。
150
+ *
151
+ * 只扫目录名,不读全部内容:文件名本身就是日期键。
152
+ */
153
+ async list(chat: string, limit: number): Promise<DiarySummary[]> {
154
+ const names = await readdir(this.chatDir(chat)).catch(() => [] as string[])
155
+ const dates = names
156
+ .map((name) => /^(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1])
157
+ .filter((value): value is string => Boolean(value))
158
+ .sort()
159
+ .reverse()
160
+ .slice(0, Math.max(0, limit))
161
+ const summaries: DiarySummary[] = []
162
+ for (const date of dates) {
163
+ const entry = await this.read(chat, date)
164
+ if (!entry) continue
165
+ summaries.push({ date: entry.date, title: entry.title, source: entry.source })
166
+ }
167
+ return summaries
168
+ }
169
+
170
+ /** 最近的一篇日记。 */
171
+ async latest(chat: string): Promise<DiaryEntry | undefined> {
172
+ const summaries = await this.list(chat, 1)
173
+ const first = summaries[0]
174
+ if (!first) return undefined
175
+ return await this.read(chat, first.date)
176
+ }
177
+
178
+ /** 某天是否已经有自动生成的日记。 */
179
+ async hasAuto(chat: string, date: string): Promise<boolean> {
180
+ const entry = await this.read(chat, date)
181
+ return entry?.source === "auto"
182
+ }
183
+
184
+ /** 今天的日期键。 */
185
+ today(): string {
186
+ return dateKey()
187
+ }
188
+ }