@linjz/opencode-qqbot 0.3.19 → 0.3.21

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,145 @@
1
+ // @input: fs/path/crypto(角色级摘要锚点持久化)
2
+ // @output: createMirrorAnchorStore、pruneMirrorAnchorEntries、MirrorAnchorEntry
3
+ // @pos: core - QQ 发送回执 ref_idx → (用户,会话) 的有界持久化索引
4
+ import {
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ renameSync,
9
+ unlinkSync,
10
+ writeFileSync,
11
+ } from "node:fs"
12
+ import { dirname } from "node:path"
13
+ import { randomUUID } from "node:crypto"
14
+
15
+ export const MIRROR_ANCHOR_TTL_MS = 24 * 60 * 60 * 1000
16
+ export const MIRROR_ANCHOR_MAX_PER_USER = 500
17
+
18
+ export interface MirrorAnchorEntry {
19
+ /** 发送响应 ext_info.ref_idx;入站 ref_msg_idx 的 lookup 主键 */
20
+ refIdx: string
21
+ /** 发送响应 id;仅诊断/撤回关联,不参与引用 lookup */
22
+ messageId: string
23
+ userId: string
24
+ sessionId: string
25
+ title: string
26
+ sentAt: number
27
+ }
28
+
29
+ export interface MirrorAnchorStore {
30
+ readonly filePath: string
31
+ record: (entry: MirrorAnchorEntry) => void
32
+ resolve: (userId: string, refIdx: string | undefined, now?: number) => MirrorAnchorEntry | undefined
33
+ list: () => MirrorAnchorEntry[]
34
+ }
35
+
36
+ interface AnchorDocument {
37
+ version: 1
38
+ entries: MirrorAnchorEntry[]
39
+ }
40
+
41
+ function validEntry(value: unknown): value is MirrorAnchorEntry {
42
+ const entry = value as Partial<MirrorAnchorEntry> | null
43
+ return !!entry &&
44
+ typeof entry.refIdx === "string" && !!entry.refIdx &&
45
+ typeof entry.messageId === "string" && !!entry.messageId &&
46
+ typeof entry.userId === "string" && !!entry.userId &&
47
+ typeof entry.sessionId === "string" && !!entry.sessionId &&
48
+ typeof entry.title === "string" &&
49
+ typeof entry.sentAt === "number" && Number.isFinite(entry.sentAt) && entry.sentAt > 0
50
+ }
51
+
52
+ /** TTL + 每用户 LRU;返回按 sentAt 升序排列,便于稳定落盘与测试。 */
53
+ export function pruneMirrorAnchorEntries(
54
+ input: readonly MirrorAnchorEntry[],
55
+ now = Date.now(),
56
+ ): MirrorAnchorEntry[] {
57
+ const fresh = input.filter((entry) =>
58
+ validEntry(entry) && entry.sentAt <= now && now - entry.sentAt < MIRROR_ANCHOR_TTL_MS,
59
+ )
60
+ const newestFirst = [...fresh].sort((a, b) => b.sentAt - a.sentAt)
61
+ const counts = new Map<string, number>()
62
+ const seen = new Set<string>()
63
+ const retained: MirrorAnchorEntry[] = []
64
+ for (const entry of newestFirst) {
65
+ const identity = `${entry.userId}\u0000${entry.refIdx}`
66
+ if (seen.has(identity)) continue
67
+ const count = counts.get(entry.userId) ?? 0
68
+ if (count >= MIRROR_ANCHOR_MAX_PER_USER) continue
69
+ seen.add(identity)
70
+ counts.set(entry.userId, count + 1)
71
+ retained.push(entry)
72
+ }
73
+ return retained.sort((a, b) => a.sentAt - b.sentAt)
74
+ }
75
+
76
+ export function createMirrorAnchorStore(filePath: string): MirrorAnchorStore {
77
+ let entries: MirrorAnchorEntry[] = []
78
+
79
+ function save(nextEntries: MirrorAnchorEntry[] = entries): void {
80
+ const document: AnchorDocument = { version: 1, entries: nextEntries }
81
+ mkdirSync(dirname(filePath), { recursive: true })
82
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`
83
+ try {
84
+ writeFileSync(temporary, JSON.stringify(document, null, 2), { mode: 0o600 })
85
+ renameSync(temporary, filePath)
86
+ } catch (error) {
87
+ try { unlinkSync(temporary) } catch { /* 已 rename 或清理失败 */ }
88
+ throw error
89
+ }
90
+ }
91
+
92
+ try {
93
+ if (existsSync(filePath)) {
94
+ const parsed = JSON.parse(readFileSync(filePath, "utf8").replace(/^\uFEFF/, "")) as Partial<AnchorDocument>
95
+ if (parsed.version !== 1 || !Array.isArray(parsed.entries)) throw new Error("锚点文件格式无效")
96
+ const loaded = parsed.entries.filter(validEntry)
97
+ const pruned = pruneMirrorAnchorEntries(loaded)
98
+ entries = pruned
99
+ if (loaded.length !== parsed.entries.length || pruned.length !== loaded.length) save()
100
+ }
101
+ } catch (error) {
102
+ // 原字节保留在诊断副本;空表意味着旧摘要一律按未知锚点 fail-closed。
103
+ try {
104
+ const backup = `${filePath}.corrupt-${Date.now()}`
105
+ renameSync(filePath, backup)
106
+ console.error(`[mirror-anchor] 锚点文件损坏,已保留诊断副本:${backup}`)
107
+ } catch (backupError) {
108
+ console.error("[mirror-anchor] 损坏文件备份失败:", backupError)
109
+ }
110
+ entries = []
111
+ console.error("[mirror-anchor] 锚点恢复失败,按空表 fail-closed:", error)
112
+ }
113
+
114
+ return {
115
+ filePath,
116
+ record(entry): void {
117
+ if (!validEntry(entry)) throw new Error("摘要锚点字段不完整")
118
+ // 同步读改写:单角色事件循环内天然串行;原子 rename 防半截文件。
119
+ const next = pruneMirrorAnchorEntries([
120
+ ...entries.filter((item) => !(item.userId === entry.userId && item.refIdx === entry.refIdx)),
121
+ entry,
122
+ ])
123
+ // 先盘后备内存:落盘失败的锚点绝不可在本进程内侥幸放行。
124
+ save(next)
125
+ entries = next
126
+ },
127
+ resolve(userId, refIdx, now = Date.now()): MirrorAnchorEntry | undefined {
128
+ if (!refIdx) return undefined
129
+ const entry = entries.find((item) => item.userId === userId && item.refIdx === refIdx)
130
+ if (!entry) return undefined
131
+ if (entry.sentAt > now || now - entry.sentAt >= MIRROR_ANCHOR_TTL_MS) {
132
+ const before = entries.length
133
+ entries = pruneMirrorAnchorEntries(entries, now)
134
+ if (entries.length !== before) {
135
+ try { save() } catch (error) { console.error("[mirror-anchor] 过期锚点清理失败:", error) }
136
+ }
137
+ return undefined
138
+ }
139
+ return { ...entry }
140
+ },
141
+ list(): MirrorAnchorEntry[] {
142
+ return entries.map((entry) => ({ ...entry }))
143
+ },
144
+ }
145
+ }
@@ -7,8 +7,17 @@ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
7
7
  import type { MessageContext } from "../qq/types.js"
8
8
  import type { OpencodeClient } from "../opencode/client.js"
9
9
  import { createEventStream } from "../opencode/eventstream.js"
10
- import { buildDigest, digestAnchorUserId, digestTurnKey } from "../opencode/mirror.js"
10
+ import {
11
+ buildDigest,
12
+ clipDigestTitle,
13
+ digestAnchorUserId,
14
+ digestSessionLabel,
15
+ digestTurnKey,
16
+ } from "../opencode/mirror.js"
11
17
  import { laneKeyOf } from "./message-queue.js"
18
+ import { redactSecrets } from "../opencode/history.js"
19
+ import type { DeliveryContentOptions, OnSentMessage } from "./delivery.js"
20
+ import type { MirrorAnchorStore } from "./mirror-anchors.js"
12
21
  import type { SessionManager } from "../opencode/sessions.js"
13
22
  import type { MirrorApi } from "../commands.js"
14
23
 
@@ -55,11 +64,18 @@ export interface MirrorDeps {
55
64
  eventStream: EventStream
56
65
  client: OpencodeClient
57
66
  lastCtx: ReadonlyMap<string, MessageContext> // bridge 拥有写权,本域只读
58
- safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
67
+ safeDeliver: (
68
+ ctx: MessageContext,
69
+ text: string,
70
+ onSent?: OnSentMessage,
71
+ content?: DeliveryContentOptions,
72
+ ) => Promise<boolean>
59
73
  bgWaits: ReadonlyMap<string, { cancel: () => void }> // 后台等待在途则不解锁
60
74
  busyUsers: ReadonlySet<string> // 会话主人在忙则不解锁(5 秒宽限内再判定)
61
75
  /** 多角色(2026-11-17):镜像开关文件可按角色注入;缺省 legacy 全局 settings.json */
62
76
  settingsFile?: string
77
+ /** 角色级摘要回复锚点;缺省仅用于轻量组件测试,不持久化。 */
78
+ anchorStore?: MirrorAnchorStore
63
79
  /** A 方案(2026-11-23):摘要投递前过 cron 标记钩——注册提醒并返回剥净正文。
64
80
  * 桌面端发起的回合也会输出 QQBOT_PAYLOAD,不经此钩会原样泄漏到 QQ。 */
65
81
  onDigest?: (userId: string, digest: string) => string
@@ -89,28 +105,52 @@ export function createMirror(deps: MirrorDeps): Mirror {
89
105
  // 本册,镜像前核对摘要锚定的用户消息 id 是否命中——重放再迟也改变不了消息来源。
90
106
  const qqPromptIds = new Map<string, Set<string>>() // sessionId -> QQ 派发过的 promptId 环
91
107
  const QQ_PROMPT_ID_CAP = 200
108
+ const MIRROR_SESSION_STATE_CAP = 500
92
109
  function markQqPrompt(sessionId: string, promptId: string): void {
93
110
  if (!promptId) return
94
- let set = qqPromptIds.get(sessionId)
95
- if (!set) {
96
- set = new Set()
97
- qqPromptIds.set(sessionId, set)
98
- }
111
+ const set = qqPromptIds.get(sessionId) ?? new Set<string>()
112
+ qqPromptIds.delete(sessionId) // LRU:最近使用移到末尾
99
113
  if (set.size >= QQ_PROMPT_ID_CAP) {
100
114
  const first = set.values().next().value
101
115
  if (first !== undefined) set.delete(first)
102
116
  }
103
117
  set.add(promptId)
118
+ qqPromptIds.set(sessionId, set)
119
+ while (qqPromptIds.size > MIRROR_SESSION_STATE_CAP) {
120
+ const oldest = qqPromptIds.keys().next().value
121
+ if (oldest === undefined) break
122
+ qqPromptIds.delete(oldest)
123
+ }
104
124
  }
105
125
  const mirroredTurns = new Map<string, string>() // 逻辑回合幂等:多 location/重复完成事件只投一次
126
+ function rememberMirroredTurn(sessionId: string, turnKey: string): void {
127
+ mirroredTurns.delete(sessionId)
128
+ mirroredTurns.set(sessionId, turnKey)
129
+ while (mirroredTurns.size > MIRROR_SESSION_STATE_CAP) {
130
+ const oldest = mirroredTurns.keys().next().value
131
+ if (oldest === undefined) break
132
+ mirroredTurns.delete(oldest)
133
+ }
134
+ }
106
135
  const mirrorState = { enabled: loadMirrorEnabled(deps.settingsFile) }
107
136
 
108
137
  // ===== 摘要镜像(E 阶段 A 方案):桌面会话轮次完成 → QQ 摘要卡 =====
109
138
  // 与 /watch 观察推送互补:观察给过程里程碑,镜像给问答正文摘要。
110
139
  // QQ 自己发起的轮次由 promptAndWait 正常回复,不重复镜像(qqTurnActive 守卫)。
140
+ // 订阅不是历史累加:始终是「当前绑定 sessionId 去重集」的幂等投影。
111
141
  function ensureMirrorSubs(): void {
112
- if (!mirrorState.enabled) return
113
- for (const { sessionId } of sessions.all()) {
142
+ const desired = new Set(
143
+ (mirrorState.enabled ? sessions.all() : []).map((binding) => binding.sessionId),
144
+ )
145
+ let added = 0
146
+ let removed = 0
147
+ for (const [sessionId, unsub] of [...mirrorUnsubs]) {
148
+ if (desired.has(sessionId)) continue
149
+ unsub()
150
+ mirrorUnsubs.delete(sessionId)
151
+ removed++
152
+ }
153
+ for (const sessionId of desired) {
114
154
  if (mirrorUnsubs.has(sessionId)) continue
115
155
  mirrorUnsubs.set(
116
156
  sessionId,
@@ -124,13 +164,21 @@ export function createMirror(deps: MirrorDeps): Mirror {
124
164
  void mirrorTurn(sessionId)
125
165
  }),
126
166
  )
167
+ added++
168
+ }
169
+ if (added > 0 || removed > 0) {
170
+ console.log(
171
+ `[mirror-reconcile] desired=${desired.size} added=${added} removed=${removed} actual=${mirrorUnsubs.size}`,
172
+ )
127
173
  }
128
174
  }
129
175
 
130
- function disableMirrorSubs(): void {
131
- for (const unsub of mirrorUnsubs.values()) unsub()
132
- mirrorUnsubs.clear()
176
+ // 所有绑定变更即时对账;60s 周期只作遗漏兜底。定时器不阻止进程退出。
177
+ if (typeof sessions.onBindingChange === "function") {
178
+ sessions.onBindingChange(() => ensureMirrorSubs())
133
179
  }
180
+ const reconcileTimer = setInterval(ensureMirrorSubs, 60_000)
181
+ reconcileTimer.unref?.()
134
182
 
135
183
  // QQ 轮次结束后延迟解锁镜像:SSE 完成事件可能晚于 promptAndWait 返回,
136
184
  // 5 秒宽限内若又有新 QQ 回合/后台等待在途则不解锁(防竞态开窗)。
@@ -149,11 +197,21 @@ export function createMirror(deps: MirrorDeps): Mirror {
149
197
 
150
198
  async function mirrorTurn(sessionID: string): Promise<void> {
151
199
  try {
152
- const owners = sessions.all().filter((x) => x.sessionId === sessionID).map((x) => x.userId)
200
+ const bindings = sessions.all().filter((x) => x.sessionId === sessionID)
201
+ const owners = bindings.map((x) => x.userId)
153
202
  if (owners.length === 0) {
154
203
  console.log(`[mirror] 跳过:会话无映射主人 session=${sessionID}`)
155
204
  return
156
205
  }
206
+ let title: string | undefined
207
+ if (typeof client.session.get === "function") {
208
+ try {
209
+ title = (await client.session.get({ path: { id: sessionID } }))?.data?.title
210
+ } catch {
211
+ // 标题只是展示元数据:服务端读取失败走映射缓存,不阻断摘要正文。
212
+ }
213
+ }
214
+ title ??= bindings.find((binding) => binding.title?.trim())?.title
157
215
  const listJson = await client.session.messages({ path: { id: sessionID } })
158
216
  const messages = listJson?.data ?? []
159
217
  const turnKey = digestTurnKey(messages)
@@ -167,16 +225,19 @@ export function createMirror(deps: MirrorDeps): Mirror {
167
225
  const anchorId = digestAnchorUserId(messages)
168
226
  if (anchorId && qqPromptIds.get(sessionID)?.has(anchorId)) {
169
227
  console.log(`[mirror] 跳过:QQ 直答回合(来源身份核对命中)session=${sessionID} prompt=${anchorId}`)
170
- if (turnKey) mirroredTurns.set(sessionID, turnKey)
228
+ if (turnKey) rememberMirroredTurn(sessionID, turnKey)
171
229
  return
172
230
  }
173
- const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID))
231
+ const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID), {
232
+ sessionId: sessionID,
233
+ title,
234
+ })
174
235
  if (!digest) {
175
236
  console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`)
176
237
  return
177
238
  }
