@cmach_socket/opencode-qq-bot 1.0.1 → 2.0.1

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.
@@ -9,7 +9,7 @@ import type { SensitiveChecker } from "../sensitive"
9
9
  import { createPlainSender, sendFileMessage } from "../tools/qq"
10
10
  import type { DiaryCollector } from "./collector"
11
11
  import { dateKey, chatLabel, isDateKey } from "./format"
12
- import { diaryScopeChat, isDiaryScopeChat } from "./scope"
12
+ import { diaryEnabled } from "./scope"
13
13
  import { readDiaryHead, type DiaryStore } from "./store"
14
14
  import type { DiarySummarizer } from "./summary"
15
15
 
@@ -287,14 +287,16 @@ export function diaryCommand(runner: DiaryCommandRunner): CommandDefinition {
287
287
  description: "写、看、列出聊天日记:write 手写,show 看某天,list 列最近几篇,auto 自动生成。",
288
288
  usage: DIARY_USAGE_LINES,
289
289
  run: async (context, args) => {
290
- // 日记只属于 owner:QQ 侧只认 owner 自己的私聊。
291
- const scope = diaryScopeChat(context.config)
292
- if (!scope) return "没有配置 ownerQQ,无法使用日记。"
293
- if (context.source !== "tui" && !isDiaryScopeChat(context.config, context.target)) {
294
- return "日记只在 owner 自己的私聊里可用。"
290
+ // 全局开关是总开关:关掉后连每聊天开关都救不回来。
291
+ if (!context.config.diary.enabled) {
292
+ return "日记总开关已关闭,先在配置里把 diary.enabled 打开。"
295
293
  }
296
- // TUI 侧同样按 owner 私聊操作:不能在绑到群聊的会话里把日记发进群里。
297
- await runner.run(scope, args.join(" "))
294
+ // 日记属于「调用所在的聊天」:它得在会话覆盖里开着日记。
295
+ const override = await context.overrides.for(context.target)
296
+ if (!diaryEnabled(override)) {
297
+ return "这个聊天没有开启日记,先在会话覆盖里打开 diary.enabled。"
298
+ }
299
+ await runner.run(context.target, args.join(" "))
298
300
  },
299
301
  }
300
302
  }
@@ -5,12 +5,13 @@ import type { QQBotConfig } from "../config"
5
5
  import type { Logger } from "../logger"
6
6
  import type { OutboundMedia } from "../media-path"
7
7
  import type { QQClient } from "../naplink/client"
8
+ import type { ChatOverrides } from "../overrides"
8
9
  import type { SendRateLimiter } from "../rate-limit"
9
10
  import type { SensitiveChecker } from "../sensitive"
10
11
  import { sendFileMessage, sendPlainMessage } from "../tools/qq"
11
12
  import type { DiaryCollector } from "./collector"
12
13
  import { dateKey } from "./format"
13
- import { diaryScopeChat } from "./scope"
14
+ import { diaryScopeChats } from "./scope"
14
15
  import { readDiaryHead, type DiaryStore } from "./store"
15
16
  import type { DiarySummarizer } from "./summary"
16
17
 
@@ -30,6 +31,8 @@ export interface DiarySchedulerDeps {
30
31
  collector: DiaryCollector
31
32
  /** 自动生成。 */
32
33
  summarizer: DiarySummarizer
34
+ /** 会话覆盖:决定哪些聊天生成日记。 */
35
+ overrides: ChatOverrides
33
36
  }
34
37
 
