@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.
Files changed (45) hide show
  1. package/NOTICE +0 -1
  2. package/README.md +152 -494
  3. package/chat-overrides.example.json +3 -3
  4. package/config.example.json +12 -0
  5. package/package.json +7 -2
  6. package/src/chat.ts +5 -0
  7. package/src/commands.ts +88 -1
  8. package/src/config/fields.ts +48 -5
  9. package/src/config/live.ts +61 -3
  10. package/src/config/store.ts +6 -11
  11. package/src/config/types.ts +24 -0
  12. package/src/config.ts +3 -0
  13. package/src/diary/command.ts +13 -12
  14. package/src/diary/format.ts +17 -0
  15. package/src/diary/scheduler.ts +1 -1
  16. package/src/diary/summary.ts +6 -5
  17. package/src/emoji/collection.ts +321 -0
  18. package/src/emoji/favorite-index.ts +40 -3
  19. package/src/emoji/favorites.ts +7 -1
  20. package/src/fs/atomic.ts +82 -0
  21. package/src/home.ts +6 -2
  22. package/src/index.ts +41 -36
  23. package/src/keepalive.ts +60 -2
  24. package/src/known-secrets.ts +20 -0
  25. package/src/logger.ts +2 -1
  26. package/src/overrides.ts +209 -47
  27. package/src/panel/api.ts +61 -7
  28. package/src/panel/documents.ts +621 -0
  29. package/src/panel/server.ts +66 -25
  30. package/src/panel/status.ts +8 -1
  31. package/src/safe-object.ts +48 -0
  32. package/src/sensitive.ts +31 -2
  33. package/src/session/find.ts +3 -2
  34. package/src/session/manager.ts +646 -43
  35. package/src/session/proactive.ts +3 -1
  36. package/src/session/soul-guard.ts +162 -0
  37. package/src/session/soul.ts +78 -13
  38. package/src/state-lock.ts +74 -0
  39. package/src/tools/policy.ts +65 -24
  40. package/src/tools/qq.ts +103 -22
  41. package/web/dist/assets/index-C5lRsdbz.css +1 -0
  42. package/web/dist/assets/index-YqorZD0I.js +8 -0
  43. package/web/dist/index.html +2 -2
  44. package/web/dist/assets/index-7eMQEM7-.css +0 -1
  45. package/web/dist/assets/index-DCkgUY7y.js +0 -15
@@ -187,7 +187,7 @@ export class DiaryScheduler {
187
187
  }
188
188
  const text = toOwner
189
189
  ? `${targetLabel(chat)} ${date} 的日记已生成\n文件:${file}`
190
- : `${date} 的日记已生成`
190
+ : `${targetLabel(chat)} ${date} 的日记已生成`
191
191
  // 推送走插件自己的通道,不经过模型侧的出站检查,这里自己过一遍。
192
192
  const verdict = this.deps.sensitive.check(text)
