@linjz/opencode-qqbot 0.3.12 → 0.3.13

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/bin/openqq-setup.mjs +50 -50
  2. package/bin/openqq.js +47 -47
  3. package/dist/opencode-qqbot-plugin.js +3 -3
  4. package/dist/openqq-bot.js +1033 -191
  5. package/package.json +2 -2
  6. package/src/_FOLDER.md +19 -19
  7. package/src/bridge.ts +135 -15
  8. package/src/commands.ts +554 -554
  9. package/src/config.ts +121 -121
  10. package/src/core/bot-launcher.ts +146 -146
  11. package/src/core/card-approval.ts +146 -146
  12. package/src/core/context-buffer.ts +78 -78
  13. package/src/core/delivery.ts +105 -13
  14. package/src/core/discovery.ts +151 -151
  15. package/src/core/error-rescue.ts +33 -33
  16. package/src/core/file-log.ts +45 -45
  17. package/src/core/form-bridge.ts +388 -72
  18. package/src/core/form-journal.ts +214 -0
  19. package/src/core/gateway-state.ts +68 -0
  20. package/src/core/inbound-dedupe.ts +43 -0
  21. package/src/core/inflight-journal.ts +148 -21
  22. package/src/core/instance-lock.ts +28 -1
  23. package/src/core/linkwatch.ts +195 -195
  24. package/src/core/message-queue.ts +11 -0
  25. package/src/core/mirror.ts +182 -182
  26. package/src/core/outbox.ts +522 -0
  27. package/src/core/permission.ts +301 -301
  28. package/src/core/reply-limiter.ts +106 -106
  29. package/src/core/send-media.ts +90 -90
  30. package/src/core/util.ts +8 -8
  31. package/src/index.ts +162 -162
  32. package/src/opencode/_FOLDER.md +11 -11
  33. package/src/opencode/client.ts +89 -8
  34. package/src/opencode/eventstream.ts +138 -138
  35. package/src/opencode/history.ts +143 -143
  36. package/src/opencode/mirror.ts +85 -85
  37. package/src/opencode/sessions.ts +158 -158
  38. package/src/plugin-entry.ts +112 -112
  39. package/src/qq/_FOLDER.md +13 -13
  40. package/src/qq/api.ts +539 -539
  41. package/src/qq/gateway.ts +69 -20
  42. package/src/qq/media.ts +219 -219
  43. package/src/qq/sender.ts +300 -300
  44. package/src/qq/types.ts +154 -154
  45. package/tsconfig.json +24 -24