35
38
  /**
@@ -132,7 +135,7 @@ export class DiaryScheduler {
132
135
  }
133
136
  const date = dateKey(now)
134
137
  let done = 0
135
- for (const chat of this.targets()) {
138
+ for (const chat of await this.targets()) {
136
139
  await this.runFor(chat, date)
137
140
  done += 1
138
141
  }
@@ -141,15 +144,12 @@ export class DiaryScheduler {
141
144
  })
142
145
  }
143
146
 
144
- /** 本轮要处理的目标聊天:日记只服务 owner 自己的私聊。 */
145
- private targets(): ChatTarget[] {
146
- const scope = diaryScopeChat(this.deps.config)
147
- if (!scope) {
148
- this.deps.logger.warn("没有配置 ownerQQ,日记不生成也不推送")
149
- return []
150
- }
151
- if (!isTargetAllowed(this.deps.config.access, scope, this.deps.config.ownerQQ)) return []
152
- return [scope]
147
+ /** 本轮要处理的目标聊天:会话覆盖里开着日记、且准入名单放行的聊天。 */
148
+ private async targets(): Promise<ChatTarget[]> {
149
+ const chats = diaryScopeChats(await this.deps.overrides.current())
150
+ return chats.filter((chat) =>
151
+ isTargetAllowed(this.deps.config.access, chat, this.deps.config.ownerQQ),
152
+ )
153
153
  }
154
154
 
155
155
  /** 为一个聊天生成当天的日记。 */
@@ -1,27 +1,18 @@
1
- import { type ChatTarget, targetKey } from "../chat"
2
- import type { QQBotConfig } from "../config"
1
+ import { type ChatTarget, parseTargetKey } from "../chat"
2
+ import type { ChatOverride, ChatOverridesFile } from "../overrides"
3
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 }
4
+ /** 这个聊天是否开着日记:会话覆盖里写了 `diary.enabled: true` 才算开。 */
5
+ export function diaryEnabled(override: ChatOverride | undefined): boolean {
6
+ return override?.["diary.enabled"] === true
14
7
  }
15
8
 
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
9
+ /** 日记范围:会话覆盖里开着日记、且聊天键合法的那些聊天。 */
10
+ export function diaryScopeChats(file: ChatOverridesFile): ChatTarget[] {
11
+ const chats: ChatTarget[] = []
12
+ for (const [key, override] of Object.entries(file.chats)) {
13
+ if (!diaryEnabled(override)) continue
14
+ const target = parseTargetKey(key)
15
+ if (target) chats.push(target)
16
+ }
17
+ return chats
27
18
  }
@@ -1,6 +1,7 @@
1
1
  import type { Plugin } from "@opencode/plugin"
2
2
  import type { Location } from "@opencode/schema"
3
3
  import { Mutex } from "async-mutex"
4
+ import { resolve } from "node:path"
4
5
  import { delay, unrefTimer } from "../async"
5
6
  import type { QQBotConfig } from "../config"
6
7
  import type { BotHome } from "../home"
@@ -13,12 +14,14 @@ import type { DiaryCollector, DiaryLine } from "./collector"
13
14
  import { chatLabel, dateKey, fallbackTitle } from "./format"
14
15
  import type { DiaryStore } from "./store"
15
16
 
16
- /** 插件存储里保存生成会话 ID 的键。 */
17
+ /** 插件存储里保存生成会话 ID 的键前缀:每个聊天一条。 */
17
18
  export const DIARY_SUMMARY_SESSION_KEY = "diary-summary-session"
18
19
  /** 会话标记:用来认出已经建好的生成会话。 */
19
20
  export const DIARY_SUMMARY_MARKER = "qqDiarySummary"
20
21
  /** 会话标记里记的日期:这个生成会话是哪一天建的。 */
21
22
  export const DIARY_SUMMARY_DATE_MARKER = "qqDiaryDate"
23
+ /** 会话标记里记的聊天:这个生成会话属于哪个聊天。 */
24
+ export const DIARY_SUMMARY_CHAT_MARKER = "qqDiaryChat"
22
25
  /** 等待模型生成日记的超时时间。 */
23
26
  export const DIARY_SUMMARY_TIMEOUT_MS = 120_000
24
27
  /** 标题最长字符数。 */
@@ -30,11 +33,16 @@ const RETRY_DELAY_MS = 10_000
30
33
 
31
34
  /** 存储里的生成会话记录:会话 ID 与它所属的日期。 */