178
239
  // 在投递前占位:两个完成事件并发到达时,后到的回调也会命中同一回合并被去重。
179
- if (turnKey) mirroredTurns.set(sessionID, turnKey)
240
+ if (turnKey) rememberMirroredTurn(sessionID, turnKey)
180
241
  for (const userId of owners) {
181
242
  // 无最近 ctx(重启后尚未收到新消息)→ 构造主动通道 ctx,
182
243
  // deliver 的被动尝试失败会自然降级为主动消息(D4 配额内)。
@@ -188,7 +249,33 @@ export function createMirror(deps: MirrorDeps): Mirror {
188
249
  const cronHook = deps.onDigest
189
250
  const outText = cronHook ? cronHook(userId, digest) : digest
190
251
  if (!outText.trim()) continue // 纯提醒标记的摘要:注册即全部语义,无可镜像内容
191
- await safeDeliver(ctx, outText)
252
+ const onSent: OnSentMessage = (receipt) => {
253
+ if (!deps.anchorStore) return
254
+ if (!receipt.refIdx) {
255
+ console.warn(
256
+ `[mirror-anchor] QQ 未返回 ref_idx,摘要不可安全路由 session=${sessionID} user=${userId.slice(0, 8)}…`,
257
+ )
258
+ return
259
+ }
260
+ try {
261
+ deps.anchorStore.record({
262
+ refIdx: receipt.refIdx,
263
+ messageId: receipt.id,
264
+ userId,
265
+ sessionId: sessionID,
266
+ title: clipDigestTitle(redactSecrets(title ?? "")),
267
+ sentAt: Date.now(),
268
+ })
269
+ console.log(
270
+ `[mirror-anchor] 已登记 session=${digestSessionLabel(sessionID)} user=${userId.slice(0, 8)}…`,
271
+ )
272
+ } catch (error) {
273
+ console.error("[mirror-anchor] 锚点落盘失败,后续引用将 fail-closed:", error)
274
+ }
275
+ }
276
+ await safeDeliver(ctx, outText, onSent, {
277
+ continuationPrefix: `📋 摘要续 · ${digestSessionLabel(sessionID)}\n`,
278
+ })
192
279
  }
193
280
  console.log(`[mirror] 会话 ${sessionID} 摘要已镜像给 ${owners.length} 个用户`)
194
281
  } catch (error) {
@@ -204,17 +291,20 @@ export function createMirror(deps: MirrorDeps): Mirror {
204
291
  if (enabled) {
205
292
  if (!prev) ensureMirrorSubs()
206
293
  } else {
207
- disableMirrorSubs()
294
+ ensureMirrorSubs()
208
295
  }
209
296
  return enabled
210
297
  ? "✅ 摘要镜像已开启:桌面会话轮次完成后推送问答摘要"
211
298
  : "🔇 摘要镜像已关闭(/status mirror on 重新开启)"
212
299
  },
213
300
  status() {
214
- const subs = mirrorUnsubs.size
215
- return mirrorState.enabled
216
- ? `📋 摘要镜像:开(已挂 ${subs} 个会话订阅)`
217
- : "📋 摘要镜像:关(/status mirror on 开启)"
301
+ if (!mirrorState.enabled) return "📋 摘要镜像:关(/status mirror on 开启)"
302
+ const desired = new Set(sessions.all().map((binding) => binding.sessionId))
303
+ const actual = mirrorUnsubs.size
304
+ const aligned = desired.size === actual && [...desired].every((sessionId) => mirrorUnsubs.has(sessionId))
305
+ return aligned
306
+ ? "📋 摘要镜像:开"
307
+ : `⚠️ 摘要镜像:开 · 订阅对账异常(期望 ${desired.size} / 实际 ${actual})`
218
308
  },
219
309
  }
