@cmach_socket/opencode-qq-bot 0.7.0 → 0.9.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.
Files changed (51) hide show
  1. package/NOTICE +48 -15
  2. package/README.md +220 -115
  3. package/package.json +10 -1
  4. package/src/cleanup.ts +1 -0
  5. package/src/commands.ts +2 -0
  6. package/src/config/fields.ts +780 -0
  7. package/src/config/live.ts +161 -0
  8. package/src/config/registry.ts +654 -0
  9. package/src/config/store.ts +175 -0
  10. package/src/config/types.ts +253 -0
  11. package/src/config.ts +77 -1023
  12. package/src/diary/collector.ts +28 -14
  13. package/src/diary/command.ts +24 -2
  14. package/src/diary/paths.ts +27 -0
  15. package/src/diary/scheduler.ts +63 -14
  16. package/src/diary/scope.ts +27 -0
  17. package/src/diary/store.ts +48 -4
  18. package/src/diary/summary.ts +33 -5
  19. package/src/home.ts +11 -16
  20. package/src/index.ts +777 -644
  21. package/src/logger.ts +104 -1
  22. package/src/model-view.ts +3 -1
  23. package/src/naplink/client.ts +16 -0
  24. package/src/panel/api.ts +345 -0
  25. package/src/panel/auth.ts +65 -0
  26. package/src/panel/models.ts +56 -0
  27. package/src/panel/runtime.ts +51 -0
  28. package/src/panel/server.ts +185 -0
  29. package/src/panel/status.ts +201 -0
  30. package/src/rate-limit.ts +46 -0
  31. package/src/runtime/claim.ts +37 -0
  32. package/src/runtime/start.ts +55 -0
  33. package/src/sensitive.ts +6 -1
  34. package/src/session/find.ts +44 -10
  35. package/src/session/manager.ts +118 -19
  36. package/src/session/prompt.ts +1 -1
  37. package/src/text.ts +34 -0
  38. package/src/tools/policy.ts +16 -1
  39. package/src/tools/qq.ts +90 -38
  40. package/src/tools/send-guard.ts +2 -2
  41. package/src/tui-commands.ts +1 -1
  42. package/web/dist/assets/index-7eMQEM7-.css +1 -0
  43. package/web/dist/assets/index-DCkgUY7y.js +15 -0
  44. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  45. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  46. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  47. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  48. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  49. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  50. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  51. package/web/dist/index.html +13 -0
