@linjz/opencode-qqbot 0.3.15 → 0.3.16

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 (50) hide show
  1. package/README.md +42 -5
  2. package/bin/openqq.js +13 -0
  3. package/dist/notify-cli.js +28 -14
  4. package/dist/opencode-qqbot-plugin.js +934 -64
  5. package/dist/openqq-bot.js +3095 -677
  6. package/dist/openqq-cli.js +791 -0
  7. package/dist/openqq-watchdog.js +1063 -0
  8. package/package.json +8 -5
  9. package/src/bridge.ts +1310 -150
  10. package/src/cli/notify.ts +167 -158
  11. package/src/cli/openqq-main.ts +95 -0
  12. package/src/cli/service-main.ts +302 -0
  13. package/src/cli/watchdog-main.ts +77 -0
  14. package/src/commands.ts +644 -554
  15. package/src/config.ts +85 -0
  16. package/src/core/bot-control.ts +148 -0
  17. package/src/core/bot-launcher.ts +106 -13
  18. package/src/core/card-approval.ts +20 -9
  19. package/src/core/delivery.ts +145 -54
  20. package/src/core/discovery.ts +22 -4
  21. package/src/core/file-log.ts +35 -3
  22. package/src/core/form-bridge.ts +14 -5
  23. package/src/core/form-journal.ts +4 -4
  24. package/src/core/gateway-state.ts +3 -3
  25. package/src/core/inflight-journal.ts +214 -36
  26. package/src/core/instance-lock.ts +10 -2
  27. package/src/core/linkwatch.ts +3 -4
  28. package/src/core/markdown.ts +117 -0
  29. package/src/core/message-queue.ts +242 -91
  30. package/src/core/mirror.ts +222 -182
  31. package/src/core/notify-sink.ts +93 -96
  32. package/src/core/outbox.ts +10 -9
  33. package/src/core/permission.ts +627 -303
  34. package/src/core/question-form.ts +230 -0
  35. package/src/core/queue-view.ts +661 -0
  36. package/src/core/send-media.ts +32 -0
  37. package/src/core/storage.ts +34 -0
  38. package/src/core/watchdog.ts +513 -0
  39. package/src/core/zombie-reaper.ts +127 -0
  40. package/src/index.ts +140 -52
  41. package/src/opencode/client.ts +206 -27
  42. package/src/opencode/eventstream.ts +94 -12
  43. package/src/opencode/history.ts +4 -2
  44. package/src/opencode/mirror.ts +15 -2
  45. package/src/opencode/sessions.ts +135 -37
  46. package/src/plugin-entry.ts +120 -115
  47. package/src/qq/api.ts +165 -61
  48. package/src/qq/gateway.ts +79 -16
  49. package/src/qq/sender.ts +30 -18
  50. package/src/qq/types.ts +7 -0