220
310
 
@@ -1,7 +1,7 @@
1
1
  // @input: 无依赖(纯文本工具)
2
2
  // @output: cmdInput/cmdEnter 标签构造、stripInteractionTags 兜底剥离、NOTICE 文案目录
3
- // @pos: core - 通知文案目录(2026-11-22 学习吸收轮:融合 dsh-qqbot errors.ts/session-notice.ts
4
- // 目录制之长——用户可见文案单一出口、可测;P0 佐证=QQ 官方文档「文本交互」
3
+ // @pos: core - 通知文案目录(2026-11-22:参考 dsh-qqbot errors.ts/session-notice.ts
4
+ // 的文案目录化设计,用户可见文案单一出口、可测;P0 佐证=QQ 官方文档「文本交互」
5
5
  // bot.q.qq.com/wiki api-v2,2026-10-26 更新版,<qqbot-cmd-input>/<qqbot-cmd-enter> 形状确认)
6
6
  //
7
7
  // ⚠️ 平台边界(官方文档原文):
@@ -64,7 +64,7 @@ export function createNotifySink(options: NotifySinkOptions): NotifySink {
64
64
  const ctx = entry.ctx as MessageContext
65
65
  // fail-closed 校验在入队端(CLI)完成;消费端不再重复校验,outbox 快照不可篡改。
66
66
  // maxAttempts 由 start 透传到 recover/flush:失败达到上限后保持 failed,不再无限退避。
67
- return options.deliver(ctx, text).then(() => ({ delivered: true, text: text.slice(0, 120) }))
67
+ return options.deliver(ctx, text).then((delivered) => ({ delivered, text: text.slice(0, 120) }))
68
68
  })