32
35
  interface StoredSummarySession {
33
- /** 会话是哪一天建的;旧版本没有这一项,那种记录一律作废。 */
34
- date?: string
36
+ /** 会话是哪一天建的。 */
37
+ date: string
35
38
  sessionID: string
36
39
  }
37
40
 
41
+ /** 每个聊天在插件存储里的生成会话键。 */
42
+ export function summarySessionKey(chat: string): string {
43
+ return `${DIARY_SUMMARY_SESSION_KEY}:${chat}`
44
+ }
45
+
38
46
  /**
39
47
  * 生成日记用的提示词。
40
48
  *
@@ -125,8 +133,9 @@ export interface DiarySummarizerDeps {
125
133
  /**
126
134
  * 用模型把当天的聊天素材整理成一篇日记。
127
135
  *
128
- * 走一个专用的会话:这个会话不绑定任何 QQ 目标,
129
- * 因此不会触发角色设定里“必须调用 qq_send_message”的守则。
136
+ * 每个聊天走自己的专用生成会话:会话不绑定任何 QQ 目标,
137
+ * 因此不会触发角色设定里“必须调用 qq_send_message”的守则;
138
+ * 按聊天拆开会话也保证不同聊天的素材不会串进同一个上下文。
130
139
  */
131
140
  export class DiarySummarizer {
132
141
  private readonly abort = new AbortController()
@@ -135,11 +144,11 @@ export class DiarySummarizer {
135
144
  /** 等待本轮回复结束的回调。 */
136
145
  private readonly waiters = new Map<string, ((text: string | undefined) => void)[]>()
137
146
  private listener: Promise<void> | undefined
138
- private sessionID: string | undefined
139
- /** 当前生成会话属于哪一天:跨天就换一个会话。 */
140
- private sessionDate: string | undefined
141
- private creating: Promise<string> | undefined
142
- /** 同一时间只跑一个生成:全局生成会话的缓冲区不能同时承载两份素材。 */
147
+ /** 每个聊天当前使用的生成会话,以及它属于哪一天。 */
148
+ private readonly sessions = new Map<string, { sessionID: string; date: string }>()
149
+ /** 每个聊天正在创建的生成会话。 */
150
+ private readonly creating = new Map<string, Promise<string>>()
151
+ /** 同一时间只跑一个生成,避免同时占用多份模型上下文。 */
143
152
  private readonly mutex = new Mutex()
144
153
  /** 同一聊天同一天的生成只跑一次;两个入口同时来的时候共享同一个结果。 */
145
154
  private readonly inflight = new Map<string, Promise<string | undefined>>()
@@ -163,7 +172,7 @@ export class DiarySummarizer {
163
172
  * 而它的输入是群友可控的聊天记录,所以这个会话必须单独把工具全部摘掉。
164
173
  */
165
174
  async isSummarySession(sessionID: string): Promise<boolean> {
166
- if (this.sessionID === sessionID) return true
175
+ if (this.activeSession(sessionID)) return true
167
176
  try {
168
177
  const info = await this.deps.ctx.session.get({ sessionID })
169
178
  return info?.metadata?.[DIARY_SUMMARY_MARKER] === true
@@ -173,6 +182,28 @@ export class DiarySummarizer {
173
182
  }
174
183
  }
175
184
 
185
+ /** 某个会话属于哪一条聊天;不是生成会话时返回 undefined。 */
186
+ async chatForSession(sessionID: string): Promise<string | undefined> {
187
+ for (const [chat, entry] of this.sessions) {
188
+ if (entry.sessionID === sessionID) return chat
189
+ }
190
+ try {
191
+ const info = await this.deps.ctx.session.get({ sessionID })
192
+ const chat = info?.metadata?.[DIARY_SUMMARY_CHAT_MARKER]
193
+ return typeof chat === "string" && chat.length > 0 ? chat : undefined
194
+ } catch {
195
+ return undefined
196
+ }
197
+ }
198
+
199
+ /** 这个会话是不是某个聊天正在用的生成会话。 */
200
+ private activeSession(sessionID: string): boolean {
201
+ for (const entry of this.sessions.values()) {
202
+ if (entry.sessionID === sessionID) return true
203
+ }
204
+ return false
205
+ }
206
+
176
207
  /** 开始订阅文本事件。 */
177
208
  start(): void {
178
209
  this.listener ??= this.listen()
@@ -222,7 +253,7 @@ export class DiarySummarizer {
222
253
  /** 累加模型输出的一段文本;一轮回复可能拆成多段。 */
223
254
  private push(sessionID: string, text: string): void {
224
255
  // 全局事件里夹着所有会话的输出,只留生成会话自己的。
225
- if (this.sessionID !== sessionID) return
256
+ if (!this.activeSession(sessionID)) return
226
257
  const buffer = `${this.buffers.get(sessionID) ?? ""}${text}`
227
258
  this.buffers.set(sessionID, buffer)
228
259
  }
@@ -273,37 +304,40 @@ export class DiarySummarizer {
273
304
  })
274
305
  }
275
306
 
276
- /** 取得(必要时创建)当天的生成会话。 */
277
- private async ensureSession(date: string): Promise<string> {
278
- if (this.sessionID && this.sessionDate === date) return this.sessionID
279
- this.creating ??= this.resolveSession(date).finally(() => {
280
- this.creating = undefined
307
+ /** 取得(必要时创建)某个聊天当天的生成会话。 */
308
+ private async ensureSession(chat: string, date: string): Promise<string> {
309
+ const current = this.sessions.get(chat)
310
+ if (current?.date === date) return current.sessionID
311
+ const pending = this.creating.get(chat)
312
+ if (pending) return pending
313
+ const created = this.resolveSession(chat, date).finally(() => {
314
+ this.creating.delete(chat)
281
315
  })
282
- return this.creating
316
+ this.creating.set(chat, created)
317
+ return created
283
318
  }
284
319
 
285
320
  /**
286
- * 解析当天的生成会话。
321
+ * 解析某个聊天当天的生成会话。
287
322
  *
288
- * 生成会话按天换:同一个会话的上下文只增不减,跑久了会超出模型上下文。
323
+ * 生成会话按聊天、按天换:不同聊天的素材不能进同一个上下文,
324
+ * 同一个会话的上下文只增不减,跑久了会超出模型上下文。
289
325
  * 换天时新建一个会话,并把前一个删掉,不给上游留只增不减的旧会话。
290
326
  */
291
- private async resolveSession(date: string): Promise<string> {
292
- const stored = await this.readStoredSession()
327
+ private async resolveSession(chat: string, date: string): Promise<string> {
328
+ const stored = await this.readStoredSession(chat)
293
329
  // 还是今天的会话就接着用:同一天里的几轮生成不用重建上下文。
294
330
  if (stored?.date === date && (await this.sessionUsable(stored.sessionID))) {
295
- this.sessionID = stored.sessionID
296
- this.sessionDate = date
331
+ this.sessions.set(chat, { sessionID: stored.sessionID, date })
297
332
  return stored.sessionID
298
333
  }
299
334
  // 换天,或者存储里记的会话已经没了:前一个会话删掉,别留在上游。
300
335
  if (stored) await this.removeSession(stored.sessionID)
301
- const found = await this.findSummarySession(date)
336
+ const found = await this.findSummarySession(chat, date)
302
337
  if (found) {
303
- this.sessionID = found
304
- this.sessionDate = date
305
- await this.writeStoredSession(date, found)
306
- this.deps.logger.info(`复用日记生成会话 ${found}`)
338
+ this.sessions.set(chat, { sessionID: found, date })
339
+ await this.writeStoredSession(chat, date, found)
340
+ this.deps.logger.info(`复用日记生成会话 ${found}(${chat})`)
307
341
  return found
308
342
  }
309
343
  const created = await this.deps.ctx.session.create({
@@ -311,42 +345,37 @@ export class DiarySummarizer {
311
345
  location: this.location,
312
346
  ...(this.deps.config.agent ? { agent: this.deps.config.agent } : {}),
313
347
  ...(this.deps.config.model ? { model: this.deps.config.model } : {}),
314
- metadata: { [DIARY_SUMMARY_MARKER]: true, [DIARY_SUMMARY_DATE_MARKER]: date },
348
+ metadata: {
349
+ [DIARY_SUMMARY_MARKER]: true,
350
+ [DIARY_SUMMARY_DATE_MARKER]: date,
351
+ [DIARY_SUMMARY_CHAT_MARKER]: chat,
352
+ },
315
353
  })
316
- this.sessionID = created.id
317
- this.sessionDate = date
318
- await this.writeStoredSession(date, created.id)
319
- this.deps.logger.info(`新建日记生成会话 ${created.id}(${date})`)
354
+ this.sessions.set(chat, { sessionID: created.id, date })
355
+ await this.writeStoredSession(chat, date, created.id)
356
+ this.deps.logger.info(`新建日记生成会话 ${created.id}(${chat} ${date})`)
320
357
  return created.id
321
358
  }
322
359
 
323
- /**
324
- * 读存储里记的生成会话。
325
- *
326
- * 旧版本记的是一串会话 ID,没有日期:那种记录一律作废,
327
- * 换天时连着旧会话一起清掉。
328
- */
329
- private async readStoredSession(): Promise<StoredSummarySession | undefined> {
360
+ /** 读存储里记的生成会话;记录必须同时带会话 ID 与日期,缺一项按没有记录处理。 */
361
+ private async readStoredSession(chat: string): Promise<StoredSummarySession | undefined> {
330
362
  try {
331
- const stored = await this.deps.ctx.storage.get(DIARY_SUMMARY_SESSION_KEY)
332
- if (typeof stored === "string" && stored.length > 0) return { sessionID: stored }
363
+ const stored = await this.deps.ctx.storage.get(summarySessionKey(chat))
333
364
  if (!stored || typeof stored !== "object" || Array.isArray(stored)) return undefined
334
365
  const record = stored as Partial<StoredSummarySession>
335
366
  if (typeof record.sessionID !== "string" || record.sessionID.length === 0) return undefined
336
- return {
337
- sessionID: record.sessionID,
338
- ...(typeof record.date === "string" && record.date.length > 0 ? { date: record.date } : {}),
339
- }
367
+ if (typeof record.date !== "string" || record.date.length === 0) return undefined
368
+ return { sessionID: record.sessionID, date: record.date }
340
369
  } catch (error) {
341
370
  this.deps.logger.debug("读取日记生成会话失败,将新建会话", error)
342
371
  return undefined
343
372
  }
344
373
  }
345
374
 
346
- /** 记下当天的生成会话。 */
347
- private async writeStoredSession(date: string, sessionID: string): Promise<void> {
375
+ /** 记下某个聊天当天的生成会话。 */
376
+ private async writeStoredSession(chat: string, date: string, sessionID: string): Promise<void> {
348
377
  try {
349
- await this.deps.ctx.storage.set(DIARY_SUMMARY_SESSION_KEY, { date, sessionID })
378
+ await this.deps.ctx.storage.set(summarySessionKey(chat), { date, sessionID })
350
379
  } catch (error) {
351
380
  this.deps.logger.warn("保存日记生成会话失败", error)
352
381
  }
@@ -356,7 +385,10 @@ export class DiarySummarizer {
356
385
  private async sessionUsable(sessionID: string): Promise<boolean> {
357
386
  try {
358
387
  const info = await this.deps.ctx.session.get({ sessionID })
359
- return info?.location?.directory === this.location.directory
388
+ const directory = info?.location?.directory
389
+ if (!directory) return false
390
+ // 路径写法可能不同(尾斜杠、`..` 段),比之前先归一。
391
+ return resolve(directory) === resolve(this.location.directory)
360
392
  } catch {
361
393
  return false
362
394
  }
@@ -372,14 +404,15 @@ export class DiarySummarizer {
372
404
  }
373
405
  }
374
406
 
375
- /** 查找当天建的生成会话。 */
376
- private async findSummarySession(date: string): Promise<string | undefined> {
407
+ /** 查找某个聊天当天建的生成会话。 */
408
+ private async findSummarySession(chat: string, date: string): Promise<string | undefined> {
377
409
  return await findSession(
378
410
  this.deps.ctx,
379
411
  this.location.directory,
380
412
  (session) =>
381
413
  session.metadata?.[DIARY_SUMMARY_MARKER] === true &&
382
- session.metadata?.[DIARY_SUMMARY_DATE_MARKER] === date,
414
+ session.metadata?.[DIARY_SUMMARY_DATE_MARKER] === date &&
415
+ session.metadata?.[DIARY_SUMMARY_CHAT_MARKER] === chat,
383
416
  this.deps.logger,
384
417
  "查找日记生成会话失败",
385
418
  )
@@ -405,7 +438,7 @@ export class DiarySummarizer {
405
438
  }
406
439
  }
407
440
 
408
- /** 真正跑生成;同一时间只允许一个生成占用全局生成会话。 */
441
+ /** 真正跑生成;同一时间只允许一个生成,避免同时占用多份模型上下文。 */
409
442
  private async runSummary(chat: string, date: string): Promise<string | undefined> {
410
443
  if (this.abort.signal.aborted) return undefined
411
444
  const lines = await this.deps.collector.read(chat, date)
@@ -422,7 +455,7 @@ export class DiarySummarizer {
422
455
  for (let attempt = 0; attempt < 2; attempt += 1) {
423
456
  if (this.abort.signal.aborted) return undefined
424
457
  if (attempt > 0) await delay(RETRY_DELAY_MS)
425
- const summary = await this.runOnce(prompt, timeoutMs, runDate)
458
+ const summary = await this.runOnce(chat, prompt, timeoutMs, runDate)
426
459
  if (!summary) continue
427
460
  if (this.abort.signal.aborted) return undefined
428
461
  const entry = await this.deps.store.write(chat, date, {
@@ -439,11 +472,12 @@ export class DiarySummarizer {
439
472
 
440
473
  /** 跑一轮生成;返回 undefined 表示这轮没拿到可用结果。 */
441
474
  private async runOnce(
475
+ chat: string,
442
476
  prompt: string,
443
477
  timeoutMs: number,
444
478
  date: string,
445
479
  ): Promise<{ title: string; body: string } | undefined> {
446
- const sessionID = await this.ensureSession(date)
480
+ const sessionID = await this.ensureSession(chat, date)
447
481
  // 丢掉上一轮的残留文本,保证拿到的是这次提问的回复。
448
482
  this.buffers.delete(sessionID)
449
483
  try {
package/src/fs/atomic.ts CHANGED
@@ -7,7 +7,8 @@ import writeFileAtomic from "write-file-atomic"
7
7
  *
8
8
  * 临时文件 + fsync + rename:中途失败不会留下半截文件;
9
9
  * 写之前把旧内容存成 `.bak`,写坏了还能翻回去。
10
- * `config.json`、`chat-overrides.json` 与 `tool-profiles.json` 共用这一份实现。
10
+ * `config/config.json`、`config/chat-overrides.json`、`config/tool-profiles.json`
11
+ * 与每个聊天的用户画像共用这一份实现。
11
12
  *
12
13
  * 目标必须是普通文件:符号链接一律拒绝写。`write-file-atomic` 会把临时文件
13
14
  * rename 到链接指向的真实文件上,链接本身还在,但替换的是别人的 inode;
@@ -45,22 +46,33 @@ async function fsyncDirectory(path: string): Promise<void> {
45
46
  }
46
47
 
47
48
  /**
48
- * 原子写 JSON 文件。
49
+ * 原子写文本文件。
49
50
  *
50
- * 目录按 `0700` 创建,文件按 `0600` 写;备份由调用方单独做。
51
+ * 目录按 `0700` 创建,文件按 `0600` 写;临时文件 + fsync + rename,
52
+ * 中途失败不会留下半截文件。
51
53
  *
52
54
  * @throws 目标是符号链接时抛错,避免写穿到别处。
53
55
  */
54
- export async function writeJsonAtomic(path: string, value: unknown): Promise<void> {
56
+ export async function writeTextAtomic(path: string, text: string): Promise<void> {
55
57
  await mkdir(dirname(path), { recursive: true, mode: DIR_MODE })
56
58
  if (await isSymlink(path)) {
57
59
  throw new Error(`拒绝写入符号链接:${path}(请把它换成普通文件再试)`)
58
60
  }
59
- const text = `${JSON.stringify(value, null, 2)}\n`
60
61
  await writeFileAtomic(path, text, { mode: FILE_MODE, fsync: true })
61
62
  await fsyncDirectory(dirname(path))
62
63
  }
63
64
 
65
+ /**
66
+ * 原子写 JSON 文件。
67
+ *
68
+ * 目录按 `0700` 创建,文件按 `0600` 写;备份由调用方单独做。
69
+ *
70
+ * @throws 目标是符号链接时抛错,避免写穿到别处。
71
+ */
72
+ export async function writeJsonAtomic(path: string, value: unknown): Promise<void> {
73
+ await writeTextAtomic(path, `${JSON.stringify(value, null, 2)}\n`)
74
+ }
75
+
64
76
  /**
65
77
  * 把当前内容存成 `.bak`。
66
78
  *
package/src/home.ts CHANGED
@@ -1,39 +1,44 @@
1
1
  import { mkdir } from "node:fs/promises"
2
2
  import { homedir } from "node:os"
3
- import { dirname, isAbsolute, join } 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
-
12
6
  /** 机器人固定服务的工作目录。 */
13
7
  export interface BotHome {
14
- /** 会话统一所在的绝对路径。 */
8
+ /** 工作目录:配置、日记、全局媒体与各聊天目录都在这里。 */
15
9
  directory: string
16
10
  /** 共享状态的跨进程写锁路径;不设就不加文件锁。 */
17
11
  lockPath?: string
18
12
  }
19
13
 
20
- /** 默认工作目录:`$XDG_DATA_HOME/opencode-qq-bot/workspace`。 */
14
+ /**
15
+ * 默认工作目录:`$XDG_DATA_HOME/opencode-qq-bot`。
16
+ *
17
+ * 目录固定且不可配置:`config/` 就在这个目录里,位置固定才不会自举。
18
+ */
21
19
  export function defaultHome(): string {
22
20
  const data = process.env.XDG_DATA_HOME
23
21
  const base = data && isAbsolute(data) ? data : join(homedir(), ".local", "share")
24
- return join(base, "opencode-qq-bot", "workspace")
22
+ return join(base, "opencode-qq-bot")
25
23
  }
26
24
 
25
+ /** 启动时就建好的基础目录:配置、角色设定、日记、全局媒体与各聊天目录。 */
26
+ const BASE_DIRS = ["config", "souls", "diary", "media", "chats"] as const
27
+
27
28
  /**
28
29
  * 解析机器人工作目录并确保它存在。
29
30
  *
30
- * 目录固定在 XDG 数据目录下的工作区,启动时自动创建。
31
+ * 目录固定在 XDG 数据目录下,启动时把基础目录一并建好,
32
+ * 免得第一次用到某个目录时才临时创建。
31
33
  */
32
34
  export async function resolveHome(logger: Logger): Promise<BotHome> {
33
35
  const directory = defaultHome()
34
36
  await mkdir(directory, { recursive: true, mode: 0o700 })
35
- // 写锁放在工作目录的同级:工作目录本身是会话目录,不往里面塞杂物。
36
- const lockPath = join(dirname(directory), "state.lock")
37
+ await Promise.all(
38
+ BASE_DIRS.map((name) => mkdir(join(directory, name), { recursive: true, mode: 0o700 })),
39
+ )
40
+ // 写锁和数据目录里的其它状态放在一起,不另占 XDG 根目录。
41
+ const lockPath = join(directory, "state.lock")
37
42
  logger.debug(`机器人工作目录:${directory}`)
38
43
  return { directory, lockPath }
39
44
  }