@@ -0,0 +1,661 @@
1
+ // @input: ./inflight-journal(InflightEntry/SettleReason), ./message-queue(QueuedJob/previewText/agoLabel)
2
+ // @output: deriveQueueView, formatQueueReply, formatLedgerReply, formatStatusLine,
3
+ // shortId, ORPHAN_DEFAULT_MS, REJECTED_WINDOW_MS, QUEUE_REPLY_MAX_CHARS
4
+ // @pos: core - 队列/台账可观测性派生视图(纯函数:同一输入必得同一状态与文案)
5
+ //
6
+ // 背景(2026-11-05 队列测试1–20):内存队列只回答"谁在等",磁盘台账只回答"谁没答",
7
+ // 两者失联时用户从 /queue 只能看到"队列:空"。本模块把三源(队列/台账/运行态)
8
+ // join 成 9 个对外状态,并给出可复算的回复文案。
9
+ import type { InflightEntry, InflightStage, SettleReason } from "./inflight-journal.js"
10
+ import { agoLabel, intentKeyOf, laneKeyOf, previewText, type QueuedJob } from "./message-queue.js"
11
+ import { messageFingerprint } from "./inbound-dedupe.js"
12
+
13
+ /** 孤儿判定阈值:台账在途、不在队列、也不在运行/后台,超过该时长即孤儿。 */
14
+ export const ORPHAN_DEFAULT_MS = 90_000
15
+ /** "最近拒绝"展示窗口。 */
16
+ export const REJECTED_WINDOW_MS = 30 * 60_000
17
+ /** 单条回复字符上限(超过分页,避免 QQ 长文体验崩坏)。 */
18
+ export const QUEUE_REPLY_MAX_CHARS = 1800
19
+ const PAGE_SIZE = 10
20
+ const ALL_PAGE_SIZE = 20
21
+ const PREVIEW = 32
22
+
23
+ export type ViewStage =
24
+ | "claimed"
25
+ | "queued"
26
+ | "dispatched"
27
+ | "running"
28
+ | "background"
29
+ | "orphan"
30
+ | "ghost"
31
+ | "settled"
32
+ | "rejected"
33
+
34
+ export interface ViewEntry {
35
+ msgId: string
36
+ text: string
37
+ /** 受理时刻(台账 at) */
38
+ at: number
39
+ /** 入队时刻(队列 job.enqueuedAt;未入队回落到 at) */
40
+ enqueuedAt?: number
41
+ stage: ViewStage
42
+ /** 票号(只增不复用;drop/ledger 的引用键) */
43
+ queueId?: number
44
+ /** 排队位置(1-based,仅 queued 有;完成一条后其余前移) */
45
+ position?: number
46
+ sessionId?: string
47
+ promptId?: string
48
+ attemptId?: string
49
+ ownerPid?: number
50
+ settleReason?: SettleReason
51
+ updatedAt?: number
52
+ lastError?: string
53
+ /** K2 内容指纹(design §3.5:/ledger 详情须含) */
54
+ fingerprint?: string
55
+ }
56
+
57
+ export interface QueueView {
58
+ now: number
59
+ busy: boolean
60
+ orphanMs: number
61
+ /** 队列里等待的条目(按入队顺序) */
62
+ queued: ViewEntry[]
63
+ /** 已受理但还在派发窗口内的条目 */
64
+ claimed: ViewEntry[]
65
+ /** 执行中的条目(会话隔离后每 (用户,会话) lane 至多一条,用户可多 lane 并行) */
66
+ running: ViewEntry[]
67
+ /** 后台等待的条目 */
68
+ background: ViewEntry[]
69
+ /** 已派发但当前无运行标记的条目(可能刚结束未销账/进程换代间隙) */
70
+ dispatchedOthers: ViewEntry[]
71
+ /** 孤儿:台账在途、不在队列、不在运行/后台、超过阈值 */
72
+ orphan: ViewEntry[]
73
+ /** 幽灵:队列有、台账无 */
74
+ ghost: ViewEntry[]
75
+ /** 最近拒绝/作废(settled 且 reason != answered) */
76
+ rejected: ViewEntry[]
77
+ /** 最近已答(供 /ledger 展示) */
78
+ settledRecent: ViewEntry[]
79
+ /** 全部在途(含上述分类,按受理时间升序) */
80
+ inflightEntries: ViewEntry[]
81
+ counts: {
82
+ queued: number
83
+ inflight: number
84
+ running: number
85
+ background: number
86
+ dispatched: number
87
+ claimed: number
88
+ orphan: number
89
+ ghost: number
90
+ rejected: number
91
+ settledRecent: number
92
+ }
93
+ warnings: string[]
94
+ }
95
+
96
+ const STAGE_LABEL: Record<ViewStage, string> = {
97
+ claimed: "派发中",
98
+ queued: "排队中",
99
+ dispatched: "已派发",
100
+ running: "执行中",
101
+ background: "后台等待",
102
+ orphan: "孤儿",
103
+ ghost: "幽灵",
104
+ settled: "已结",
105
+ rejected: "已拒",
106
+ }
107
+
108
+ const REASON_LABEL: Record<SettleReason, string> = {
109
+ answered: "已答",
110
+ error: "处理失败",
111
+ "queue-full": "排队已满",
112
+ "duplicate-msgid": "重复消息",
113
+ "duplicate-intent": "重复意图",
114
+ cancelled: "已取消",
115
+ dropped: "已删除",
116
+ blocked: "被阻塞",
117
+ superseded: "被新回合取代",
118
+ expired: "已过期",
119
+ redispatch: "重启重派",
120
+ manual: "人工结清",
121
+ }
122
+
123
+ const STAGE_RANK: Record<InflightStage, number> = {
124
+ claimed: 0,
125
+ queued: 1,
126
+ dispatched: 2,
127
+ running: 3,
128
+ background: 4,
129
+ settled: 5,
130
+ }
131
+
132
+ export interface DeriveQueueViewInput {
133
+ /** 该用户的台账条目(inflight + settled) */
134
+ entries: InflightEntry[]
135
+ /** 该用户的内存队列 */
136
+ jobs: readonly QueuedJob[]
137
+ runtime: {
138
+ /** 忙 lane 集合(lane 键 = userId|sessionId;会话隔离后按条目自身会话判定 running) */
139
+ busyLanes: ReadonlySet<string>
140
+ /** 任一 lane 正在 drain */
141
+ draining: boolean
142
+ /** 处于后台等待的会话集合 */
143
+ bgSessions: ReadonlySet<string>
144
+ }
145
+ now?: number
146
+ orphanMs?: number
147
+ rejectedWindowMs?: number
148
+ /** 队列上限(违例 I4 长度校验用;缺省 20) */
149
+ queueMax?: number
150
+ }
151
+
152
+ function toViewEntry(entry: InflightEntry, stage: ViewStage, enqueuedAt?: number): ViewEntry {
153
+ return {
154
+ msgId: entry.msgId,
155
+ text: entry.text,
156
+ at: entry.at,
157
+ ...(enqueuedAt !== undefined ? { enqueuedAt } : {}),
158
+ stage,
159
+ ...(entry.queueId !== undefined ? { queueId: entry.queueId } : {}),
160
+ ...(entry.sessionId ? { sessionId: entry.sessionId } : {}),
161
+ ...(entry.promptId ? { promptId: entry.promptId } : {}),
162
+ ...(entry.attemptId ? { attemptId: entry.attemptId } : {}),
163
+ ...(entry.ownerPid !== undefined ? { ownerPid: entry.ownerPid } : {}),
164
+ ...(entry.settleReason ? { settleReason: entry.settleReason } : {}),
165
+ ...(entry.updatedAt !== undefined ? { updatedAt: entry.updatedAt } : {}),
166
+ ...(entry.lastError ? { lastError: entry.lastError } : {}),
167
+ ...(entry.fingerprint ? { fingerprint: entry.fingerprint } : {}),
168
+ }
169
+ }
170
+
171
+ /**
172
+ * 三源 join:队列(谁在等)+ 台账(谁没答)+ 运行态(谁在跑)。
173
+ * 判定优先级:queue > background > running > dispatched > orphan > claimed。
174
+ * 纯函数:不读盘、不取时间(now 可注入),供单测复算。
175
+ */
176
+ export function deriveQueueView(input: DeriveQueueViewInput): QueueView {
177
+ const now = input.now ?? Date.now()
178
+ const orphanMs = input.orphanMs ?? ORPHAN_DEFAULT_MS
179
+ const rejectedWindowMs = input.rejectedWindowMs ?? REJECTED_WINDOW_MS
180
+ const warnings: string[] = []
181
+
182
+ const inflight = input.entries.filter((e) => e.state === "inflight")
183
+ const settled = input.entries.filter((e) => e.state === "settled")
184
+ const byMsg = new Map(inflight.map((e) => [e.msgId, e]))
185
+ // design §3.4:join 键回退链 msgId > queueId > fingerprint(msgId 缺失/漂移时
186
+ // 仍能对账,而不是直接幽灵)。fingerprint 索引惰性构建(K2 指纹与受理同源)。
187
+ const byQueueId = new Map(inflight.filter((e) => e.queueId !== undefined).map((e) => [e.queueId as number, e]))
188
+ const byFingerprint = new Map<string, InflightEntry>()
189
+ for (const e of inflight) if (e.fingerprint && !byFingerprint.has(e.fingerprint)) byFingerprint.set(e.fingerprint, e)
190
+ const jobs = [...input.jobs]
191
+
192
+ const queued: ViewEntry[] = []
193
+ const ghost: ViewEntry[] = []
194
+ const linkedMsgIds = new Set<string>()
195
+ const linkedEntries = new Set<InflightEntry>()
196
+ let noMsgIdJobs = 0
197
+ let queueIdJoins = 0
198
+ let fingerprintJoins = 0
199
+
200
+ /** 三级回退:msgId → queueId → fingerprint;命中的条目不可被后续 job 重复认领 */
201
+ function joinEntry(job: QueuedJob): InflightEntry | undefined {
202
+ const msgId = job.ctx.msgId
203
+ if (msgId) {
204
+ const byMsgHit = byMsg.get(msgId)
205
+ if (byMsgHit && !linkedEntries.has(byMsgHit)) return byMsgHit
206
+ }
207
+ const byQueueHit = byQueueId.get(job.id)
208
+ if (byQueueHit && !linkedEntries.has(byQueueHit)) {
209
+ queueIdJoins++
210
+ return byQueueHit
211
+ }
212
+ const fp = messageFingerprint(job.userId, intentKeyOf(job.ctx))
213
+ const byFpHit = byFingerprint.get(fp)
214
+ if (byFpHit && !linkedEntries.has(byFpHit)) {
215
+ fingerprintJoins++
216
+ return byFpHit
217
+ }
218
+ return undefined
219
+ }
220
+
221
+ for (const job of jobs) {
222
+ const msgId = job.ctx.msgId
223
+ const entry = joinEntry(job)
224
+ if (!entry) {
225
+ if (!msgId) {
226
+ // 无 msgId 且 queueId/fingerprint 均未命中:从未落账,单列提示,不误报幽灵。
227
+ noMsgIdJobs++
228
+ queued.push({
229
+ msgId: `queue-${job.id}`,
230
+ text: job.text,
231
+ at: job.enqueuedAt,
232
+ enqueuedAt: job.enqueuedAt,
233
+ stage: "queued",
234
+ queueId: job.id,
235
+ })
236
+ } else {
237
+ ghost.push({
238
+ msgId,
239
+ text: job.text,
240
+ at: job.enqueuedAt,
241
+ enqueuedAt: job.enqueuedAt,
242
+ stage: "ghost",
243
+ queueId: job.id,
244
+ })
245
+ }
246
+ continue
247
+ }
248
+ linkedEntries.add(entry)
249
+ linkedMsgIds.add(entry.msgId)
250
+ const view = toViewEntry(entry, "queued", job.enqueuedAt)
251
+ view.queueId = job.id
252
+ queued.push(view)
253
+ }
254
+
255
+ const claimed: ViewEntry[] = []
256
+ const background: ViewEntry[] = []
257
+ const dispatchedOthers: ViewEntry[] = []
258
+ const orphan: ViewEntry[] = []
259
+ const running: ViewEntry[] = []
260
+ let dispatchedWithoutRuntime = 0
261
+
262
+ for (const entry of inflight) {
263
+ if (linkedMsgIds.has(entry.msgId)) continue
264
+ const inBg = !!entry.sessionId && input.runtime.bgSessions.has(entry.sessionId)
265
+ // 会话隔离(owner 2026-11-14):running 判定看条目自身会话的 lane 忙闲——
266
+ // 与「当前绑定」解耦:锚定会话的回合在跑即执行中,哪怕用户已切走绑定。
267
+ const laneHit = !!entry.sessionId && input.runtime.busyLanes.has(laneKeyOf(entry.userId, entry.sessionId))
268
+ const hasDispatched = !!entry.sessionId
269
+ const stageRank = entry.stage ? STAGE_RANK[entry.stage] : hasDispatched ? STAGE_RANK.dispatched : STAGE_RANK.claimed
270
+
271
+ if (inBg) {
272
+ background.push(toViewEntry(entry, "background"))
273
+ continue
274
+ }
275
+ if (laneHit && (entry.promptId || stageRank >= STAGE_RANK.dispatched)) {
276
+ running.push(toViewEntry(entry, "running"))
277
+ continue
278
+ }
279
+ // 已派发级(stage ≥ dispatched,含 drain 派发窗口 sessionId 尚未回填的秒级间隙):
280
+ // 归「已派发」并告警——绝不判孤儿。否则排队消息在 drain 窗口会被误报孤儿、
281
+ // 巡检每 10min 刷假告警(2026-11-05 深度自评实证)。
282
+ if (hasDispatched || stageRank >= STAGE_RANK.dispatched) {
283
+ dispatchedWithoutRuntime++
284
+ dispatchedOthers.push(toViewEntry(entry, "dispatched"))
285
+ continue
286
+ }
287
+ // 孤儿门槛:只有「从未进过派发」(claimed/queued 级)的超龄空账才算孤儿——
288
+ // 当初 19 条孤儿正是这种;真卡死的已派发票由 /queue 可见 + 重启恢复兜底。
289
+ if (now - entry.at > orphanMs) {
290
+ orphan.push(toViewEntry(entry, "orphan"))
291
+ continue
292
+ }
293
+ claimed.push(toViewEntry(entry, "claimed"))
294
+ }
295
+
296
+ // 位置是派生量:票号不变,完成/删除后其余前移。
297
+ queued.forEach((e, i) => {
298
+ e.position = i + 1
299
+ })
300
+
301
+ const rejected = settled
302
+ .filter((e) => e.settleReason !== undefined && e.settleReason !== "answered" && now - e.at <= rejectedWindowMs)
303
+ .sort((a, b) => b.at - a.at)
304
+ .map((e) => toViewEntry(e, "rejected"))
305
+
306
+ const settledRecent = settled
307
+ .slice()
308
+ .sort((a, b) => b.at - a.at)
309
+ .slice(0, 20)
310
+ .map((e) => toViewEntry(e, "settled"))
311
+
312
+ const inflightEntries = [...queued, ...claimed, ...background, ...dispatchedOthers, ...running, ...orphan].sort(
313
+ (a, b) => a.at - b.at,
314
+ )
315
+
316
+ if (ghost.length > 0) warnings.push(`幽灵 ${ghost.length} 条(队列有、台账无)`)
317
+ if (queueIdJoins > 0) warnings.push(`${queueIdJoins} 条队列条目经 queueId 回退对账(msgId 未命中)`)
318
+ if (fingerprintJoins > 0) warnings.push(`${fingerprintJoins} 条队列条目经指纹回退对账(msgId/queueId 未命中)`)
319
+ if (noMsgIdJobs > 0) warnings.push(`队列中 ${noMsgIdJobs} 条无 msgId(无法与台账对账)`)
320
+ if (orphan.length > 0) warnings.push(`孤儿 ${orphan.length} 条(超 ${Math.round(orphanMs / 1000)}s 无人认领)`)
321
+ if (dispatchedWithoutRuntime > 0) {
322
+ warnings.push(`台账 ${dispatchedWithoutRuntime} 条已派发但当前无运行标记(可能已结束未销账)`)
323
+ }
324
+ for (let i = 1; i < queued.length; i++) {
325
+ const prev = queued[i - 1]?.queueId ?? 0
326
+ const cur = queued[i]?.queueId ?? 0
327
+ if (cur <= prev) {
328
+ warnings.push("队列编号非递增(顺序异常)")
329
+ break
330
+ }
331
+ }
332
+
333
+ // —— design §3.4 不变量补校:I3(settled 不得在队列)/ I4 长度半条 /
334
+ // I5(队列顺序=入队顺序)/ I6(at ≤ now、updatedAt ≥ at)——
335
+ // 违例只进 warnings 观测面,不改任何状态。
336
+ const queueMax = input.queueMax ?? 20
337
+ if (queued.length > queueMax) warnings.push(`队列长度 ${queued.length} 超上限 ${queueMax}(违例)`)
338
+ const settledMsgIds = new Set(settled.map((e) => e.msgId))
339
+ for (const job of jobs) {
340
+ if (job.ctx.msgId && settledMsgIds.has(job.ctx.msgId)) {
341
+ warnings.push("已结清条目仍出现在队列(违例)")
342
+ break
343
+ }
344
+ }
345
+ for (let i = 1; i < queued.length; i++) {
346
+ if ((queued[i]?.enqueuedAt ?? 0) < (queued[i - 1]?.enqueuedAt ?? 0)) {
347
+ warnings.push("队列顺序≠入队顺序(违例)")
348
+ break
349
+ }
350
+ }
351
+ for (const e of [...inflight, ...settled]) {
352
+ if (e.at > now) {
353
+ warnings.push(`条目 ${shortId(e.msgId)} 受理时刻晚于当前时间(违例)`)
354
+ break
355
+ }
356
+ }
357
+ for (const e of [...inflight, ...settled]) {
358
+ if (e.updatedAt !== undefined && e.updatedAt < e.at) {
359
+ warnings.push(`条目 ${shortId(e.msgId)} 更新时刻早于受理时刻(违例)`)
360
+ break
361
+ }
362
+ }
363
+
364
+ return {
365
+ now,
366
+ busy: input.runtime.busyLanes.size > 0,
367
+ orphanMs,
368
+ queued,
369
+ claimed,
370
+ running,
371
+ background,
372
+ dispatchedOthers,
373
+ orphan,
374
+ ghost,
375
+ rejected,
376
+ settledRecent,
377
+ inflightEntries,
378
+ counts: {
379
+ queued: queued.length,
380
+ inflight: inflight.length,
381
+ running: running.length,
382
+ background: background.length,
383
+ dispatched: dispatchedOthers.length,
384
+ claimed: claimed.length,
385
+ orphan: orphan.length,
386
+ ghost: ghost.length,
387
+ rejected: rejected.length,
388
+ settledRecent: settledRecent.length,
389
+ },
390
+ warnings,
391
+ }
392
+ }
393
+
394
+ function clock(at: number): string {
395
+ const d = new Date(at)
396
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`
397
+ }
398
+
399
+ /** 台账 id 太长:只留尾部,便于用户复制定位。 */
400
+ export function shortId(id: string | undefined, n = 6): string {
401
+ if (!id) return "-"
402
+ const flat = id.replace(/\s+/g, "")
403
+ return flat.length <= n ? flat : `…${flat.slice(-n)}`
404
+ }
405
+
406
+ function stageLabel(stage: ViewStage): string {
407
+ return STAGE_LABEL[stage]
408
+ }
409
+
410
+ function reasonLabel(reason: string | undefined): string {
411
+ if (!reason) return "-"
412
+ return (REASON_LABEL as Record<string, string>)[reason] ?? reason
413
+ }
414
+
415
+ function clampReply(lines: string[], maxChars: number, hint: string): string {
416
+ let out = ""
417
+ for (const line of lines) {
418
+ if (out.length + line.length + 1 > maxChars) {
419
+ return `${out}\n…(${hint})`
420
+ }
421
+ out = out ? `${out}\n${line}` : line
422
+ }
423
+ return out
424
+ }
425
+
426
+ /** 队列满拒绝回执(固定文案,design §3.4:指向 /queue)。 */
427
+ export function formatQueueFullReceipt(max: number): string {
428
+ return `排队已满(${max} 条),本条未入队;请稍候再试,发 /queue 查看队列或 /cancel 中止当前任务`
429
+ }
430
+
431
+ /** design §3.4/§5:孤儿阈值可调(QQ_ORPHAN_MS),非法值回退默认 90s。纯函数便于单测。 */
432
+ export function resolveOrphanMs(envValue: string | undefined): number {
433
+ const raw = Number(envValue ?? "")
434
+ if (Number.isFinite(raw) && raw >= 5_000 && raw <= 3_600_000) return raw
435
+ return ORPHAN_DEFAULT_MS
436
+ }
437
+
438
+ /**
439
+ * /ledger 数字参数歧义消解(DEF-qqbot-20261110-8,2026-11-10 回归实证):
440
+ * 纯数字参数既是合法 msgId 尾号(design §3.5 详情查询)也是合法页码(后增功能)——
441
+ * 旧实现数字一律当页码,尾号详情永不可达。口径:尾号唯一命中→详情;
442
+ * 多条命中→歧义提示;零命中→按页码。
443
+ */
444
+ export type LedgerNumericResolution =
445
+ | { kind: "detail"; entry: ViewEntry }
446
+ | { kind: "ambiguous"; count: number }
447
+ | { kind: "page"; page: number }
448
+
449
+ export function resolveLedgerNumericArg(sub: string, pool: readonly ViewEntry[]): LedgerNumericResolution {
450
+ const hits = pool.filter((e) => e.msgId === sub || e.msgId.endsWith(sub) || shortId(e.msgId) === sub)
451
+ if (hits.length === 1 && hits[0]) return { kind: "detail", entry: hits[0] }
452
+ if (hits.length > 1) return { kind: "ambiguous", count: hits.length }
453
+ return { kind: "page", page: Math.max(1, Number(sub)) }
454
+ }
455
+
456
+ /** 孤儿提醒状态(design §3.4:仅新增孤儿且距上次提醒 >gapMs 才汇总,不刷屏) */
457
+ export interface OrphanNotifyState {
458
+ lastNotifyAt: number
459
+ /** 上次提醒时已通告的孤儿 msgId 集合 */
460
+ notifiedIds: ReadonlySet<string>
461
+ }
462
+
463
+ /**
464
+ * 孤儿提醒决策(纯函数)。口径:
465
+ * - 当前无孤儿 → 清空已通告集合(下次出现即为新增),不提醒;
466
+ * - 存在上次未通告的新孤儿 且 距上次提醒 ≥ gapMs → 提醒并记录当前集合;
467
+ * - 有新孤儿但间隔未满 → 不提醒且保留旧集合(挂起,间隔满后补报);
468
+ * - 无新孤儿 → 不提醒(旧孤儿存续不重复刷)。
469
+ */
470
+ export function decideOrphanNotify(
471
+ prev: OrphanNotifyState | undefined,
472
+ currentIds: readonly string[],
473
+ now: number,
474
+ gapMs: number,
475
+ ): { notify: boolean; state: OrphanNotifyState } {
476
+ const currentSet = new Set(currentIds)
477
+ if (currentIds.length === 0) {
478
+ return { notify: false, state: { lastNotifyAt: prev?.lastNotifyAt ?? 0, notifiedIds: currentSet } }
479
+ }
480
+ const hasNew = !prev || currentIds.some((id) => !prev.notifiedIds.has(id))
481
+ const gapOk = !prev || now - prev.lastNotifyAt >= gapMs
482
+ const notify = hasNew && gapOk
483
+ return {
484
+ notify,
485
+ state: notify
486
+ ? { lastNotifyAt: now, notifiedIds: currentSet }
487
+ : { lastNotifyAt: prev?.lastNotifyAt ?? 0, notifiedIds: prev?.notifiedIds ?? currentSet },
488
+ }
489
+ }
490
+
491
+ export interface QueueReplyOptions {
492
+ all?: boolean
493
+ page?: number
494
+ limit?: number
495
+ maxChars?: number
496
+ }
497
+
498
+ /** 用户面回复:当前任务 / 队列占用 / 台账在途 / 异常区。 */
499
+ export function formatQueueReply(view: QueueView, opts: QueueReplyOptions = {}): string {
500
+ const limit = opts.limit ?? 20
501
+ const all = opts.all ?? false
502
+ const page = Math.max(1, Math.floor(opts.page ?? 1))
503
+ const pageSize = all ? ALL_PAGE_SIZE : PAGE_SIZE
504
+ const lines: string[] = []
505
+
506
+ lines.push(`当前任务:${view.busy ? "处理中" : "空闲"}`)
507
+ lines.push(`队列:${view.counts.queued}/${limit} · 台账在途:${view.counts.inflight} 条`)
508
+
509
+ if (view.counts.queued > 0) {
510
+ lines.push(`排队中 ${view.counts.queued} 条:`)
511
+ const start = (page - 1) * pageSize
512
+ const slice = all ? view.queued.slice(start, start + pageSize) : view.queued.slice(0, pageSize)
513
+ for (const e of slice) {
514
+ lines.push(
515
+ ` #${e.queueId ?? "-"} · 第${e.position ?? "-"}位 · ${agoLabel(e.enqueuedAt ?? e.at, view.now)} · ${previewText(e.text, PREVIEW)} · ${stageLabel(e.stage)}${all ? ` · msg ${shortId(e.msgId)} · att ${shortId(e.attemptId)}` : ""}`,
516
+ )
517
+ }
518
+ const remain = view.counts.queued - (start + slice.length)
519
+ if (remain > 0) lines.push(` …还有 ${remain} 条(/queue all ${page + 1})`)
520
+ } else if (view.counts.inflight === 0 && view.counts.rejected === 0) {
521
+ lines.push(`队列:空(0/${limit})`)
522
+ }
523
+
524
+ if (view.counts.claimed > 0) {
525
+ lines.push(`派发中 ${view.counts.claimed} 条(受理后 90s 内,正常窗口)`)
526
+ }
527
+
528
+ if (view.counts.running > 0) {
529
+ for (const r of view.running.slice(0, 5)) {
530
+ lines.push(`执行中:#${r.queueId ?? "-"} · ${previewText(r.text, PREVIEW)} · ${agoLabel(r.at, view.now)}`)
531
+ }
532
+ if (view.running.length > 5) lines.push(` …还有 ${view.running.length - 5} 条执行中(多会话并行)`)
533
+ }
534
+
535
+ if (view.counts.background > 0) {
536
+ lines.push(`后台等待 ${view.counts.background} 条(完成会自动回传)`)
537
+ }
538
+
539
+ if (view.counts.dispatched > 0) {
540
+ lines.push(`已派发 ${view.counts.dispatched} 条(等待接续执行)`)
541
+ }
542
+
543
+ if (view.counts.orphan > 0) {
544
+ lines.push(`⚠️ 孤儿 ${view.counts.orphan} 条(已受理,未入队/未派发,超 ${Math.round(view.orphanMs / 1000)}s)`)
545
+ const shown = all ? view.orphan.slice(0, pageSize) : view.orphan.slice(0, 8)
546
+ for (const e of shown) {
547
+ lines.push(` · ${previewText(e.text, PREVIEW)} · ${agoLabel(e.at, view.now)} · msg ${shortId(e.msgId)}`)
548
+ }
549
+ if (view.orphan.length > shown.length) lines.push(` …还有 ${view.orphan.length - shown.length} 条(/queue all 或 /ledger orphan)`)
550
+ }
551
+
552
+ if (view.counts.ghost > 0) {
553
+ lines.push(`⚠️ 幽灵 ${view.counts.ghost} 条(队列有、台账无,需修复)`)
554
+ for (const e of view.ghost.slice(0, 5)) {
555
+ lines.push(` · ${previewText(e.text, PREVIEW)} · #${e.queueId ?? "-"} · msg ${shortId(e.msgId)}`)
556
+ }
557
+ }
558
+
559
+ if (view.counts.rejected > 0) {
560
+ lines.push(`最近拒绝 ${view.counts.rejected} 条`)
561
+ for (const e of view.rejected.slice(0, 5)) {
562
+ lines.push(` · ${previewText(e.text, PREVIEW)} · ${reasonLabel(e.settleReason)} · ${clock(e.at)}`)
563
+ }
564
+ }
565
+
566
+ for (const w of view.warnings) {
567
+ if (w.startsWith("队列编号")) lines.push(`⚠️ ${w}`)
568
+ }
569
+
570
+ lines.push("发 /queue all 看全部 · /ledger 看台账明细 · /queue clear 清空")
571
+
572
+ return clampReply(lines, opts.maxChars ?? QUEUE_REPLY_MAX_CHARS, "内容过长,发 /queue all 分页查看")
573
+ }
574
+
575
+ export interface LedgerReplyOptions {
576
+ filter?: "all" | "orphan" | "rejected" | "inflight" | "settled"
577
+ page?: number
578
+ detail?: ViewEntry
579
+ maxChars?: number
580
+ }
581
+
582
+ /** 诊断面回复:台账快照(在途分类 + 最近结清 + 拒绝原因)。 */
583
+ export function formatLedgerReply(view: QueueView, opts: LedgerReplyOptions = {}): string {
584
+ if (opts.detail) return formatLedgerDetail(opts.detail, opts.maxChars ?? QUEUE_REPLY_MAX_CHARS)
585
+
586
+ const filter = opts.filter ?? "all"
587
+ const page = Math.max(1, Math.floor(opts.page ?? 1))
588
+ const lines: string[] = [
589
+ `台账快照 · ${new Date(view.now).toLocaleString("zh-CN", { hour12: false })}`,
590
+ `在途 ${view.counts.inflight} · 已结 ${view.counts.settledRecent}(保留 24h / 最新 20)`,
591
+ ]
592
+
593
+ const wantInflight = filter === "all" || filter === "orphan" || filter === "inflight"
594
+ const wantSettled = filter === "all" || filter === "settled" || filter === "rejected"
595
+
596
+ if (wantInflight) {
597
+ const list =
598
+ filter === "orphan"
599
+ ? view.orphan
600
+ : filter === "inflight"
601
+ ? view.inflightEntries
602
+ : view.inflightEntries
603
+ if (list.length === 0) {
604
+ lines.push(filter === "orphan" ? "孤儿:无" : "在途:无")
605
+ } else {
606
+ const start = (page - 1) * ALL_PAGE_SIZE
607
+ const slice = list.slice(start, start + ALL_PAGE_SIZE)
608
+ lines.push(filter === "orphan" ? `孤儿 ${list.length} 条:` : `在途 ${list.length} 条(按受理时间):`)
609
+ slice.forEach((e, i) => {
610
+ lines.push(
611
+ ` ${start + i + 1}. ${previewText(e.text, PREVIEW)} · ${clock(e.at)} · ${agoLabel(e.at, view.now)} · ${stageLabel(e.stage)} · att ${shortId(e.attemptId)} · sid ${shortId(e.sessionId)} · pid ${e.ownerPid ?? "-"}`,
612
+ )
613
+ })
614
+ const remain = list.length - (start + slice.length)
615
+ if (remain > 0) lines.push(` …还有 ${remain} 条(/ledger ${page + 1})`)
616
+ }
617
+ }
618
+
619
+ if (wantSettled) {
620
+ const list = filter === "rejected" ? view.rejected : view.settledRecent
621
+ if (list.length === 0) {
622
+ lines.push(filter === "rejected" ? "最近拒绝:无" : "最近结清:无")
623
+ } else {
624
+ lines.push(filter === "rejected" ? `最近拒绝 ${list.length} 条:` : `最近结清 ${list.length} 条:`)
625
+ for (const e of list.slice(0, 10)) {
626
+ lines.push(` · ${previewText(e.text, PREVIEW)} · ${clock(e.at)} · ${reasonLabel(e.settleReason)} · att ${shortId(e.attemptId)}`)
627
+ }
628
+ }
629
+ }
630
+
631
+ if (view.warnings.length > 0) {
632
+ lines.push(`⚠️ ${view.warnings.join(";")}`)
633
+ }
634
+
635
+ lines.push("发 /ledger check 对账会话历史 · /ledger settle <尾号> confirm 人工结清")
636
+ return clampReply(lines, opts.maxChars ?? QUEUE_REPLY_MAX_CHARS, "内容过长,发 /ledger <页码> 分页查看")
637
+ }
638
+
639
+ function formatLedgerDetail(entry: ViewEntry, maxChars: number): string {
640
+ const lines = [
641
+ `台账条目 · ${previewText(entry.text, 60)}`,
642
+ `状态:${entry.stage}(${stageLabel(entry.stage)})`,
643
+ `msgId:${entry.msgId}`,
644
+ `attemptId:${entry.attemptId ?? "-"}`,
645
+ `指纹:${entry.fingerprint ?? "-"}`,
646
+ `会话:${entry.sessionId ?? "-"}`,
647
+ `promptId:${entry.promptId ?? "-"}`,
648
+ `队列编号:${entry.queueId ?? "-"}`,
649
+ `受理:${new Date(entry.at).toLocaleString("zh-CN", { hour12: false })}`,
650
+ `更新:${entry.updatedAt ? new Date(entry.updatedAt).toLocaleString("zh-CN", { hour12: false }) : "-"}`,
651
+ `结清原因:${reasonLabel(entry.settleReason)}`,
652
+ `进程:${entry.ownerPid ?? "-"}`,
653
+ `最近错误:${entry.lastError ?? "-"}`,
654
+ ]
655
+ return clampReply(lines, maxChars, "详情过长")
656
+ }
657
+
658
+ /** /status 摘要行:五个数字回答"队列/台账是否健康"。 */
659
+ export function formatStatusLine(view: QueueView): string {
660
+ return `队列/台账:排队 ${view.counts.queued} · 在途 ${view.counts.inflight} · 执行中 ${view.counts.running} · 孤儿 ${view.counts.orphan} · 最近拒绝 ${view.counts.rejected}`
661
+ }