@cmach_socket/opencode-qq-bot 0.7.0 → 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.
@@ -1,4 +1,4 @@
1
- import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"
1
+ import { mkdir, open, readFile, readdir, writeFile } from "node:fs/promises"
2
2
  import { join } from "node:path"
3
3
  import type { Logger } from "../logger"
4
4
  import {
@@ -6,11 +6,32 @@ import {
6
6
  dateKey,
7
7
  diaryFileName,
8
8
  fallbackTitle,
9
+ isDateKey,
9
10
  parseDiary,
10
11
  serializeDiary,
11
12
  type DiaryEntry,
12
13
  type DiarySource,
13
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
+ }
14
35
 
15
36
  /** 日记列表里的摘要:只要日期与标题,不带正文。 */
16
37
  export interface DiarySummary {
@@ -54,9 +75,20 @@ export class DiaryStore {
54
75
  * 文件不存在或读不出来都按「没有日记」处理,不缓存失败结果。
55
76
  */
56
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
+ }
57
89
  let content: string
58
90
  try {
59
- content = await readFile(this.filePath(chat, date), "utf8")
91
+ content = await readFile(file, "utf8")
60
92
  } catch {
61
93
  return undefined
62
94
  }
@@ -84,8 +116,20 @@ export class DiaryStore {
84
116
  date: string,
85
117
  input: { title: string; body: string; source: DiarySource },
86
118
  ): Promise<DiaryEntry> {
119
+ if (!isDateKey(date)) throw new Error(`日期格式不对:${date}`)
87
120
  const dir = this.chatDir(chat)
88
- await mkdir(dir, { recursive: true })
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
+ }
89
133
  const existing = await this.read(chat, date)
90
134
  const now = new Date().toISOString()
91
135
  const entry: DiaryEntry = {
@@ -97,7 +141,7 @@ export class DiaryStore {
97
141
  title: input.title.trim() || fallbackTitle(date),
98
142
  body: input.body.trim(),
99
143
  }
100
- await writeFile(this.filePath(chat, date), serializeDiary(entry), "utf8")
144
+ await writeFile(file, serializeDiary(entry), { encoding: "utf8", mode: 0o600 })
101
145
  return entry
102
146
  }
103
147
 
@@ -1,5 +1,6 @@
1
1
  import type { Plugin } from "@opencode/plugin"
2
2
  import type { Location } from "@opencode/schema"
3
+ import { Mutex } from "async-mutex"
3
4
  import { delay, unrefTimer } from "../async"
4
5
  import type { QQBotConfig } from "../config"
5
6
  import type { BotHome } from "../home"
@@ -7,6 +8,7 @@ import type { Logger } from "../logger"
7
8
  import { neutralizeStructureTags, sanitizeUntrustedText } from "../model-view"
8
9
  import { toPlainText } from "../outbound"
9
10
  import { findSession } from "../session/find"
11
+ import { softTruncate } from "../text"
10
12
  import type { DiaryCollector, DiaryLine } from "./collector"
11
13
  import { fallbackTitle } from "./format"
12
14
  import type { DiaryStore } from "./store"
@@ -34,8 +36,11 @@ export function buildDiaryPrompt(date: string, lines: readonly DiaryLine[]): str
34
36
  const body = lines
35
37
  .map((line) => {
36
38
  const stamp = formatClock(line.time)
37
- const name = sanitizeUntrustedText(line.name).trim() || "某人"
38
- const text = neutralizeStructureTags(sanitizeUntrustedText(line.text)).trim()
39
+ // 机器人自己的行固定署「机器人」,并去掉 @QQ 号:
40
+ // 提示词第 4 条要求不出现 QQ 号,自己的 @ 又没有信息量。
41
+ const name = line.self ? "机器人" : sanitizeUntrustedText(line.name).trim() || "某人"
42
+ const raw = neutralizeStructureTags(sanitizeUntrustedText(line.text)).trim()
43
+ const text = line.self ? raw.replace(/@\d+/g, "@某人").trim() : raw
39
44
  return `[${stamp}] ${name}:${text}`
40
45
  })
41
46
  .join("\n")
@@ -78,7 +83,7 @@ export function cleanDiarySummary(raw: string): { title: string; body: string }
78
83
  if (!plain) return undefined
79
84
  const lines = plain.split("\n")
80
85
  const titleLine = (lines[0] ?? "").trim()
81
- const title = Array.from(titleLine).slice(0, DIARY_TITLE_MAX_CHARS).join("")
86
+ const title = softTruncate(titleLine, DIARY_TITLE_MAX_CHARS)
82
87
  const body = lines
83
88
  .slice(1)
84
89
  .map((line) => line.trim())
@@ -88,7 +93,7 @@ export function cleanDiarySummary(raw: string): { title: string; body: string }
88
93
  if (!body) return undefined
89
94
  return {
90
95
  title: title || fallbackTitle(""),
91
- body: Array.from(body).slice(0, DIARY_BODY_MAX_CHARS).join(""),
96
+ body: softTruncate(body, DIARY_BODY_MAX_CHARS),
92
97
  }
93
98
  }
94
99
 
@@ -122,6 +127,10 @@ export class DiarySummarizer {
122
127
  private listener: Promise<void> | undefined
123
128
  private sessionID: string | undefined
124
129
  private creating: Promise<string> | undefined
130
+ /** 同一时间只跑一个总结:全局总结会话的缓冲区不能同时承载两份素材。 */
131
+ private readonly mutex = new Mutex()
132
+ /** 同一聊天同一天的总结只跑一次;两个入口同时来的时候共享同一个结果。 */
133
+ private readonly inflight = new Map<string, Promise<string | undefined>>()
125
134
 
126
135
  constructor(private readonly deps: DiarySummarizerDeps) {}
127
136
 
@@ -147,7 +156,8 @@ export class DiarySummarizer {
147
156
  const info = await this.deps.ctx.session.get({ sessionID })
148
157
  return info?.metadata?.[DIARY_SUMMARY_MARKER] === true
149
158
  } catch {
150
- return false
159
+ // 查不出来时按总结会话处理:它的输入是群友可控文本,工具必须摘掉。
160
+ return true
151
161
  }
152
162
  }
153
163
 
@@ -199,6 +209,8 @@ export class DiarySummarizer {
199
209
 
200
210
  /** 累加模型输出的一段文本;一轮回复可能拆成多段。 */
201
211
  private push(sessionID: string, text: string): void {
212
+ // 全局事件里夹着所有会话的输出,只留总结会话自己的。
213
+ if (this.sessionID !== sessionID) return
202
214
  const buffer = `${this.buffers.get(sessionID) ?? ""}${text}`
203
215
  this.buffers.set(sessionID, buffer)
204
216
  }
@@ -209,6 +221,7 @@ export class DiarySummarizer {
209
221
  if (!waiters || waiters.length === 0) return
210
222
  this.waiters.delete(sessionID)
211
223
  const text = this.buffers.get(sessionID) ?? ""
224
+ this.buffers.delete(sessionID)
212
225
  for (const resolve of waiters) resolve(text)
213
226
  }
214
227
 
@@ -217,6 +230,7 @@ export class DiarySummarizer {
217
230
  const waiters = this.waiters.get(sessionID)
218
231
  if (!waiters || waiters.length === 0) return
219
232
  this.waiters.delete(sessionID)
233
+ this.buffers.delete(sessionID)
220
234
  for (const resolve of waiters) resolve(undefined)
221
235
  }
222
236
 
@@ -325,6 +339,20 @@ export class DiarySummarizer {
325
339
  * @returns 写进去的日记;没有素材或总结失败时返回 undefined。
326
340
  */
327
341
  async summarize(chat: string, date: string): Promise<string | undefined> {
342
+ const key = `${chat}#${date}`
343
+ const existing = this.inflight.get(key)
344
+ if (existing) return existing
345
+ const run = this.mutex.runExclusive(() => this.runSummary(chat, date))
346
+ this.inflight.set(key, run)
347
+ try {
348
+ return await run
349
+ } finally {
350
+ this.inflight.delete(key)
351
+ }
352
+ }
353
+
354
+ /** 真正跑总结;同一时间只允许一个总结占用全局总结会话。 */
355
+ private async runSummary(chat: string, date: string): Promise<string | undefined> {
328
356
  if (this.abort.signal.aborted) return undefined
329
357
  const lines = await this.deps.collector.read(chat, date)
330
358
  if (lines.length === 0) {