69
69
  outbox.start({ recover: true, maxAttempts }).catch((error) => {
70
70
  console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error)
@@ -0,0 +1,234 @@
1
+ // @input: node:fs/node:zlib(OOXML zip/XML 只读解析)
2
+ // @output: officeKindForPath, isLegacyOfficePath, extractOfficeTextFromFile
3
+ // @pos: core - Office Open XML 文档文本提取(docx/xlsx/pptx 及 macro 变体)
4
+ //
5
+ // 设计边界:只支持 ZIP 容器 + XML 的现代 Office 格式;传统 .doc/.xls/.ppt
6
+ // 是 OLE 二进制,跨平台零依赖无法安全解析,由调用方明确拒识并指引转换。
7
+ import { readFileSync } from "node:fs"
8
+ import { inflateRawSync } from "node:zlib"
9
+
10
+ export type OfficeKind = "docx" | "xlsx" | "pptx"
11
+
12
+ const MAX_ENTRY_COUNT = 10_000
13
+ const MAX_ENTRY_UNCOMPRESSED_BYTES = 50 * 1024 * 1024
14
+ export const MAX_OFFICE_TEXT_CHARS = 200_000
15
+
16
+ export function officeKindForPath(path: string): OfficeKind | null {
17
+ const ext = path.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] ?? ""
18
+ if (ext === "docx" || ext === "docm") return "docx"
19
+ if (ext === "xlsx" || ext === "xlsm") return "xlsx"
20
+ if (ext === "pptx" || ext === "pptm") return "pptx"
21
+ return null
22
+ }
23
+
24
+ export function isLegacyOfficePath(path: string): boolean {
25
+ return /\.(doc|xls|ppt)$/i.test(path)
26
+ }
27
+
28
+ interface ZipEntry {
29
+ name: string
30
+ flags: number
31
+ method: number
32
+ compressedSize: number
33
+ uncompressedSize: number
34
+ localHeaderOffset: number
35
+ }
36
+
37
+ function findEndOfCentralDirectory(buf: Buffer): number {
38
+ const min = Math.max(0, buf.length - 65_557) // EOCD 22B + 最大 comment 65535B
39
+ for (let i = buf.length - 22; i >= min; i--) {
40
+ if (buf.readUInt32LE(i) === 0x06054b50) return i
41
+ }
42
+ throw new Error("不是有效的 ZIP/OOXML 文件")
43
+ }
44
+
45
+ function readZipEntries(buf: Buffer): Map<string, ZipEntry> {
46
+ const eocd = findEndOfCentralDirectory(buf)
47
+ const count = buf.readUInt16LE(eocd + 10)
48
+ const centralOffset = buf.readUInt32LE(eocd + 16)
49
+ if (count > MAX_ENTRY_COUNT) throw new Error("ZIP 条目过多")
50
+ const entries = new Map<string, ZipEntry>()
51
+ let offset = centralOffset
52
+ for (let i = 0; i < count; i++) {
53
+ if (offset + 46 > buf.length || buf.readUInt32LE(offset) !== 0x02014b50) {
54
+ throw new Error("ZIP 中央目录损坏")
55
+ }
56
+ const flags = buf.readUInt16LE(offset + 8)
57
+ const method = buf.readUInt16LE(offset + 10)
58
+ const compressedSize = buf.readUInt32LE(offset + 20)
59
+ const uncompressedSize = buf.readUInt32LE(offset + 24)
60
+ const nameLength = buf.readUInt16LE(offset + 28)
61
+ const extraLength = buf.readUInt16LE(offset + 30)
62
+ const commentLength = buf.readUInt16LE(offset + 32)
63
+ const localHeaderOffset = buf.readUInt32LE(offset + 42)
64
+ const name = buf.subarray(offset + 46, offset + 46 + nameLength).toString("utf8")
65
+ if (uncompressedSize > MAX_ENTRY_UNCOMPRESSED_BYTES) throw new Error(`ZIP 条目过大:${name}`)
66
+ entries.set(name, { name, flags, method, compressedSize, uncompressedSize, localHeaderOffset })
67
+ offset += 46 + nameLength + extraLength + commentLength
68
+ }
69
+ return entries
70
+ }
71
+
72
+ function readZipEntry(buf: Buffer, entry: ZipEntry): Buffer {
73
+ if ((entry.flags & 0x1) !== 0) throw new Error(`加密 ZIP 条目不支持:${entry.name}`)
74
+ const offset = entry.localHeaderOffset
75
+ if (offset + 30 > buf.length || buf.readUInt32LE(offset) !== 0x04034b50) {
76
+ throw new Error(`ZIP 本地头损坏:${entry.name}`)
77
+ }
78
+ const nameLength = buf.readUInt16LE(offset + 26)
79
+ const extraLength = buf.readUInt16LE(offset + 28)
80
+ const dataOffset = offset + 30 + nameLength + extraLength
81
+ const dataEnd = dataOffset + entry.compressedSize
82
+ if (dataEnd > buf.length) throw new Error(`ZIP 数据越界:${entry.name}`)
83
+ const data = buf.subarray(dataOffset, dataEnd)
84
+ if (entry.method === 0) return Buffer.from(data)
85
+ if (entry.method === 8) {
86
+ const out = inflateRawSync(data)
87
+ if (out.length !== entry.uncompressedSize) throw new Error(`ZIP 解压长度不符:${entry.name}`)
88
+ return out
89
+ }
90
+ throw new Error(`ZIP 压缩方式不支持:${entry.name}`)
91
+ }
92
+
93
+ function xmlUnescape(value: string): string {
94
+ return value
95
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex: string) => String.fromCodePoint(Number.parseInt(hex, 16)))
96
+ .replace(/&#([0-9]+);/g, (_, dec: string) => String.fromCodePoint(Number.parseInt(dec, 10)))
97
+ .replace(/&lt;/g, "<")
98
+ .replace(/&gt;/g, ">")
99
+ .replace(/&quot;/g, '"')
100
+ .replace(/&apos;/g, "'")
101
+ .replace(/&amp;/g, "&")
102
+ }
103
+
104
+ function attrs(tag: string): Record<string, string> {
105
+ const out: Record<string, string> = {}
106
+ for (const match of tag.matchAll(/([\w:]+)\s*=\s*"([^"]*)"/g)) {
107
+ out[match[1]] = xmlUnescape(match[2])
108
+ }
109
+ return out
110
+ }
111
+
112
+ function normalizeExtractedText(value: string): string {
113
+ const cleaned = xmlUnescape(value.replace(/<[^>]+>/g, ""))
114
+ .replace(/\r/g, "")
115
+ .split("\n")
116
+ .map((line) => line.replace(/ +/g, " ").trimEnd())
117
+ .join("\n")
118
+ .replace(/\n{3,}/g, "\n\n")
119
+ .trim()
120
+ return cleaned.length > MAX_OFFICE_TEXT_CHARS
121
+ ? `${cleaned.slice(0, MAX_OFFICE_TEXT_CHARS)}\n…(Office 文档内容过长,已截断)`
122
+ : cleaned
123
+ }
124
+
125
+ function extractDocx(entries: Map<string, ZipEntry>, zip: Buffer): string {
126
+ const entry = entries.get("word/document.xml")
127
+ if (!entry) throw new Error("DOCX 缺少 word/document.xml")
128
+ const xml = readZipEntry(zip, entry).toString("utf8")
129
+ const text = xml
130
+ .replace(/<w:tab\b[^>]*\/>/g, "\t")
131
+ .replace(/<w:br\b[^>]*\/>/g, "\n")
132
+ .replace(/<\/w:p>/g, "\n")
133
+ .replace(/<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g, "$1")
134
+ return normalizeExtractedText(text)
135
+ }
136
+
137
+ function extractPptx(entries: Map<string, ZipEntry>, zip: Buffer): string {
138
+ const slides = [...entries.keys()]
139
+ .filter((name) => /^ppt\/slides\/slide\d+\.xml$/.test(name))
140
+ .sort((a, b) => Number(a.match(/slide(\d+)\.xml$/)?.[1] ?? 0) - Number(b.match(/slide(\d+)\.xml$/)?.[1] ?? 0))
141
+ if (slides.length === 0) throw new Error("PPTX 缺少幻灯片 XML")
142
+ const parts: string[] = []
143
+ for (const [index, name] of slides.entries()) {
144
+ const xml = readZipEntry(zip, entries.get(name)!).toString("utf8")
145
+ const text = xml
146
+ .replace(/<a:br\b[^>]*\/>/g, "\n")
147
+ .replace(/<\/a:p>/g, "\n")
148
+ .replace(/<a:t(?:\s[^>]*)?>([\s\S]*?)<\/a:t>/g, "$1")
149
+ const cleaned = normalizeExtractedText(text)
150
+ if (cleaned) parts.push(`## Slide ${index + 1}\n${cleaned}`)
151
+ }
152
+ return normalizeExtractedText(parts.join("\n\n"))
153
+ }
154
+
155
+ function sharedStrings(entries: Map<string, ZipEntry>, zip: Buffer): string[] {
156
+ const entry = entries.get("xl/sharedStrings.xml")
157
+ if (!entry) return []
158
+ const xml = readZipEntry(zip, entry).toString("utf8")
159
+ const out: string[] = []
160
+ for (const si of xml.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>/g)) {
161
+ const texts = [...si[1].matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((m) => xmlUnescape(m[1]))
162
+ out.push(texts.join(""))
163
+ }
164
+ return out
165
+ }
166
+
167
+ function workbookSheets(entries: Map<string, ZipEntry>, zip: Buffer): Array<{ name: string; path: string }> {
168
+ const workbookEntry = entries.get("xl/workbook.xml")
169
+ if (!workbookEntry) throw new Error("XLSX 缺少 xl/workbook.xml")
170
+ const workbook = readZipEntry(zip, workbookEntry).toString("utf8")
171
+ const rels = new Map<string, string>()
172
+ const relEntry = entries.get("xl/_rels/workbook.xml.rels")
173
+ if (relEntry) {
174
+ const relXml = readZipEntry(zip, relEntry).toString("utf8")
175
+ for (const rel of relXml.matchAll(/<Relationship\b[^>]*>/g)) {
176
+ const a = attrs(rel[0])
177
+ if (a.Id && a.Target) rels.set(a.Id, a.Target.replace(/^\//, ""))
178
+ }
179
+ }
180
+ const sheets: Array<{ name: string; path: string }> = []
181
+ for (const sheet of workbook.matchAll(/<sheet\b[^>]*\/>/g)) {
182
+ const a = attrs(sheet[0])
183
+ const rid = a["r:id"] ?? a.id
184
+ const target = rid ? rels.get(rid) : undefined
185
+ const path = target?.startsWith("xl/") ? target : target ? `xl/${target}` : undefined
186
+ if (a.name && path && entries.has(path)) sheets.push({ name: a.name, path })
187
+ }
188
+ if (sheets.length > 0) return sheets
189
+ return [...entries.keys()]
190
+ .filter((name) => /^xl\/worksheets\/sheet\d+\.xml$/.test(name))
191
+ .sort((a, b) => Number(a.match(/sheet(\d+)\.xml$/)?.[1] ?? 0) - Number(b.match(/sheet(\d+)\.xml$/)?.[1] ?? 0))
192
+ .map((path, index) => ({ name: `Sheet${index + 1}`, path }))
193
+ }
194
+
195
+ function cellText(cellTag: string, body: string, shared: string[]): string {
196
+ const type = attrs(cellTag).t
197
+ if (type === "s") {
198
+ const index = Number(body.match(/<v>(\d+)<\/v>/)?.[1] ?? "-1")
199
+ return shared[index] ?? ""
200
+ }
201
+ if (type === "inlineStr") {
202
+ return [...body.matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((m) => xmlUnescape(m[1])).join("")
203
+ }
204
+ const value = body.match(/<v>([\s\S]*?)<\/v>/)?.[1]
205
+ return value === undefined ? "" : xmlUnescape(value)
206
+ }
207
+
208
+ function extractXlsx(entries: Map<string, ZipEntry>, zip: Buffer): string {
209
+ const shared = sharedStrings(entries, zip)
210
+ const parts: string[] = []
211
+ for (const sheet of workbookSheets(entries, zip)) {
212
+ const xml = readZipEntry(zip, entries.get(sheet.path)!).toString("utf8")
213
+ const rows: string[] = []
214
+ for (const row of xml.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)) {
215
+ const cells: string[] = []
216
+ for (const cell of row[1].matchAll(/<c\b([^>]*)>([\s\S]*?)<\/c>/g)) {
217
+ cells.push(cellText(`<c ${cell[1]}>`, cell[2], shared))
218
+ }
219
+ if (cells.some((cell) => cell.trim())) rows.push(cells.join("\t").trimEnd())
220
+ }
221
+ if (rows.length > 0) parts.push(`## Sheet: ${sheet.name}\n${rows.join("\n")}`)
222
+ }
223
+ return normalizeExtractedText(parts.join("\n\n"))
224
+ }
225
+
226
+ export function extractOfficeTextFromFile(filePath: string): string {
227
+ const kind = officeKindForPath(filePath)
228
+ if (!kind) throw new Error("不是支持的 Office 文档格式")
229
+ const zip = readFileSync(filePath)
230
+ const entries = readZipEntries(zip)
231
+ if (kind === "docx") return extractDocx(entries, zip)
232
+ if (kind === "pptx") return extractPptx(entries, zip)
233
+ return extractXlsx(entries, zip)
234
+ }
@@ -1,6 +1,8 @@
1
1
  // @input: 纯文本(无依赖)
2
2
  // @output: stripScaffolding
3
- // @pos: core - 出站脚手架消毒(2026-11-23 学习吸收 Z 项,源=openclaw outbound/sanitize.ts P0)
3
+ // @pos: core - 出站脚手架消毒(2026-11-23 派生修订 Z 项,源=openclaw outbound/sanitize.ts P0)
4
+ // 本文件保留上游主要正则与剥离顺序,合并残留标签规则并调整返回处理,属于派生修订。
5
+ // 上游版权与许可见 THIRD_PARTY_NOTICES.md。
4
6
  //
5
7
  // 背景:模型偶发把内部推理/脚手架块写进正文( thinking/system-reminder 等),
6
8
  // QQ 会把原始标签渲染给用户。出站前统一剥离——主路径(formatForQQMarkdown)与