@@ -1,7 +1,9 @@
1
1
  import { appendFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises"
2
2
  import { join } from "node:path"
3
3
  import type { Logger } from "../logger"
4
+ import { softTruncate } from "../text"
4
5
  import { chatSlug, dateKey } from "./format"
6
+ import { isInside, realDir, realExisting } from "./paths"
5
7
 
6
8
  /**
7
9
  * 一行聊天素材。
@@ -25,6 +27,16 @@ export interface DiaryLine {
25
27
  backfilled: boolean
26
28
  }
27
29
 
30
+ /**
31
+ * 这条消息是不是机器人自己发的。
32
+ *
33
+ * 自己的发言也要进素材:日记写的是当天发生了什么,
34
+ * 只有模型说话那部分,模型自己看不到。
35
+ */
36
+ export function isSelfSpeaker(userId: string, selfId: string): boolean {
37
+ return Boolean(selfId) && userId === selfId
38
+ }
39
+
28
40
  /** 素材收集器的依赖。 */
29
41
  export interface DiaryCollectorDeps {
30
42
  /** 日记根目录,素材放在它下面的 `raw/` 子目录里。 */
@@ -39,17 +51,6 @@ export interface DiaryCollectorDeps {
39
51
  /** 素材文件名的形状。 */
40
52
  const RAW_FILE = /^(\d{4}-\d{2}-\d{2})\.jsonl$/
41
53
 
42
- /**
43
- * 按码点截断。
44
- *
45
- * 按码点而不是 UTF-16 码元截:emoji 不会被切成半个。
46
- */
47
- export function truncateChars(value: string, max: number): string {
48
- const chars = Array.from(value)
49
- if (chars.length <= max) return value
50
- return chars.slice(0, max).join("")
51
- }
52
-
53
54
  /**
54
55
  * 聊天素材的累积与落盘。
55
56
  *
@@ -93,10 +94,23 @@ export class DiaryCollector {
93
94
  )
94
95
  return false
95
96
  }
96
- const record: DiaryLine = { ...line, text: truncateChars(line.text, this.deps.maxLineChars) }
97
+ const record: DiaryLine = { ...line, text: softTruncate(line.text, this.deps.maxLineChars) }
97
98
  try {
98
- await mkdir(this.rawDir(chat), { recursive: true })
99
- await appendFile(this.rawFile(chat, date), `${JSON.stringify(record)}\n`, "utf8")
99
+ const dir = this.rawDir(chat)
100
+ await mkdir(dir, { recursive: true, mode: 0o700 })
101
+ const root = await realDir(this.deps.root)
102
+ const realDirectory = await realExisting(dir)
103
+ if (!realDirectory || !isInside(root, realDirectory)) {
104
+ this.deps.logger.warn(`${chat} 的素材目录不在日记根目录内,拒绝写入`)
105
+ return false
106
+ }
107
+ const file = this.rawFile(chat, date)
108
+ const realFile = await realExisting(file)
109
+ if (realFile && !isInside(root, realFile)) {
110
+ this.deps.logger.warn(`${chat} ${date} 的素材文件不在日记根目录内,拒绝写入`)
111
+ return false
112
+ }
113
+ await appendFile(file, `${JSON.stringify(record)}\n`, { encoding: "utf8", mode: 0o600 })
100
114
  } catch (error) {
101
115
  this.deps.logger.warn(`${chat} ${date} 的日记素材写入失败`, error)
102
116
  return false
@@ -9,7 +9,8 @@ import type { SensitiveChecker } from "../sensitive"
9
9
  import { createPlainSender, sendFileMessage } from "../tools/qq"
10
10
  import type { DiaryCollector } from "./collector"
11
11
  import { dateKey, isDateKey } from "./format"
12
- import type { DiaryStore } from "./store"
12
+ import { diaryScopeChat, isDiaryScopeChat } from "./scope"
13
+ import { readDiaryHead, type DiaryStore } from "./store"
13
14
  import type { DiarySummarizer } from "./summary"
14
15
 
15
16
  /** 命令名。TUI 侧注册为 `qq-diary`,QQ 私聊里用 `/diary`。 */
@@ -129,6 +130,20 @@ export function createDiaryRunner(deps: DiaryRunnerDeps): DiaryCommandRunner {
129
130
  /** 发一篇日记:一行说明加文件本身。 */
130
131
  const sendDiaryFile = async (target: ChatTarget, date: string): Promise<void> => {
131
132
  const file = store.filePath(targetKey(target), date)
133
+ // `sendFileMessage` 只查文件名和路径,日记正文得自己过一遍出站检查。
134
+ let body: string
135
+ try {
136
+ body = await readDiaryHead(file)
137
+ } catch (error) {
138
+ logger.error(`${targetLabel(target)} 的日记文件读取失败,放弃发送`, error)
139
+ await report(target, "日记文件读取失败,没有发送。")
140
+ return
141
+ }
142
+ if (!sensitive.check(body).allowed) {
143
+ logger.warn(`${targetLabel(target)} 的日记正文包含敏感信息,已拦截`)
144
+ await report(target, "日记正文包含敏感信息,已拦截。")
145
+ return
146
+ }
132
147
  await sendFileMessage(client, target, file, {
133
148
  name: `日记-${date}.md`,
134
149
  limiter,
@@ -271,7 +286,14 @@ export function diaryCommand(runner: DiaryCommandRunner): CommandDefinition {
271
286
  description: "写、看、列出聊天日记:write 手写,show 看某天,list 列最近几篇,auto 自动总结。",
272
287
  usage: DIARY_USAGE_LINES,
273
288
  run: async (context, args) => {
274
- await runner.run(context.target, args.join(" "))
289
+ // 日记只属于 owner:QQ 侧只认 owner 自己的私聊。
290
+ const scope = diaryScopeChat(context.config)
291
+ if (!scope) return "没有配置 ownerQQ,无法使用日记。"
292
+ if (context.source !== "tui" && !isDiaryScopeChat(context.config, context.target)) {
293
+ return "日记只在 owner 自己的私聊里可用。"
294
+ }
295
+ // TUI 侧同样按 owner 私聊操作:不能在绑到群聊的会话里把日记发进群里。
296
+ await runner.run(scope, args.join(" "))
275
297
  },
276
298
  }
277
299
  }
@@ -0,0 +1,27 @@
1
+ import { realpath } from "node:fs/promises"
2
+ import { isAbsolute, relative, resolve, sep } from "node:path"
3
+
4
+ /** 目录的真实路径;目录还不存在时退回解析后的词法路径。 */
5
+ export async function realDir(dir: string): Promise<string> {
6
+ try {
7
+ return await realpath(dir)
8
+ } catch {
9
+ return resolve(dir)
10
+ }
11
+ }
12
+
13
+ /** 已存在路径的真实路径;不存在或读不到时返回 undefined。 */
14
+ export async function realExisting(path: string): Promise<string | undefined> {
15
+ try {
16
+ return await realpath(path)
17
+ } catch {
18
+ return undefined
19
+ }
20
+ }
21
+
22
+ /** 目标是否在根目录之内,按目录边界判定,`/data/a` 不会命中 `/data/ab`。 */
23
+ export function isInside(root: string, target: string): boolean {
24
+ const rel = relative(root, target)
25
+ if (rel === "") return true
26
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
27
+ }
@@ -1,6 +1,6 @@
1
1
  import { Mutex } from "async-mutex"
2
- import { allowedTargets, isTargetAllowed } from "../access"
3
- import { type ChatTarget, parseTargetKey, targetKey, targetLabel } from "../chat"
2
+ import { isTargetAllowed } from "../access"
3
+ import { type ChatTarget, targetKey, targetLabel } from "../chat"
4
4
  import type { QQBotConfig } from "../config"
5
5
  import type { Logger } from "../logger"
6
6
  import type { OutboundMedia } from "../media-path"
@@ -10,7 +10,8 @@ import type { SensitiveChecker } from "../sensitive"
10
10
  import { sendFileMessage, sendPlainMessage } from "../tools/qq"
11
11
  import type { DiaryCollector } from "./collector"
12
12
  import { dateKey } from "./format"
13
- import type { DiaryStore } from "./store"
13
+ import { diaryScopeChat } from "./scope"
14
+ import { readDiaryHead, type DiaryStore } from "./store"
14
15
  import type { DiarySummarizer } from "./summary"
15
16
 
16
17
  /** 日记调度器的依赖。 */
@@ -57,9 +58,39 @@ export class DiaryScheduler {
57
58
  private readonly mutex = new Mutex()
58
59
  /** 正在生成中的聊天,同一聊天同一时刻只跑一个任务。 */
59
60
  private readonly running = new Set<string>()
61
+ /** 上一次调度的时间(毫秒)。 */
62
+ private lastTick: number | undefined
63
+ /** 上一次调度结果的说明。 */
64
+ private lastOutcome = ""
60
65
 
61
66
  constructor(private readonly deps: DiarySchedulerDeps) {}
62
67
 
68
+ /** 下次轮询的时间(毫秒);还没跑过就是 undefined。 */
69
+ nextRunAt(): number | undefined {
70
+ if (this.lastTick === undefined) return undefined
71
+ const seconds = Math.max(60, this.deps.config.diary.tickSeconds)
72
+ return this.lastTick + seconds * 1000
73
+ }
74
+
75
+ /** 上次轮询的时间(毫秒)。 */
76
+ lastRunAt(): number | undefined {
77
+ return this.lastTick
78
+ }
79
+
80
+ /** 下次总结时刻(毫秒):按配置里的时刻算,今天过了就顺延到明天。 */
81
+ nextSummaryAt(now: Date = new Date()): number {
82
+ const minutes = minutesOfDay(this.deps.config.diary.summaryTime)
83
+ const target = new Date(now)
84
+ target.setHours(Math.floor(minutes / 60), minutes % 60, 0, 0)
85
+ if (target.getTime() <= now.getTime()) target.setDate(target.getDate() + 1)
86
+ return target.getTime()
87
+ }
88
+
89
+ /** 上次轮询结果的说明。 */
90
+ lastResult(): string {
91
+ return this.lastOutcome
92
+ }
93
+
63
94
  /** 开始轮询。 */
64
95
  start(): void {
65
96
  if (this.timer) return
@@ -90,30 +121,35 @@ export class DiaryScheduler {
90
121
  if (!this.deps.config.diary.enabled) return
91
122
  if (this.mutex.isLocked()) return
92
123
  await this.mutex.runExclusive(async () => {
124
+ this.lastTick = now.getTime()
93
125
  // 素材是中间产物,过期就清掉;日记成品不动。
94
126
  await this.deps.collector.cleanup(this.deps.config.diary.retentionDays)
95
127
  const target = minutesOfDay(this.deps.config.diary.summaryTime)
96
128
  const current = now.getHours() * 60 + now.getMinutes()
97
- if (current < target) return
129
+ if (current < target) {
130
+ this.lastOutcome = `未到总结时刻(${this.deps.config.diary.summaryTime})`
131
+ return
132
+ }
98
133
  const date = dateKey(now)
134
+ let done = 0
99
135
  for (const chat of this.targets()) {
100
136
  await this.runFor(chat, date)
137
+ done += 1
101
138
  }
139
+ this.lastOutcome =
140
+ done > 0 ? `已检查 ${done} 个聊天(${date})` : `没有可总结的聊天(${date})`
102
141
  })
103
142
  }
104
143
 
105
- /** 本轮要处理的目标聊天。 */
144
+ /** 本轮要处理的目标聊天:日记只服务 owner 自己的私聊。 */
106
145
  private targets(): ChatTarget[] {
107
- const access = this.deps.config.access
108
- const owner = this.deps.config.ownerQQ
109
- const configured = this.deps.config.diary.summaryTargets
110
- .map((value) => parseTargetKey(value))
111
- .filter((value): value is ChatTarget => Boolean(value))
112
- if (configured.length > 0) {
113
- // 明确配了目标就只认这些,但仍然要过准入判定。
114
- return configured.filter((chat) => isTargetAllowed(access, chat, owner))
146
+ const scope = diaryScopeChat(this.deps.config)
147
+ if (!scope) {
148
+ this.deps.logger.warn("没有配置 ownerQQ,日记不做总结也不推送")
149
+ return []
115
150
  }
116
- return allowedTargets(access, owner)
151
+ if (!isTargetAllowed(this.deps.config.access, scope, this.deps.config.ownerQQ)) return []
152
+ return [scope]
117
153
  }
118
154
 
119
155
  /** 为一个聊天生成当天的日记。 */
@@ -158,6 +194,19 @@ export class DiaryScheduler {
158
194
  this.deps.logger.warn(`${targetLabel(target)} 的日记推送包含敏感信息,已拦截`)
159
195
  return
160
196
  }
197
+ // 日记正文是模型写的,可能带进群友原文里的敏感信息;发文件前必须过一遍内容。
198
+ let body: string
199
+ try {
200
+ body = await readDiaryHead(file)
201
+ } catch (error) {
202
+ this.deps.logger.error(`${targetLabel(target)} 的日记文件读取失败,放弃推送`, error)
203
+ return
204
+ }
205
+ const bodyVerdict = this.deps.sensitive.check(body)
206
+ if (!bodyVerdict.allowed) {
207
+ this.deps.logger.warn(`${targetLabel(target)} 的日记正文包含敏感信息,已拦截`)
208
+ return
209
+ }
161
210
  await sendFileMessage(this.deps.client, target, file, {
162
211
  name: `日记-${date}.md`,
163
212
  limiter: this.deps.limiter,
@@ -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
+ }
@@ -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) {
package/src/home.ts CHANGED
@@ -1,8 +1,14 @@
1
1
  import { mkdir } from "node:fs/promises"
2
2
  import { homedir } from "node:os"
3
- import { isAbsolute, join, normalize } from "node:path"
3
+ import { isAbsolute, join } from "node:path"
4
4
  import type { Logger } from "./logger"
5
5
 
6
+ /**
7
+ * 机器人固定服务的工作目录。
8
+ *
9
+ * 工作目录不再可配置:`config.json` 自己就放在这个目录里,位置固定才不会自举。
10
+ */
11
+
6
12
  /** 机器人固定服务的工作目录。 */
7
13
  export interface BotHome {
8
14
  /** 会话统一所在的绝对路径。 */
@@ -19,14 +25,12 @@ export function defaultHome(): string {
19
25
  /**
20
26
  * 解析机器人工作目录并确保它存在。
21
27
  *
22
- * 配置项优先;未配置时使用默认的 XDG 工作区,避免会话工作目录随加载插件的项目漂移。
28
+ * 目录固定在 XDG 数据目录下的工作区,启动时自动创建。
23
29
  */
24
- export async function resolveHome(
25
- configured: string | undefined,
26
- logger: Logger,
27
- ): Promise<BotHome> {
28
- const directory = configured ? expand(configured, logger) : defaultHome()
30
+ export async function resolveHome(logger: Logger): Promise<BotHome> {
31
+ const directory = defaultHome()
29
32
  await mkdir(directory, { recursive: true, mode: 0o700 })
33
+ logger.debug(`机器人工作目录:${directory}`)
30
34
  return { directory }
31
35
  }
32
36
 
@@ -36,12 +40,3 @@ export function expandTilde(value: string): string {
36
40
  if (value.startsWith("~/")) return join(homedir(), value.slice(2))
37
41
  return value
38
42
  }
39
-
40
- function expand(configured: string, logger: Logger): string {
41
- const expanded = expandTilde(configured)
42
- if (!isAbsolute(expanded)) {
43
- logger.warn("机器人工作目录必须是绝对路径,已回退到默认目录", configured)
44
- return defaultHome()
45
- }
46
- return normalize(expanded)
47
- }