@@ -0,0 +1,522 @@
1
+ // @input: fs/path/os/crypto + ../qq/types(MessageContext)
2
+ // @output: createOutbox 及 Outbox 公共类型、保留/退避常量、pruneOutboxEntries
3
+ // @pos: core - 独立持久化出站 Outbox(先落账后发送,至少一次恢复)
4
+ //
5
+ // 文件格式:{ "version": 1, "entries": OutboxEntry[] }。所有 mutation 都在
6
+ // <outbox>.lock 短文件锁内重新读盘,再经临时文件 + rename 原子替换。
7
+ // 网络 handler 不持文件锁;sending + leaseOwner/leaseUntil 防跨进程并发双发。
8
+ import {
9
+ closeSync,
10
+ existsSync,
11
+ mkdirSync,
12
+ openSync,
13
+ readFileSync,
14
+ renameSync,
15
+ statSync,
16
+ unlinkSync,
17
+ writeFileSync,
18
+ } from "node:fs"
19
+ import { homedir } from "node:os"
20
+ import { dirname, join } from "node:path"
21
+ import { randomUUID } from "node:crypto"
22
+ import type { MessageContext } from "../qq/types.js"
23
+
24
+ export type OutboxState = "pending" | "sending" | "sent" | "failed"
25
+ export type { MessageContext }
26
+
27
+ export interface OutboxEntry<Payload = unknown, Receipt = unknown> {
28
+ id: string
29
+ kind: string
30
+ ctx: MessageContext
31
+ /** 调用方负责提供可 JSON 序列化的数据;入队时会做 JSON 快照。 */
32
+ payload: Payload
33
+ sessionId?: string
34
+ turnId?: string
35
+ state: OutboxState
36
+ /** 已开始的网络发送次数(claim sending 时递增)。 */
37
+ attempts: number
38
+ createdAt: number
39
+ updatedAt: number
40
+ nextAttemptAt: number
41
+ lastError?: string
42
+ receipt?: Receipt
43
+ /** sending 的执行体与租约;其他进程在租约有效时不得再次发送。 */
44
+ leaseOwner?: string
45
+ leaseUntil?: number
46
+ }
47
+
48
+ export interface OutboxEnqueueInput<Payload = unknown> {
49
+ /** 缺省时随机生成;显式 id 在 pending/sending/failed 活跃期用于重入去重。 */
50
+ id?: string
51
+ kind: string
52
+ ctx: MessageContext
53
+ payload: Payload
54
+ sessionId?: string
55
+ turnId?: string
56
+ /** 首次可发送时间,缺省立即。 */
57
+ nextAttemptAt?: number
58
+ }
59
+
60
+ /** handler 必须使用 entry.payload/entry.ctx,返回值原样作为 JSON receipt 落盘。 */
61
+ export type OutboxHandler = (entry: OutboxEntry) => unknown | Promise<unknown>
62
+
63
+ export interface OutboxOptions {
64
+ /** 默认 QQ_OUTBOX_FILE,再默认 ~/.openqq/outbox.json;创建实例时读取环境变量。 */
65
+ filePath?: string
66
+ /** start 的轮询间隔;0 表示禁用定时轮询,便于测试。默认 1000ms。 */
67
+ pollIntervalMs?: number
68
+ /** 首次失败退避,后续指数增长。默认 1000ms。 */
69
+ retryBaseMs?: number
70
+ /** 退避上限,默认 60000ms;0 表示不等待,便于立即重试测试。 */
71
+ retryMaxMs?: number
72
+ /** sending 租约,默认 30000ms。超时接管代表结果未知,允许至少一次重发。 */
73
+ leaseMs?: number
74
+ /** 短文件锁参数;通常无需修改。 */
75
+ lockWaitMs?: number
76
+ lockStaleMs?: number
77
+ }
78
+
79
+ export interface OutboxRecoverResult {
80
+ /** 启动/恢复扫描中,从 sending 转回可重试 pending 的条目。 */
81
+ recovered: OutboxEntry[]
82
+ /** 恢复时已重试耗尽的条目(仅在设置 maxAttempts 时出现)。 */
83
+ exhausted: OutboxEntry[]
84
+ }
85
+
86
+ export interface OutboxDispatchOptions {
87
+ /** 忽略 nextAttemptAt,供人工重试;不影响 sent 的去重与活跃 lease。 */
88
+ force?: boolean
89
+ /** >0 时,失败达到该次数后保持 failed;recover 不会自动重投。 */
90
+ maxAttempts?: number
91
+ }
92
+
93
+ export interface OutboxFlushOptions extends OutboxDispatchOptions {
94
+ /** true 时持续等待退避到期,直到没有本实例可推进的活跃项。默认 false。 */
95
+ wait?: boolean
96
+ }
97
+
98
+ export interface Outbox {
99
+ readonly filePath: string
100
+ register(kind: string, handler: OutboxHandler): () => void
101
+ /** 先持久化 pending,再触发后台 dispatch;返回的是入队时的 pending 快照。 */
102
+ enqueue<Payload = unknown>(input: OutboxEnqueueInput<Payload>): Promise<OutboxEntry<Payload>>
103
+ /** 同进程同 id 复用 Promise;sent 直接返回,活跃 lease 返回 null。 */
104
+ dispatch(id: string, options?: OutboxDispatchOptions): Promise<OutboxEntry | null>
105
+ /** sending 结果未知:租约过期(或 ignoreLeases)转 pending/failed,不处理 sent。 */
106
+ recover(options?: { ignoreLeases?: boolean; maxAttempts?: number }): Promise<OutboxRecoverResult>
107
+ /** 扫描 pending/failed;默认只处理 nextAttemptAt 已到期的项。 */
108
+ flush(options?: OutboxFlushOptions): Promise<OutboxEntry[]>
109
+ start(options?: { recover?: boolean }): Promise<void>
110
+ /** 停止定时器,不等待正在发送的 handler;需要等待时调用 drain。 */
111
+ stop(): void
112
+ /** 等待当前及等待期间新启动的本实例发送全部结束。 */
113
+ drain(): Promise<void>
114
+ list(): Promise<OutboxEntry[]>
115
+ get(id: string): Promise<OutboxEntry | undefined>
116
+ }
117
+
118
+ interface OutboxDocument {
119
+ version: 1
120
+ entries: OutboxEntry[]
121
+ }
122
+
123
+ export const OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000
124
+ export const OUTBOX_SENT_RETENTION_LIMIT = 20
125
+ export const OUTBOX_DEFAULT_RETRY_BASE_MS = 1_000
126
+ export const OUTBOX_DEFAULT_RETRY_MAX_MS = 60_000
127
+
128
+ const DEFAULT_POLL_INTERVAL_MS = 1_000
129
+ const DEFAULT_LEASE_MS = 30_000
130
+ const DEFAULT_LOCK_WAIT_MS = 5_000
131
+ const DEFAULT_LOCK_STALE_MS = 30_000
132
+ const sleepArray = new Int32Array(new SharedArrayBuffer(4))
133
+
134
+ function nonNegative(value: number | undefined, fallback: number, name: string): number {
135
+ const resolved = value ?? fallback
136
+ if (!Number.isFinite(resolved) || resolved < 0) throw new Error(`${name} 必须是 >= 0 的有限数`)
137
+ return resolved
138
+ }
139
+
140
+ function positive(value: number | undefined, fallback: number, name: string): number {
141
+ const resolved = nonNegative(value, fallback, name)
142
+ if (resolved === 0) throw new Error(`${name} 必须 > 0`)
143
+ return resolved
144
+ }
145
+
146
+ function errorText(error: unknown): string {
147
+ return error instanceof Error ? error.message : String(error)
148
+ }
149
+
150
+ function jsonSnapshot<T>(value: T, label: string): T {
151
+ const encoded = JSON.stringify(value)
152
+ if (encoded === undefined) throw new Error(`Outbox ${label} 必须是可 JSON 序列化的值`)
153
+ return JSON.parse(encoded) as T
154
+ }
155
+
156
+ function delay(ms: number): Promise<void> {
157
+ return new Promise((resolve) => setTimeout(resolve, ms))
158
+ }
159
+
160
+ function atomicWrite(filePath: string, document: OutboxDocument): void {
161
+ mkdirSync(dirname(filePath), { recursive: true })
162
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`
163
+ try {
164
+ writeFileSync(temporary, JSON.stringify(document, null, 2), { mode: 0o600 })
165
+ renameSync(temporary, filePath)
166
+ } catch (error) {
167
+ try { unlinkSync(temporary) } catch { /* 已 rename 或清理失败 */ }
168
+ throw error
169
+ }
170
+ }
171
+
172
+ function readDocument(filePath: string, now: number): OutboxDocument {
173
+ if (!existsSync(filePath)) return { version: 1, entries: [] }
174
+ const raw = JSON.parse(readFileSync(filePath, "utf8")) as unknown
175
+ // 只接受本模块明确的文档形状;损坏文件不得被静默当空台账覆盖。
176
+ if (Array.isArray(raw)) {
177
+ return { version: 1, entries: pruneOutboxEntries(raw as OutboxEntry[], now) }
178
+ }
179
+ if (
180
+ typeof raw !== "object" || raw === null ||
181
+ (raw as { version?: unknown }).version !== 1 ||
182
+ !Array.isArray((raw as { entries?: unknown }).entries)
183
+ ) {
184
+ throw new Error(`Outbox 文件格式无效: ${filePath}`)
185
+ }
186
+ const entries = (raw as { entries: OutboxEntry[] }).entries
187
+ return { version: 1, entries: pruneOutboxEntries(entries, now) }
188
+ }
189
+
190
+ /**
191
+ * sent 先按 24h 年龄过滤,再取 updatedAt 最新 20 条;非 sent 全量保留。
192
+ * 输出按 createdAt 升序,createdAt 相同保持原相对顺序,避免活跃项被修剪或重排。
193
+ */
194
+ export function pruneOutboxEntries(entries: OutboxEntry[], now = Date.now()): OutboxEntry[] {
195
+ const indexed = entries.map((entry, index) => ({ entry, index }))
196
+ const retainedSent = new Set(
197
+ indexed
198
+ .filter(({ entry }) => entry.state === "sent" && now - entry.updatedAt <= OUTBOX_SENT_RETENTION_MS)
199
+ .sort((a, b) => b.entry.updatedAt - a.entry.updatedAt || b.index - a.index)
200
+ .slice(0, OUTBOX_SENT_RETENTION_LIMIT)
201
+ .map(({ index }) => index),
202
+ )
203
+ return indexed
204
+ .filter(({ entry, index }) => entry.state !== "sent" || retainedSent.has(index))
205
+ .sort((a, b) => a.entry.createdAt - b.entry.createdAt || a.index - b.index)
206
+ .map(({ entry }) => entry)
207
+ }
208
+
209
+ export function createOutbox(options: OutboxOptions = {}): Outbox {
210
+ const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? join(homedir(), ".openqq", "outbox.json")
211
+ const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs")
212
+ const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs")
213
+ const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs")
214
+ const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs")
215
+ const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs")
216
+ const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs")
217
+ const owner = `${process.pid}:${randomUUID()}`
218
+ const handlers = new Map<string, OutboxHandler>()
219
+ const inFlight = new Map<string, Promise<OutboxEntry | null>>()
220
+ const automatic = new Set<string>()
221
+ let timer: ReturnType<typeof setInterval> | undefined
222
+ let stopped = false
223
+ let flushing: Promise<OutboxEntry[]> | undefined
224
+
225
+ function withLock<T>(fn: () => T): T {
226
+ mkdirSync(dirname(filePath), { recursive: true })
227
+ const lockPath = `${filePath}.lock`
228
+ const token = `${owner}:${Date.now()}:${randomUUID()}`
229
+ const deadline = Date.now() + lockWaitMs
230
+ for (;;) {
231
+ try {
232
+ const fd = openSync(lockPath, "wx", 0o600)
233
+ try { writeFileSync(fd, token) } finally { closeSync(fd) }
234
+ break
235
+ } catch (error) {
236
+ try {
237
+ if (Date.now() - statSync(lockPath).mtimeMs > lockStaleMs) unlinkSync(lockPath)
238
+ } catch { /* 锁已被释放或其他进程正在接管 */ }
239
+ if (Date.now() >= deadline) throw new Error(`Outbox 锁等待超时: ${errorText(error)}`)
240
+ Atomics.wait(sleepArray, 0, 0, 10)
241
+ }
242
+ }
243
+ try {
244
+ return fn()
245
+ } finally {
246
+ try {
247
+ if (readFileSync(lockPath, "utf8") === token) unlinkSync(lockPath)
248
+ } catch { /* 锁已被 stale 清理 */ }
249
+ }
250
+ }
251
+
252
+ function mutate<T>(fn: (entries: OutboxEntry[]) => T): T {
253
+ return withLock(() => {
254
+ const document = readDocument(filePath, Date.now())
255
+ const result = fn(document.entries)
256
+ document.entries = pruneOutboxEntries(document.entries)
257
+ atomicWrite(filePath, document)
258
+ return result
259
+ })
260
+ }
261
+
262
+ function clone<Payload>(entry: OutboxEntry<Payload>): OutboxEntry<Payload> {
263
+ return JSON.parse(JSON.stringify(entry)) as OutboxEntry<Payload>
264
+ }
265
+
266
+ function clearLease(entry: OutboxEntry): void {
267
+ delete entry.leaseOwner
268
+ delete entry.leaseUntil
269
+ }
270
+
271
+ function transitionRecovered(entry: OutboxEntry, now: number, maxAttempts?: number): boolean {
272
+ if (entry.state !== "sending") return false
273
+ const exhausted = maxAttempts !== undefined && entry.attempts >= maxAttempts
274
+ entry.state = exhausted ? "failed" : "pending"
275
+ entry.updatedAt = now
276
+ entry.nextAttemptAt = now
277
+ entry.lastError = exhausted
278
+ ? `${entry.lastError ? `${entry.lastError}; ` : ""}崩溃恢复后已达到 maxAttempts=${maxAttempts}`
279
+ : "进程在 sending 期间退出,发送结果未知;按至少一次语义恢复"
280
+ clearLease(entry)
281
+ return true
282
+ }
283
+
284
+ async function recover(recoverOptions: { ignoreLeases?: boolean; maxAttempts?: number } = {}): Promise<OutboxRecoverResult> {
285
+ const now = Date.now()
286
+ return mutate((entries) => {
287
+ const recovered: OutboxEntry[] = []
288
+ const exhausted: OutboxEntry[] = []
289
+ for (const entry of entries) {
290
+ if (entry.state !== "sending") continue
291
+ // recover 用于进程重启;同进程调用时不得把仍在运行的 lease 抢走。
292
+ if (inFlight.has(entry.id) && entry.leaseOwner?.startsWith(`${owner}:`)) continue
293
+ const expired = entry.leaseUntil === undefined || entry.leaseUntil <= now
294
+ if (!recoverOptions.ignoreLeases && !expired) continue
295
+ transitionRecovered(entry, now, recoverOptions.maxAttempts)
296
+ const snapshot = clone(entry)
297
+ if (snapshot.state === "failed") exhausted.push(snapshot)
298
+ else recovered.push(snapshot)
299
+ }
300
+ return { recovered, exhausted }
301
+ })
302
+ }
303
+
304
+ async function dispatchInternal(id: string, dispatchOptions: OutboxDispatchOptions): Promise<OutboxEntry | null> {
305
+ const handlerlessSnapshot = readDocument(filePath, Date.now()).entries.find((entry) => entry.id === id)
306
+ if (!handlerlessSnapshot) return null
307
+ const handler = handlers.get(handlerlessSnapshot.kind)
308
+ if (!handler) return clone(handlerlessSnapshot)
309
+
310
+ const now = Date.now()
311
+ const token = `${owner}:${randomUUID()}`
312
+ const claimed = withLock(() => {
313
+ const document = readDocument(filePath, now)
314
+ const entry = document.entries.find((candidate) => candidate.id === id)
315
+ if (!entry) return { entry: null } as const
316
+ if (entry.state === "sent") return { entry: clone(entry) } as const
317
+ if (entry.state === "sending" && entry.leaseUntil !== undefined && entry.leaseUntil > now) {
318
+ return { entry: null } as const
319
+ }
320
+ if (
321
+ (entry.state === "pending" || entry.state === "failed" || entry.state === "sending") &&
322
+ !dispatchOptions.force && entry.nextAttemptAt > now
323
+ ) {
324
+ return { entry: clone(entry) } as const
325
+ }
326
+ const maxAttempts = dispatchOptions.maxAttempts
327
+ if (maxAttempts !== undefined && entry.attempts >= maxAttempts) {
328
+ if (entry.state !== "failed") {
329
+ entry.state = "failed"
330
+ entry.updatedAt = now
331
+ clearLease(entry)
332
+ atomicWrite(filePath, document)
333
+ }
334
+ return { entry: clone(entry) } as const
335
+ }
336
+ entry.state = "sending"
337
+ entry.attempts += 1
338
+ entry.updatedAt = now
339
+ entry.leaseOwner = token
340
+ entry.leaseUntil = now + leaseMs
341
+ delete entry.lastError
342
+ // 状态必须先原子落盘,函数返回后才允许调用 handler。
343
+ atomicWrite(filePath, document)
344
+ return { entry: clone(entry), token } as const
345
+ })
346
+
347
+ if (!claimed.entry || !("token" in claimed)) return claimed.entry
348
+ try {
349
+ // handler 从持久化 claim 快照取数据,不能用 enqueue 的内存引用代替。
350
+ const receipt = await handler(clone(claimed.entry))
351
+ const persistedReceipt = receipt === undefined ? null : jsonSnapshot(receipt, "receipt")
352
+ return mutate((entries) => {
353
+ const current = entries.find((entry) => entry.id === id)
354
+ // lease 被接管后,旧执行体不得把新执行体的状态覆盖为 sent。
355
+ if (!current || current.leaseOwner !== token) return current ? clone(current) : null
356
+ const completedAt = Date.now()
357
+ current.state = "sent"
358
+ current.updatedAt = completedAt
359
+ current.receipt = persistedReceipt
360
+ delete current.lastError
361
+ clearLease(current)
362
+ return clone(current)
363
+ })
364
+ } catch (error) {
365
+ const failed = mutate((entries) => {
366
+ const current = entries.find((entry) => entry.id === id)
367
+ if (!current || current.leaseOwner !== token) return current ? clone(current) : null
368
+ const failedAt = Date.now()
369
+ current.state = "failed"
370
+ current.updatedAt = failedAt
371
+ current.lastError = errorText(error)
372
+ current.nextAttemptAt = failedAt + Math.min(
373
+ retryMaxMs,
374
+ retryBaseMs * 2 ** Math.max(0, current.attempts - 1),
375
+ )
376
+ clearLease(current)
377
+ return clone(current)
378
+ })
379
+ // 后台自动派发由轮询继续重试;显式 dispatch/flush 能看到发送异常。
380
+ if (automatic.has(id)) return failed
381
+ throw error
382
+ }
383
+ }
384
+
385
+ function dispatch(id: string, dispatchOptions: OutboxDispatchOptions = {}): Promise<OutboxEntry | null> {
386
+ const existing = inFlight.get(id)
387
+ if (existing) return existing
388
+ const promise = dispatchInternal(id, dispatchOptions).finally(() => {
389
+ if (inFlight.get(id) === promise) inFlight.delete(id)
390
+ })
391
+ inFlight.set(id, promise)
392
+ return promise
393
+ }
394
+
395
+ async function flush(flushOptions: OutboxFlushOptions = {}): Promise<OutboxEntry[]> {
396
+ if (flushing) return flushing
397
+ const run = (async () => {
398
+ const results = new Map<string, OutboxEntry>()
399
+ for (;;) {
400
+ // 启动时未过期的崩溃 lease 之后也会在这里被接管;活跃 lease 仍由 recover 尊重。
401
+ await recover({ maxAttempts: flushOptions.maxAttempts })
402
+ const entries = readDocument(filePath, Date.now()).entries
403
+ const candidates = entries.filter((entry) => {
404
+ if (entry.state !== "pending" && entry.state !== "failed") return false
405
+ if (!handlers.has(entry.kind)) return false
406
+ if (flushOptions.maxAttempts !== undefined && entry.attempts >= flushOptions.maxAttempts) return false
407
+ return flushOptions.force || flushOptions.wait || entry.nextAttemptAt <= Date.now()
408
+ })
409
+ const settled = await Promise.all(candidates.map(async (entry) => {
410
+ const result = await dispatch(entry.id, flushOptions)
411
+ if (result) results.set(entry.id, result)
412
+ return result
413
+ }))
414
+ if (!flushOptions.wait) break
415
+ const after = readDocument(filePath, Date.now()).entries
416
+ const active = after.filter((entry) =>
417
+ (entry.state === "pending" || entry.state === "failed") && handlers.has(entry.kind) &&
418
+ (flushOptions.maxAttempts === undefined || entry.attempts < flushOptions.maxAttempts)
419
+ )
420
+ const waitingLocal = after.some((entry) => entry.state === "sending" && inFlight.has(entry.id))
421
+ if (active.length === 0 && !waitingLocal) break
422
+ if (settled.length === 0 && !waitingLocal) {
423
+ const next = active.reduce((minimum, entry) => Math.min(minimum, entry.nextAttemptAt), Number.POSITIVE_INFINITY)
424
+ if (Number.isFinite(next)) await delay(Math.max(1, next - Date.now()))
425
+ else break
426
+ } else {
427
+ await delay(1)
428
+ }
429
+ }
430
+ return [...results.values()]
431
+ })()
432
+ flushing = run
433
+ try {
434
+ return await run
435
+ } finally {
436
+ if (flushing === run) flushing = undefined
437
+ }
438
+ }
439
+
440
+ async function drain(): Promise<void> {
441
+ // 新 dispatch 可能在 await 间隙启动,因此循环到 inFlight 真正为空。
442
+ while (inFlight.size > 0) {
443
+ const pending = [...inFlight.values()]
444
+ const outcomes = await Promise.allSettled(pending)
445
+ const rejection = outcomes.find((outcome) => outcome.status === "rejected")
446
+ if (rejection) throw (rejection as PromiseRejectedResult).reason
447
+ }
448
+ }
449
+
450
+ return {
451
+ filePath,
452
+ register(kind, handler) {
453
+ if (!kind) throw new Error("Outbox kind 不能为空")
454
+ handlers.set(kind, handler)
455
+ return () => {
456
+ if (handlers.get(kind) === handler) handlers.delete(kind)
457
+ }
458
+ },
459
+ async enqueue<Payload = unknown>(input: OutboxEnqueueInput<Payload>): Promise<OutboxEntry<Payload>> {
460
+ if (!input.kind) throw new Error("Outbox kind 不能为空")
461
+ if (input.payload === undefined) throw new Error("Outbox payload 必须是 JSON 值,不能为 undefined")
462
+ if (input.nextAttemptAt !== undefined && !Number.isFinite(input.nextAttemptAt)) {
463
+ throw new Error("Outbox nextAttemptAt 必须是有限时间戳")
464
+ }
465
+ const persistedCtx = jsonSnapshot(input.ctx, "ctx")
466
+ const persistedPayload = jsonSnapshot(input.payload, "payload")
467
+ const now = Date.now()
468
+ const id = input.id ?? randomUUID()
469
+ const entry = mutate((entries) => {
470
+ const existing = entries.find((candidate) => candidate.id === id)
471
+ // 同 id 重入(含 sent)复用原条目;显式无 id enqueue 永远生成新条目,不看 user/正文。
472
+ if (existing) return clone(existing) as OutboxEntry<Payload>
473
+ const created: OutboxEntry = {
474
+ id,
475
+ kind: input.kind,
476
+ ctx: persistedCtx,
477
+ payload: persistedPayload,
478
+ ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
479
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
480
+ state: "pending",
481
+ attempts: 0,
482
+ createdAt: now,
483
+ updatedAt: now,
484
+ nextAttemptAt: input.nextAttemptAt ?? now,
485
+ }
486
+ entries.push(created)
487
+ return clone(created) as OutboxEntry<Payload>
488
+ })
489
+ // mutate 已完成原子落盘;从这里之后才可能出现任何网络发送。
490
+ automatic.add(id)
491
+ void dispatch(id).finally(() => automatic.delete(id)).catch(() => { /* 自动路径在内部转为 failed */ })
492
+ return entry
493
+ },
494
+ dispatch,
495
+ recover,
496
+ flush,
497
+ async start(startOptions = {}) {
498
+ stopped = false
499
+ if (startOptions.recover !== false) await recover()
500
+ if (pollIntervalMs === 0 || timer) return
501
+ timer = setInterval(() => {
502
+ if (stopped) return
503
+ void flush().catch(() => { /* 下轮继续;失败已持久化 */ })
504
+ }, pollIntervalMs)
505
+ timer.unref?.()
506
+ void flush().catch(() => { /* 下轮继续 */ })
507
+ },
508
+ stop() {
509
+ stopped = true
510
+ if (timer) clearInterval(timer)
511
+ timer = undefined
512
+ },
513
+ drain,
514
+ async list() {
515
+ return readDocument(filePath, Date.now()).entries.map((entry) => clone(entry))
516
+ },
517
+ async get(id) {
518
+ const entry = readDocument(filePath, Date.now()).entries.find((candidate) => candidate.id === id)
519
+ return entry ? clone(entry) : undefined
520
+ },
521
+ }
522
+ }