193
193
  if (!verdict.allowed) {
@@ -10,7 +10,7 @@ import { toPlainText } from "../outbound"
10
10
  import { findSession } from "../session/find"
11
11
  import { softTruncate } from "../text"
12
12
  import type { DiaryCollector, DiaryLine } from "./collector"
13
- import { fallbackTitle } from "./format"
13
+ import { chatLabel, fallbackTitle } from "./format"
14
14
  import type { DiaryStore } from "./store"
15
15
 
16
16
  /** 插件存储里保存总结会话 ID 的键。 */
@@ -30,9 +30,10 @@ const RETRY_DELAY_MS = 10_000
30
30
  * 生成总结用的提示词。
31
31
  *
32
32
  * 素材是群友可控文本,所以先净化结构标签再包进 `<chat>`,
33
- * 并在提示词里说明标签内是素材而不是指令。
33
+ * 并在提示词里说明标签内是素材而不是指令;聊天标识写进提示词,
34
+ * 让模型知道素材来自群聊还是私聊。
34
35
  */
35
- export function buildDiaryPrompt(date: string, lines: readonly DiaryLine[]): string {
36
+ export function buildDiaryPrompt(date: string, chat: string, lines: readonly DiaryLine[]): string {
36
37
  const body = lines
37
38
  .map((line) => {
38
39
  const stamp = formatClock(line.time)
@@ -45,7 +46,7 @@ export function buildDiaryPrompt(date: string, lines: readonly DiaryLine[]): str
45
46
  })
46
47
  .join("\n")
47
48
  return [
48
- `下面是这个聊天在 ${date} 的聊天记录摘录。请把它整理成一篇当天的日记。`,
49
+ `下面是${chatLabel(chat)}在 ${date} 的聊天记录摘录。请把它整理成一篇当天的日记。`,
49
50
  "",
50
51
  "要求:",
51
52
  "1. 只依据下面的记录写,不要补充记录里没有的信息,也不要猜测。",
@@ -360,7 +361,7 @@ export class DiarySummarizer {
360
361
  return undefined
361
362
  }
362
363
  this.start()
363
- const prompt = buildDiaryPrompt(date, lines)
364
+ const prompt = buildDiaryPrompt(date, chat, lines)
364
365
  const timeoutMs = this.deps.timeoutMs ?? DIARY_SUMMARY_TIMEOUT_MS
365
366
 
366
367
  for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -0,0 +1,321 @@
1
+ import { createHash } from "node:crypto"
2
+ import { chmod, copyFile, mkdir, open, readFile, unlink } from "node:fs/promises"
3
+ import { extname, join, resolve, sep } from "node:path"
4
+ import { fileURLToPath } from "node:url"
5
+ import type { Plugin } from "@opencode/plugin"
6
+ import { Mutex } from "async-mutex"
7
+ import { type ChatTarget, targetKey } from "../chat"
8
+ import type { Logger } from "../logger"
9
+ import type { PromptFile } from "../naplink/media"
10
+
11
+ /** 收藏描述最长字数。 */
12
+ export const MAX_DESCRIPTION_LENGTH = 12
13
+
14
+ /** 收藏描述的规则说明;描述不合规时原样回给模型。 */
15
+ export const DESCRIPTION_RULES = `描述要是一个中文名字,最多 ${MAX_DESCRIPTION_LENGTH} 个字,只能用文字和数字,不要标点、空格、引号、解释。`
16
+
17
+ /** 描述校验结果。 */
18
+ export type DescriptionCheck = { ok: true; value: string } | { ok: false; reason: string }
19
+
20
+ /**
21
+ * 校验收藏描述。
22
+ *
23
+ * 描述会写进收藏列表,模型必须一次给出合规的名字:
24
+ * 只有文字和数字、不带空格标点、不超过 12 个字。
25
+ */
26
+ export function checkDescription(raw: unknown): DescriptionCheck {
27
+ if (typeof raw !== "string") return { ok: false, reason: "缺少 description(收藏描述)" }
28
+ const value = raw.trim()
29
+ if (!value) return { ok: false, reason: "缺少 description(收藏描述)" }
30
+ if (/\s/u.test(value)) return { ok: false, reason: "描述里不能有空格" }
31
+ const chars = Array.from(value)
32
+ if (chars.some((char) => !/[\p{L}\p{N}]/u.test(char))) {
33
+ return { ok: false, reason: "描述里只能有文字和数字" }
34
+ }
35
+ if (chars.length > MAX_DESCRIPTION_LENGTH) {
36
+ return { ok: false, reason: `描述最多 ${MAX_DESCRIPTION_LENGTH} 个字` }
37
+ }
38
+ return { ok: true, value }
39
+ }
40
+
41
+ /** 插件存储里收藏清单的键。 */
42
+ export const COLLECTION_KEY = "emoji-collection"
43
+ /** 收藏文件在媒体目录下的子目录名。 */
44
+ export const COLLECTION_DIR = "favorites"
45
+ /** 本机收藏的表情数量上限,超出后丢掉最早收藏的。 */
46
+ export const MAX_COLLECTED_STICKERS = 200
47
+
48
+ /** 本机收集的表情。 */
49
+ export type CollectedSticker = {
50
+ /** 图片 md5,作为身份键。 */
51
+ md5: string
52
+ /** 收藏描述。 */
53
+ description: string
54
+ /** 本地文件绝对路径。 */
55
+ file: string
56
+ /** 收藏时间(毫秒)。 */
57
+ createdAt: number
58
+ }
59
+
60
+ /** 收藏存储用到的插件存储接口。 */
61
+ export type CollectionStorage = Pick<Plugin.Context["storage"], "get" | "set">
62
+
63
+ /**
64
+ * 本机收集的表情清单。
65
+ *
66
+ * QQ 客户端的收藏表情只有 NapCat 能写,插件收集的动图只能自己存:
67
+ * 图片复制到媒体目录下的收藏子目录,元数据写在插件存储里。
68
+ */
69
+ export class CollectionStore {
70
+ private readonly mutex = new Mutex()
71
+ private items: CollectedSticker[] = []
72
+ private loaded = false
73
+ private loading: Promise<void> | undefined
74
+
75
+ constructor(
76
+ private readonly storage: CollectionStorage,
77
+ /** 媒体目录:收藏文件放在它的收藏子目录里。 */
78
+ private readonly root: string,
79
+ private readonly logger: Logger,
80
+ ) {}
81
+
82
+ /** 收藏清单,按收藏先后返回。 */
83
+ async list(): Promise<CollectedSticker[]> {
84
+ await this.ensureLoaded()
85
+ return [...this.items]
86
+ }
87
+
88
+ /**
89
+ * 收藏一张图片。
90
+ *
91
+ * 图片复制到收藏目录,元数据写进插件存储;
92
+ * 同一张图重复收藏只更新描述,文件不重复存。
93
+ */
94
+ async add(source: string, description: string): Promise<CollectedSticker> {
95
+ return this.mutex.runExclusive(async () => {
96
+ await this.ensureLoaded()
97
+ const bytes = await readFile(source)
98
+ const md5 = createHash("md5").update(bytes).digest("hex")
99
+ const ext = extname(source).replace(/^\./, "").toLowerCase() || "bin"
100
+ const dir = join(this.root, COLLECTION_DIR)
101
+ await mkdir(dir, { recursive: true, mode: 0o700 })
102
+ const file = join(dir, `${md5}.${ext}`)
103
+ await copyFile(source, file)
104
+ await chmod(file, 0o600)
105
+ const existing = this.items.find((item) => item.md5 === md5)
106
+ const sticker: CollectedSticker = {
107
+ md5,
108
+ description,
109
+ file,
110
+ createdAt: existing?.createdAt ?? Date.now(),
111
+ }
112
+ this.items = existing
113
+ ? this.items.map((item) => (item.md5 === md5 ? sticker : item))
114
+ : [...this.items, sticker]
115
+ await this.enforceLimit()
116
+ await this.persist()
117
+ return sticker
118
+ })
119
+ }
120
+
121
+ /** 超过上限时丢掉最早收藏的,连同它的文件一起删掉。 */
122
+ private async enforceLimit(): Promise<void> {
123
+ while (this.items.length > MAX_COLLECTED_STICKERS) {
124
+ const oldest = this.items.shift()
125
+ if (!oldest) break
126
+ // 只删收藏目录里的文件:存储被污染过时不能让它去删别处的文件。
127
+ if (!this.insideCollection(oldest.file)) continue
128
+ try {
129
+ await unlink(oldest.file)
130
+ } catch {
131
+ // 文件可能已经被删掉,不影响清单。
132
+ }
133
+ }
134
+ }
135
+
136
+ /** 这个路径是不是收藏目录里的文件。 */
137
+ private insideCollection(file: string): boolean {
138
+ const dir = resolve(this.root, COLLECTION_DIR)
139
+ const target = resolve(file)
140
+ return target.startsWith(`${dir}${sep}`)
141
+ }
142
+
143
+ /** 从插件存储恢复清单;读取失败下次重试。 */
144
+ private ensureLoaded(): Promise<void> {
145
+ if (this.loaded) return Promise.resolve()
146
+ this.loading ??= this.read()
147
+ .then(() => {
148
+ this.loaded = true
149
+ })
150
+ .catch((error: unknown) => {
151
+ this.logger.warn("读取收藏清单失败", error)
152
+ this.loading = undefined
153
+ })
154
+ return this.loading
155
+ }
156
+
157
+ private async read(): Promise<void> {
158
+ const stored = await this.storage.get(COLLECTION_KEY)
159
+ const raw = (stored as { items?: unknown } | undefined)?.items
160
+ if (!Array.isArray(raw)) return
161
+ const items: CollectedSticker[] = []
162
+ for (const entry of raw) {
163
+ if (!entry || typeof entry !== "object") continue
164
+ const { md5, description, file, createdAt } = entry as Record<string, unknown>
165
+ if (typeof md5 !== "string" || md5.length === 0) continue
166
+ if (typeof description !== "string" || description.length === 0) continue
167
+ if (typeof file !== "string" || file.length === 0) continue
168
+ // 存储里的路径必须落在收藏目录里:清单被污染时不至于指到别处。
169
+ if (!this.insideCollection(file)) {
170
+ this.logger.warn(`收藏清单里的文件路径不在收藏目录内,已忽略:${file}`)
171
+ continue
172
+ }
173
+ items.push({
174
+ md5,
175
+ description,
176
+ file,
177
+ createdAt: typeof createdAt === "number" && Number.isFinite(createdAt) ? createdAt : 0,
178
+ })
179
+ }
180
+ this.items = items
181
+ }
182
+
183
+ /** 写回清单;失败只记日志。 */
184
+ private async persist(): Promise<void> {
185
+ try {
186
+ await this.storage.set(COLLECTION_KEY, { version: 1, items: this.items })
187
+ } catch (error) {
188
+ this.logger.error("保存收藏清单失败", error)
189
+ }
190
+ }
191
+ }
192
+
193
+ /** 最近收到的图片在内存里保留的时间。 */
194
+ export const RECENT_IMAGE_TTL_MS = 30 * 60 * 1000
195
+ /** 每个聊天最多保留多少张最近收到的图片。 */
196
+ export const MAX_RECENT_IMAGES = 12
197
+ /** 同时记着多少个聊天:聊天数不封顶时这张表会一直涨。 */
198
+ export const MAX_TRACKED_CHATS = 64
199
+
200
+ /** 收到的一张图片。 */
201
+ export interface ReceivedImage {
202
+ /** 本地文件绝对路径。 */
203
+ file: string
204
+ /** 扩展名,不含点。 */
205
+ ext: string
206
+ /** 是否动图。 */
207
+ animated: boolean
208
+ /** 收到时间(毫秒)。 */
209
+ at: number
210
+ /** 来源消息 ID。 */
211
+ messageId?: string
212
+ }
213
+
214
+ /** 把附件引用还原成本地路径;不是本地文件时返回 undefined。 */
215
+ function localPath(uri: string): string | undefined {
216
+ if (uri.startsWith("file:")) {
217
+ try {
218
+ return fileURLToPath(uri)
219
+ } catch {
220
+ return undefined
221
+ }
222
+ }
223
+ return uri.startsWith("/") ? uri : undefined
224
+ }
225
+
226
+ /**
227
+ * 判断图片是不是动图。
228
+ *
229
+ * GIF 一律当动图;WebP 要看有没有 `ANIM` 块。
230
+ */
231
+ async function isAnimatedImage(file: string, ext: string): Promise<boolean> {
232
+ if (ext === "gif") return true
233
+ if (ext !== "webp") return false
234
+ try {
235
+ const handle = await open(file, "r")
236
+ try {
237
+ const buffer = Buffer.alloc(256)
238
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0)
239
+ return buffer.subarray(0, bytesRead).includes("ANIM")
240
+ } finally {
241
+ await handle.close()
242
+ }
243
+ } catch {
244
+ return false
245
+ }
246
+ }
247
+
248
+ /**
249
+ * 各聊天最近收到的图片。
250
+ *
251
+ * 收藏表情要有个来源:这个表记住每个聊天刚收到过哪些图片,
252
+ * 收藏时从中挑最近收到的那张动图。
253
+ */
254
+ export class RecentImages {
255
+ private readonly chats = new Map<string, ReceivedImage[]>()
256
+
257
+ constructor(private readonly ttlMs = RECENT_IMAGE_TTL_MS) {}
258
+
259
+ /** 记下一条消息里的图片。 */
260
+ async record(
261
+ target: ChatTarget,
262
+ files: readonly PromptFile[],
263
+ messageId?: string,
264
+ ): Promise<void> {
265
+ const images: ReceivedImage[] = []
266
+ for (const file of files) {
267
+ const path = localPath(file.uri)
268
+ if (!path) continue
269
+ const ext = extname(path).replace(/^\./, "").toLowerCase()
270
+ if (!ext) continue
271
+ images.push({
272
+ file: path,
273
+ ext,
274
+ animated: await isAnimatedImage(path, ext),
275
+ at: Date.now(),
276
+ ...(messageId ? { messageId } : {}),
277
+ })
278
+ }
279
+ if (images.length === 0) return
280
+ const key = targetKey(target)
281
+ if (!this.chats.has(key)) this.evictChat()
282
+ const items = [...(this.chats.get(key) ?? []), ...images]
283
+ while (items.length > MAX_RECENT_IMAGES) items.shift()
284
+ this.chats.set(key, items)
285
+ }
286
+
287
+ /** 聊天太多时丢掉最久没更新的那个。 */
288
+ private evictChat(): void {
289
+ if (this.chats.size < MAX_TRACKED_CHATS) return
290
+ let oldestKey: string | undefined
291
+ let oldestAt = Number.POSITIVE_INFINITY
292
+ for (const [key, items] of this.chats) {
293
+ const at = items[items.length - 1]?.at ?? 0
294
+ if (at < oldestAt) {
295
+ oldestAt = at
296
+ oldestKey = key
297
+ }
298
+ }
299
+ if (oldestKey !== undefined) this.chats.delete(oldestKey)
300
+ }
301
+
302
+ /** 这个聊天最近收到的图片,只返回还在保留期内的。 */
303
+ list(target: ChatTarget): ReceivedImage[] {
304
+ const key = targetKey(target)
305
+ const now = Date.now()
306
+ const items = (this.chats.get(key) ?? []).filter((item) => now - item.at < this.ttlMs)
307
+ if (items.length > 0) this.chats.set(key, items)
308
+ return [...items]
309
+ }
310
+
311
+ /**
312
+ * 最近收到的一张图片。
313
+ *
314
+ * 要求动图时只在动图里找最新的那张。
315
+ */
316
+ latest(target: ChatTarget, options: { animated?: boolean } = {}): ReceivedImage | undefined {
317
+ const items = this.list(target)
318
+ const candidates = options.animated ? items.filter((item) => item.animated) : items
319
+ return candidates[candidates.length - 1]
320
+ }
321
+ }
@@ -1,6 +1,7 @@
1
1
  import type { Plugin } from "@opencode/plugin"
2
2
  import { Mutex } from "async-mutex"
3
3
  import type { Logger } from "../logger"
4
+ import type { CollectedSticker } from "./collection"
4
5
  import { type CustomFace, faceTag, type FavoriteRow } from "./favorites"
5
6
 
6
7
  /** 插件存储里收藏表情编号索引的键。 */
@@ -31,6 +32,15 @@ interface StoredEntry {
31
32
  id: number
32
33
  }
33
34
 
35
+ /**
36
+ * 本机收集的表情的身份键。
37
+ *
38
+ * 和收藏表情一样以图片 md5 为准:同一张图只占一个编号。
39
+ */
40
+ export function collectedKey(sticker: CollectedSticker): string {
41
+ return `md5:${sticker.md5.trim().toLowerCase()}`
42
+ }
43
+
34
44
  /** 从插件存储里读回编号记录,格式不对就当没有。 */
35
45
  function parseEntries(stored: unknown): StoredEntry[] {
36
46
  if (!stored || typeof stored !== "object" || Array.isArray(stored)) return []
@@ -70,8 +80,12 @@ export class FavoriteIndex {
70
80
  * 读取收藏表情列表并给每个表情配上编号。
71
81
  *
72
82
  * 返回的顺序按编号从小到大;`md5` 相同的记录视为同一个表情,只保留一条。
83
+ * 本机收集的表情和 QQ 收藏表情共用一套编号,按图片 md5 认回同一个编号。
73
84
  */
74
- async sync(faces: readonly CustomFace[]): Promise<FavoriteRow[]> {
85
+ async sync(
86
+ faces: readonly CustomFace[],
87
+ collected: readonly CollectedSticker[] = [],
88
+ ): Promise<FavoriteRow[]> {
75
89
  await this.ensureLoaded()
76
90
  const rows: FavoriteRow[] = []
77
91
  const seen = new Set<string>()
@@ -94,14 +108,37 @@ export class FavoriteIndex {
94
108
  }
95
109
  rows.push({ id, face, tag: faceTag(face) })
96
110
  }
111
+ for (const sticker of collected) {
112
+ const key = collectedKey(sticker)
113
+ // 和 QQ 收藏表情撞上同一张图时以 QQ 收藏表情为准。
114
+ if (seen.has(key)) continue
115
+ seen.add(key)
116
+ let id = this.entries.get(key)
117
+ if (id === undefined) {
118
+ id = nextId
119
+ nextId += 1
120
+ this.entries.set(key, id)
121
+ changed = true
122
+ }
123
+ rows.push({
124
+ id,
125
+ face: { md5: sticker.md5, url: sticker.file, desc: sticker.description },
126
+ tag: sticker.description,
127
+ collected: sticker,
128
+ })
129
+ }
97
130
  rows.sort((left, right) => left.id - right.id)
98
131
  if (changed) await this.persist()
99
132
  return rows
100
133
  }
101
134
 
102
135
  /** 按编号找收藏表情;编号不存在时返回 undefined。 */
103
- async resolve(faces: readonly CustomFace[], id: number): Promise<FavoriteRow | undefined> {
104
- const rows = await this.sync(faces)
136
+ async resolve(
137
+ faces: readonly CustomFace[],
138
+ id: number,
139
+ collected: readonly CollectedSticker[] = [],
140
+ ): Promise<FavoriteRow | undefined> {
141
+ const rows = await this.sync(faces, collected)
105
142
  return rows.find((row) => row.id === id)
106
143
  }
107
144
 
@@ -1,6 +1,7 @@
1
1
  import { Mutex } from "async-mutex"
2
2
  import type { Logger } from "../logger"
3
3
  import { sanitizeUntrustedText } from "../model-view"
4
+ import type { CollectedSticker } from "./collection"
4
5
 
5
6
  /**
6
7
  * NapCat 收藏表情(自定义表情)的详情。
@@ -57,6 +58,8 @@ export interface FavoriteRow {
57
58
  face: CustomFace
58
59
  /** 收藏表情当前的标签。 */
59
60
  tag: string
61
+ /** 本机收集的表情;QQ 收藏表情没有这个字段。 */
62
+ collected?: CollectedSticker
60
63
  }
61
64
 
62
65
  /**
@@ -66,7 +69,10 @@ export interface FavoriteRow {
66
69
  */
67
70
  export function formatFavoriteList(rows: readonly FavoriteRow[]): string {
68
71
  if (rows.length === 0) return "没有读取到收藏表情。"
69
- const lines = rows.map((row) => `${row.id}. ${row.tag || "(未标注)"}`)
72
+ const lines = rows.map((row) => {
73
+ const tag = row.tag || "(未标注)"
74
+ return `${row.id}. ${tag}${row.collected ? "(本机收藏)" : ""}`
75
+ })
70
76
  return [`收藏表情(编号即发送用的 id,共 ${rows.length} 个)`, ...lines].join("\n")
71
77
  }
72
78
 
@@ -0,0 +1,82 @@
1
+ import { lstat, mkdir, open, readFile } from "node:fs/promises"
2
+ import { dirname } from "node:path"
3
+ import writeFileAtomic from "write-file-atomic"
4
+
5
+ /**
6
+ * 配置文件的原子写。
7
+ *
8
+ * 临时文件 + fsync + rename:中途失败不会留下半截文件;
9
+ * 写之前把旧内容存成 `.bak`,写坏了还能翻回去。
10
+ * `config.json`、`chat-overrides.json` 与 `tool-profiles.json` 共用这一份实现。
11
+ *
12
+ * 目标必须是普通文件:符号链接一律拒绝写。`write-file-atomic` 会把临时文件
13
+ * rename 到链接指向的真实文件上,链接本身还在,但替换的是别人的 inode;
14
+ * 链接要是被别处种下的,写出去的内容就落到了意料之外的地方。
15
+ */
16
+
17
+ /** 配置文件权限:只有本人可读写。 */
18
+ export const FILE_MODE = 0o600
19
+
20
+ /** 配置文件所在目录的权限:只有本人可进入。 */
21
+ export const DIR_MODE = 0o700
22
+
23
+ /** 目标是否是指向别处的符号链接。 */
24
+ async function isSymlink(path: string): Promise<boolean> {
25
+ const info = await lstat(path).catch(() => undefined)
26
+ return info?.isSymbolicLink() ?? false
27
+ }
28
+
29
+ /**
30
+ * 目录 fsync:把 rename 之后的目录项刷盘。
31
+ *
32
+ * 文件本身已经 fsync 过,但没有这一步,断电时目录项可能还没落盘。
33
+ * 不是所有平台都支持对目录 fsync,失败就跳过:这一步只是加固,不是唯一保障。
34
+ */
35
+ async function fsyncDirectory(path: string): Promise<void> {
36
+ let handle: Awaited<ReturnType<typeof open>> | undefined
37
+ try {
38
+ handle = await open(path, "r")
39
+ await handle.sync()
40
+ } catch {
41
+ // 平台或文件系统不支持对目录 fsync:跳过。
42
+ } finally {
43
+ await handle?.close().catch(() => {})
44
+ }
45
+ }
46
+
47
+ /**
48
+ * 原子写 JSON 文件。
49
+ *
50
+ * 目录按 `0700` 创建,文件按 `0600` 写;备份由调用方单独做。
51
+ *
52
+ * @throws 目标是符号链接时抛错,避免写穿到别处。
53
+ */
54
+ export async function writeJsonAtomic(path: string, value: unknown): Promise<void> {
55
+ await mkdir(dirname(path), { recursive: true, mode: DIR_MODE })
56
+ if (await isSymlink(path)) {
57
+ throw new Error(`拒绝写入符号链接:${path}(请把它换成普通文件再试)`)
58
+ }
59
+ const text = `${JSON.stringify(value, null, 2)}\n`
60
+ await writeFileAtomic(path, text, { mode: FILE_MODE, fsync: true })
61
+ await fsyncDirectory(dirname(path))
62
+ }
63
+
64
+ /**
65
+ * 把当前内容存成 `.bak`。
66
+ *
67
+ * 文件不存在时跳过;`.bak` 是符号链接时拒绝写;其它错误照常抛出,
68
+ * 由调用方决定是记日志还是中断。
69
+ */
70
+ export async function backupFile(path: string): Promise<void> {
71
+ const target = `${path}.bak`
72
+ if (await isSymlink(target)) {
73
+ throw new Error(`拒绝写入符号链接:${target}(请把它换成普通文件再试)`)
74
+ }
75
+ try {
76
+ const text = await readFile(path, "utf8")
77
+ await writeFileAtomic(target, text, { mode: FILE_MODE })
78
+ } catch (error) {
79
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return
80
+ throw error
81
+ }
82
+ }
package/src/home.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { mkdir } from "node:fs/promises"
2
2
  import { homedir } from "node:os"
3
- import { isAbsolute, join } from "node:path"
3
+ import { dirname, isAbsolute, join } from "node:path"
4
4
  import type { Logger } from "./logger"
5
5
 
6
6
  /**
@@ -13,6 +13,8 @@ import type { Logger } from "./logger"
13
13
  export interface BotHome {
14
14
  /** 会话统一所在的绝对路径。 */
15
15
  directory: string
16
+ /** 共享状态的跨进程写锁路径;不设就不加文件锁。 */
17
+ lockPath?: string
16
18
  }
17
19
 
18
20
  /** 默认工作目录:`$XDG_DATA_HOME/opencode-qq-bot/workspace`。 */
@@ -30,8 +32,10 @@ export function defaultHome(): string {
30
32
  export async function resolveHome(logger: Logger): Promise<BotHome> {
31
33
  const directory = defaultHome()
32
34
  await mkdir(directory, { recursive: true, mode: 0o700 })
35
+ // 写锁放在工作目录的同级:工作目录本身是会话目录,不往里面塞杂物。
36
+ const lockPath = join(dirname(directory), "state.lock")
33
37
  logger.debug(`机器人工作目录:${directory}`)
34
- return { directory }
38
+ return { directory, lockPath }
35
39
  }
36
40
 
37
41
  /** 展开路径开头的 `~` 或 `~/`,其余原样返回。 */