@linjz/opencode-qqbot 0.3.15 → 0.3.17

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 (61) hide show
  1. package/README.md +303 -229
  2. package/README.zh-CN.md +313 -0
  3. package/bin/openqq.js +13 -0
  4. package/dist/notify-cli.js +92 -26
  5. package/dist/opencode-qqbot-plugin.js +1201 -67
  6. package/dist/openqq-bot.js +3963 -893
  7. package/dist/openqq-cli.js +980 -0
  8. package/dist/openqq-watchdog.js +1326 -0
  9. package/package.json +8 -5
  10. package/src/bridge.ts +1599 -150
  11. package/src/cli/notify.ts +170 -158
  12. package/src/cli/openqq-main.ts +95 -0
  13. package/src/cli/service-main.ts +302 -0
  14. package/src/cli/watchdog-main.ts +92 -0
  15. package/src/commands.ts +670 -554
  16. package/src/config.ts +122 -3
  17. package/src/core/bot-config.ts +66 -0
  18. package/src/core/bot-control.ts +166 -0
  19. package/src/core/bot-launcher.ts +110 -15
  20. package/src/core/card-approval.ts +20 -9
  21. package/src/core/cron-reminders.ts +84 -0
  22. package/src/core/delivery.ts +145 -54
  23. package/src/core/discovery.ts +207 -151
  24. package/src/core/error-rescue.ts +1 -1
  25. package/src/core/file-log.ts +50 -9
  26. package/src/core/form-bridge.ts +14 -5
  27. package/src/core/form-journal.ts +4 -4
  28. package/src/core/gateway-state.ts +3 -3
  29. package/src/core/inflight-journal.ts +215 -36
  30. package/src/core/instance-lock.ts +42 -3
  31. package/src/core/linkwatch.ts +3 -4
  32. package/src/core/log-rotate.ts +91 -0
  33. package/src/core/markdown.ts +117 -0
  34. package/src/core/message-queue.ts +242 -91
  35. package/src/core/mirror.ts +228 -182
  36. package/src/core/notices.ts +62 -0
  37. package/src/core/notify-sink.ts +93 -96
  38. package/src/core/outbound-sanitize.ts +29 -0
  39. package/src/core/outbox.ts +10 -9
  40. package/src/core/permission.ts +634 -303
  41. package/src/core/question-form.ts +230 -0
  42. package/src/core/queue-view.ts +662 -0
  43. package/src/core/send-media.ts +61 -2
  44. package/src/core/start-error.ts +26 -0
  45. package/src/core/storage.ts +34 -0
  46. package/src/core/stt.ts +55 -0
  47. package/src/core/supervisor-election.ts +53 -0
  48. package/src/core/watchdog.ts +670 -0
  49. package/src/core/zombie-reaper.ts +127 -0
  50. package/src/index.ts +262 -162
  51. package/src/opencode/client.ts +237 -27
  52. package/src/opencode/eventstream.ts +94 -12
  53. package/src/opencode/history.ts +4 -2
  54. package/src/opencode/mirror.ts +25 -5
  55. package/src/opencode/sessions.ts +135 -37
  56. package/src/plugin-entry.ts +139 -115
  57. package/src/qq/api.ts +165 -61
  58. package/src/qq/gateway.ts +114 -16
  59. package/src/qq/media.ts +21 -0
  60. package/src/qq/sender.ts +79 -18
  61. package/src/qq/types.ts +7 -0
@@ -0,0 +1,117 @@
1
+ // @input: (纯文本工具,无依赖)
2
+ // @output: startsWithBlockSyntax, labelBlock, matchFence, balanceFences, FenceToken
3
+ // @pos: 根层/core - QQ markdown 安全层(标签↔块级语法隔离、围栏配对兜底)
4
+ //
5
+ // 背景(2026-11-10 用户截图实证):摘要卡正文以 ``` 开头时,标签行
6
+ // `🤖 \`\`\`` 让开围栏不顶格(CommonMark 要求行首 ≤3 空格),开栏失效;而结尾
7
+ // 顶格的 ``` 反而被当成开栏 → QQ 渲染出一张空代码卡、正文外泄成普通段落。
8
+ // 同类风险还有:/history 的 🧑/🤖 标签 + 块级正文、clipBlock 截断切断围栏、
9
+ // 分条器只认 ``` 不认 ~~~。本模块把「标签拼接」与「围栏配对」收敛成两个纯函数,
10
+ // 供摘要、历史、分条与出站兜底共用。
11
+
12
+ /** 一行里识别到的围栏标记(含信息串,如 ```ts 的 ts) */
13
+ export interface FenceToken {
14
+ /** 围栏字符:反引号或波浪线 */
15
+ ch: "`" | "~"
16
+ /** 连续标记长度(CommonMark 允许 ≥3,闭合须 ≥ 开启长度) */
17
+ len: number
18
+ /** 信息串(语言标签);闭合围栏的信息串必须为空 */
19
+ info: string
20
+ }
21
+
22
+ // CommonMark:围栏前最多 3 空格;反引号围栏的信息串不得含反引号。
23
+ const FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/
24
+
25
+ /** 判断整行是否为围栏行;返回标记,非围栏返回 null。 */
26
+ export function matchFence(line: string): FenceToken | null {
27
+ const m = FENCE_LINE.exec(line)
28
+ if (!m) return null
29
+ const run = m[1]
30
+ const ch = run[0] as "`" | "~"
31
+ const info = m[2].trim()
32
+ if (ch === "`" && info.includes("`")) return null
33
+ return { ch, len: run.length, info }
34
+ }
35
+
36
+ // 正文首个非空行落在这些块级构造上时,标签必须独占一行——否则 "🤖 " 前缀会把
37
+ // 围栏/标题/列表/引用/表格降级成普通段落(最坏情况即空代码卡 + 内容外泄)。
38
+ const BLOCK_START = [
39
+ /^ {0,3}(`{3,}|~{3,})/, // 围栏代码块
40
+ /^ {0,3}#{1,6}(\s|$)/, // ATX 标题
41
+ /^ {0,3}>/, // 引用
42
+ /^ {0,3}([-*+]|\d{1,9}[.)])\s+/, // 无序/有序列表
43
+ /^ {0,3}\|/, // GFM 表格
44
+ /^ {0,3}((-\s*){3,}|(\*\s*){3,}|(_\s*){3,})$/, // 分隔线
45
+ /^ {0,3}</, // HTML 块
46
+ /^ {4,}\S/, // 缩进代码块
47
+ ]
48
+
49
+ /** 正文首个非空行是否以块级语法开头(决定标签能否内联)。 */
50
+ export function startsWithBlockSyntax(text: string): boolean {
51
+ const first = text.split("\n").find((line) => line.trim() !== "") ?? ""
52
+ return BLOCK_START.some((re) => re.test(first))
53
+ }
54
+
55
+ /**
56
+ * 给正文加标签(如 "🤖"):普通段落保持 "标签 正文" 内联;块级正文让标签独占一行,
57
+ * 保住块级语法与围栏顶格。空正文只返回标签。
58
+ */
59
+ export function labelBlock(label: string, body: string): string {
60
+ if (!body.trim()) return label
61
+ return startsWithBlockSyntax(body) ? `${label}\n${body}` : `${label} ${body}`
62
+ }
63
+
64
+ /**
65
+ * 出站兜底(补):去掉「空围栏对」——开栏下一行就是同字符同长度闭栏。
66
+ * 嵌套围栏/套娃预览时,多余的成对围栏会在 QQ 里渲染成一张空白代码卡
67
+ * (2026-11-10 第二轮截图实证),而空代码块本身没有任何信息量。
68
+ * 含空白的空块同样去除;非空块逐字保留。
69
+ */
70
+ export function stripEmptyFences(text: string): string {
71
+ const lines = text.split("\n")
72
+ const out: string[] = []
73
+ for (let i = 0; i < lines.length; i++) {
74
+ const open = matchFence(lines[i])
75
+ if (open) {
76
+ const next = i + 1 < lines.length ? matchFence(lines[i + 1]) : null
77
+ const empty = next !== null && next.ch === open.ch && next.len >= open.len && next.info === ""
78
+ if (empty) {
79
+ i += 1
80
+ continue
81
+ }
82
+ }
83
+ out.push(lines[i])
84
+ }
85
+ return out.join("\n")
86
+ }
87
+
88
+ /**
89
+ * 出站兜底:补齐未闭合的围栏。QQ 渲染器把未闭合围栏吞到消息末尾并渲染成空卡片,
90
+ * 因此在发送前把「开栏无闭栏」补成配对(内容仍是原文,只是补一个闭合标记)。
91
+ * 已配对的文本逐字返回,幂等。
92
+ */
93
+ export function balanceFences(text: string): string {
94
+ let open: FenceToken | null = null
95
+ for (const line of text.split("\n")) {
96
+ const f = matchFence(line)
97
+ if (!f) continue
98
+ if (!open) {
99
+ open = f
100
+ } else if (f.ch === open.ch && f.len >= open.len && f.info === "") {
101
+ open = null
102
+ }
103
+ }
104
+ if (!open) return text
105
+ const closer = open.ch.repeat(open.len)
106
+ return text.endsWith("\n") ? `${text}${closer}` : `${text}\n${closer}`
107
+ }
108
+
109
+ /**
110
+ * 出站 markdown 归一:先补配对、再清空块(顺序不可换——配对本就会造出新的空对)。
111
+ * 归一后为空则回退到只配对的结果,避免整条消息被清空。
112
+ */
113
+ export function normalizeOutboundMarkdown(text: string): string {
114
+ const balanced = balanceFences(text)
115
+ const stripped = stripEmptyFences(balanced)
116
+ return stripped.trim() ? stripped : balanced
117
+ }
@@ -1,91 +1,242 @@
1
- // @input: ../qq/types(MessageContext)
2
- // @output: MessageQueue, QueuedJob, previewText, agoLabel
3
- // @pos: core - 忙碌消息队列(Q1 学习自 pi-qqbot queue.ts 的 UX 语义)
4
- //
5
- // 旧行为:忙碌时直接拒绝"上一条消息还在处理中"。新行为(学习竞品):
6
- // 忙时消息 FIFO 排队并回执,当前回合结束自动 drain 下一条;/cancel 清队。
7
- // 控制面(/queue、审批作答、表单作答)永远即时处理,不进队列。
8
- import type { MessageContext } from "../qq/types.js"
9
-
10
- export interface QueuedJob {
11
- id: number
12
- userId: string
13
- ctx: MessageContext
14
- text: string
15
- enqueuedAt: number
16
- }
17
-
18
- const PREVIEW_MAX = 48
19
-
20
- /** 忙碌期间的用户意图键:msgId 不同的重复提问/同图重发仍视为同一意图。 */
21
- export function intentKeyOf(ctx: MessageContext): string {
22
- const text = ctx.content.replace(/\s+/g, " ").trim()
23
- const attachments = (ctx.attachments ?? []).map((a) => `${a.content_type}:${a.size}:${a.filename}`).join("|")
24
- return JSON.stringify({ text, referenced: ctx.referencedMsgId ?? "", attachments })
25
- }
26
-
27
- export function previewText(text: string, max = PREVIEW_MAX): string {
28
- const flat = text.replace(/\s+/g, " ").trim()
29
- return flat.length > max ? `${flat.slice(0, max)}…` : flat || "(空消息)"
30
- }
31
-
32
- export function agoLabel(at: number, now = Date.now()): string {
33
- const seconds = Math.max(0, Math.round((now - at) / 1000))
34
- if (seconds < 60) return `${seconds}s 前`
35
- const minutes = Math.floor(seconds / 60)
36
- if (minutes < 60) return `${minutes}m 前`
37
- return `${Math.floor(minutes / 60)}h 前`
38
- }
39
-
40
- export class MessageQueue {
41
- private jobs = new Map<string, QueuedJob[]>()
42
- private nextId = 1
43
-
44
- constructor(private limit = 20) {}
45
-
46
- /** 入队;满员返回 null(调用方回绝并提示) */
47
- push(userId: string, ctx: MessageContext): { job: QueuedJob; ahead: number } | null {
48
- const list = this.jobs.get(userId) ?? []
49
- if (list.length >= this.limit) return null
50
- const job: QueuedJob = { id: this.nextId++, userId, ctx, text: ctx.content, enqueuedAt: Date.now() }
51
- list.push(job)
52
- this.jobs.set(userId, list)
53
- return { job, ahead: list.length - 1 }
54
- }
55
-
56
- hasIntent(userId: string, key: string): boolean {
57
- return (this.jobs.get(userId) ?? []).some((job) => intentKeyOf(job.ctx) === key)
58
- }
59
-
60
- shift(userId: string): QueuedJob | undefined {
61
- const list = this.jobs.get(userId)
62
- const job = list?.shift()
63
- if (list && list.length === 0) this.jobs.delete(userId)
64
- return job
65
- }
66
-
67
- list(userId: string): readonly QueuedJob[] {
68
- return this.jobs.get(userId) ?? []
69
- }
70
-
71
- drop(userId: string, id: number): boolean {
72
- const list = this.jobs.get(userId)
73
- if (!list) return false
74
- const idx = list.findIndex((j) => j.id === id)
75
- if (idx < 0) return false
76
- list.splice(idx, 1)
77
- if (list.length === 0) this.jobs.delete(userId)
78
- return true
79
- }
80
-
81
- /** 清空该用户队列,返回清掉的条数 */
82
- clear(userId: string): number {
83
- const n = this.jobs.get(userId)?.length ?? 0
84
- this.jobs.delete(userId)
85
- return n
86
- }
87
-
88
- size(userId: string): number {
89
- return this.jobs.get(userId)?.length ?? 0
90
- }
91
- }
1
+ // @input: ../qq/types(MessageContext)
2
+ // @output: MessageQueue, QueuedJob, laneKeyOf, userIdOfLane, sessionIdOfLane, previewText, agoLabel
3
+ // @pos: core - 忙碌消息队列(Q1 学习自 pi-qqbot queue.ts 的 UX 语义)
4
+ //
5
+ // 旧行为:忙碌时直接拒绝"上一条消息还在处理中"。新行为(学习竞品):
6
+ // 忙时消息 FIFO 排队并回执,当前回合结束自动 drain 下一条;/cancel 清队。
7
+ // 控制面(/queue、审批作答、表单作答)永远即时处理,不进队列。
8
+ //
9
+ // 会话隔离(owner 2026-11-14 裁定,DEF-qqbot-20261112-01 修法①):
10
+ // 队列按 (userId, sessionId) 分 lane——官方 per-peer 串行的会话级细腻化。
11
+ // 僵尸/长回合只堵所在 lane;入队即锚定 sessionId 快照,drain 按锚定会话派发。
12
+ // 票号仍按用户单调递增(#N 是用户可见身份键,跨 lane 不复用)。
13
+ //
14
+ // 会话隔离粒度可配(owner 2026-11-17 裁定,design §2.3):QQ_LANE_SCOPE=
15
+ // - "per-session-peer"(缺省):每 (对端,会话) 一条 lane——官方 per-peer 的会话级
16
+ // 细腻化(owner 11-14 裁定),同用户多会话可并行;
17
+ // - "per-peer"(行内通用名,对齐官方 SDK concurrencyGuard 口径):lane 退化为
18
+ // 每对端(C2C=用户)一条,用户消息全局串行;
19
+ // busy/队列/僵尸收割/重启重建全线随 laneKeyOf 收敛(队列本身对 laneKey 不透明)。
20
+ // 判定走惰性函数:.env 由 ensureConfig() 运行时才注入 process.env(同 apiBase 教训)。
21
+ // 命名依据(2026-11-17 检索):peer=QQ 平台官方术语(单关系配额/concurrencyGuard
22
+ // 按 peer 串行);session=引擎会话;vercel/chat 等通用框架同款 lock-scope 枚举风格
23
+ // ("thread"|"channel" = 细→粗两档)。
24
+ import type { MessageContext } from "../qq/types.js"
25
+
26
+ export interface QueuedJob {
27
+ id: number
28
+ userId: string
29
+ /** 入队锚定的目标会话(owner 2026-11-14:快照于入队时刻;派发/drain 跟锚定不跟漂移绑定) */
30
+ sessionId?: string
31
+ ctx: MessageContext
32
+ text: string
33
+ enqueuedAt: number
34
+ }
35
+
36
+ /**
37
+ * 并发 lane 粒度(design §2.3,行内通用 lock-scope 枚举风格,细→粗):
38
+ * - per-session-peer:每 (对端,会话) 一条 lane(缺省);
39
+ * - per-peer:每对端一条 lane(官方 SDK concurrencyGuard 同构)。
40
+ */
41
+ export type LaneScope = "per-session-peer" | "per-peer"
42
+
43
+ export function laneScope(): LaneScope {
44
+ return (process.env.QQ_LANE_SCOPE ?? "").trim().toLowerCase() === "per-peer" ? "per-peer" : "per-session-peer"
45
+ }
46
+
47
+ /**
48
+ * lane 键 = userId|sessionId;无绑定消息落 null lane(sessionId 段为空串)。
49
+ * QQ_LANE_SCOPE=per-peer 时带会话也退化为 `${userId}|`(对端全局串行)——
50
+ * 与 null lane 同形,userIdOfLane/sessionIdOfLane 解析不受影响。
51
+ */
52
+ export function laneKeyOf(userId: string, sessionId: string | null | undefined): string {
53
+ if (!sessionId || laneScope() === "per-peer") return `${userId}|`
54
+ return `${userId}|${sessionId}`
55
+ }
56
+
57
+ export function userIdOfLane(laneKey: string): string {
58
+ const i = laneKey.indexOf("|")
59
+ return i < 0 ? laneKey : laneKey.slice(0, i)
60
+ }
61
+
62
+ export function sessionIdOfLane(laneKey: string): string | undefined {
63
+ const i = laneKey.indexOf("|")
64
+ const sid = i < 0 ? "" : laneKey.slice(i + 1)
65
+ return sid || undefined
66
+ }
67
+
68
+ const PREVIEW_MAX = 48
69
+
70
+ /** 忙碌期间的用户意图键:msgId 不同的重复提问/同图重发仍视为同一意图。 */
71
+ export function intentKeyOf(ctx: MessageContext): string {
72
+ const text = ctx.content.replace(/\s+/g, " ").trim()
73
+ const attachments = (ctx.attachments ?? []).map((a) => `${a.content_type}:${a.size}:${a.filename}`).join("|")
74
+ return JSON.stringify({ text: stableIntentText(text), referenced: ctx.referencedMsgId ?? "", attachments })
75
+ }
76
+
77
+ /**
78
+ * design §3.4 K2「稳定尾段随机段」:剥离文本尾部的随机段(nonce/时间戳/消息指纹类
79
+ * 尾巴),使带随机尾巴的同内容消息仍归同一意图。口径保守,只剥两类尾 token——
80
+ * ① 长度 ≥8 且字母数字混杂的连续 token(nonce/hex/base64 形态);
81
+ * ② 长度 ≥6 的纯数字 token(毫秒/微秒时间戳形态)。
82
+ * 剥后留白即再剥(多层尾巴),剥到非随机 token 或空为止;不影响普通文本。
83
+ */
84
+ export function stableIntentText(text: string): string {
85
+ let out = text
86
+ const NOISE = /(?:^|\s)(\S{8,}|\d{6,})$/
87
+ for (;;) {
88
+ const m = NOISE.exec(out)
89
+ if (!m || m[1] === undefined) break
90
+ // ① 混合形态:字母数字混杂(含大小写混合或数字插入);纯字母词(如"继续"后的
91
+ // 英文单词)或纯数字走 ② 的长度门槛,避免误伤正常结尾词
92
+ const token = m[1]
93
+ const mixedAlnum = /[a-zA-Z]/.test(token) && /\d/.test(token)
94
+ const longDigit = /^\d{6,}$/.test(token)
95
+ if (!mixedAlnum && !longDigit) break
96
+ out = out.slice(0, m.index).trimEnd()
97
+ }
98
+ return out
99
+ }
100
+
101
+ export function previewText(text: string, max = PREVIEW_MAX): string {
102
+ const flat = text.replace(/\s+/g, " ").trim()
103
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat || "(空消息)"
104
+ }
105
+
106
+ export function agoLabel(at: number, now = Date.now()): string {
107
+ const seconds = Math.max(0, Math.round((now - at) / 1000))
108
+ if (seconds < 60) return `${seconds}s 前`
109
+ const minutes = Math.floor(seconds / 60)
110
+ if (minutes < 60) return `${minutes}m 前`
111
+ return `${Math.floor(minutes / 60)}h 前`
112
+ }
113
+
114
+ export class MessageQueue {
115
+ // lane(= userId|sessionId)-> 该 (用户,会话) 的 FIFO
116
+ private jobs = new Map<string, QueuedJob[]>()
117
+ // 票号按用户独立递增(2026-11-05):全局计数器会让 A 用户看到 #7 而队列只有 1 条;
118
+ // 票号只增不复用——它是身份/引用键,不是排队位置(位置由视图层单独计算)。
119
+ // 2026-11-14 会话隔离:票号维持 per-user 单调(跨 lane 不复用)。
120
+ private nextIds = new Map<string, number>()
121
+
122
+ constructor(private limit = 20) {}
123
+
124
+ private issueId(userId: string): number {
125
+ const next = this.nextIds.get(userId) ?? 1
126
+ this.nextIds.set(userId, next + 1)
127
+ return next
128
+ }
129
+
130
+ /** 入队到指定 lane;满员返回 null(调用方回绝并提示) */
131
+ push(laneKey: string, userId: string, sessionId: string | undefined, ctx: MessageContext): { job: QueuedJob; ahead: number } | null {
132
+ const list = this.jobs.get(laneKey) ?? []
133
+ if (list.length >= this.limit) return null
134
+ const job: QueuedJob = { id: this.issueId(userId), userId, ctx, text: ctx.content, enqueuedAt: Date.now(), ...(sessionId ? { sessionId } : {}) }
135
+ list.push(job)
136
+ this.jobs.set(laneKey, list)
137
+ return { job, ahead: list.length - 1 }
138
+ }
139
+
140
+ hasIntent(laneKey: string, key: string): boolean {
141
+ return (this.jobs.get(laneKey) ?? []).some((job) => intentKeyOf(job.ctx) === key)
142
+ }
143
+
144
+ shift(laneKey: string): QueuedJob | undefined {
145
+ const list = this.jobs.get(laneKey)
146
+ const job = list?.shift()
147
+ if (list && list.length === 0) this.jobs.delete(laneKey)
148
+ return job
149
+ }
150
+
151
+ list(laneKey: string): readonly QueuedJob[] {
152
+ return this.jobs.get(laneKey) ?? []
153
+ }
154
+
155
+ /** 该用户全部 lane 的条目,跨 lane 按入队时刻升序(视图/清场用) */
156
+ listUser(userId: string): readonly QueuedJob[] {
157
+ const out: QueuedJob[] = []
158
+ for (const [laneKey, list] of this.jobs) {
159
+ if (userIdOfLane(laneKey) === userId) out.push(...list)
160
+ }
161
+ return out.sort((a, b) => a.enqueuedAt - b.enqueuedAt)
162
+ }
163
+
164
+ /** 该用户在队的全部 lane 键(stopAll 后逐 lane 续排用) */
165
+ laneKeysOf(userId: string): string[] {
166
+ return [...this.jobs.keys()].filter((laneKey) => userIdOfLane(laneKey) === userId)
167
+ }
168
+
169
+ /** 按队列编号查单条(跨 lane 搜索;/queue drop 与 /ledger 对账用) */
170
+ find(userId: string, id: number): QueuedJob | undefined {
171
+ return this.listUser(userId).find((job) => job.id === id)
172
+ }
173
+
174
+ /** 队首(drain 前预读,不改变队列) */
175
+ peek(laneKey: string): QueuedJob | undefined {
176
+ return this.jobs.get(laneKey)?.[0]
177
+ }
178
+
179
+ /**
180
+ * 重启恢复:按给定顺序重建指定 lane。id 缺省时续接该用户票号,
181
+ * 显式 id 时同步推进该用户票号,保证后续入队编号不冲突。
182
+ * 超过上限的部分不恢复,返回实际恢复条数。
183
+ */
184
+ restore(
185
+ laneKey: string,
186
+ userId: string,
187
+ sessionId: string | undefined,
188
+ jobs: Array<{ ctx: MessageContext; text: string; enqueuedAt: number; id?: number; sessionId?: string }>,
189
+ ): number {
190
+ const list = this.jobs.get(laneKey) ?? []
191
+ let restored = 0
192
+ for (const item of jobs) {
193
+ if (list.length >= this.limit) break
194
+ const explicit = Number.isInteger(item.id) && (item.id ?? 0) > 0 ? (item.id as number) : 0
195
+ const id = explicit > 0 ? explicit : this.issueId(userId)
196
+ if (id >= (this.nextIds.get(userId) ?? 1)) this.nextIds.set(userId, id + 1)
197
+ // 锚定会话取条目自身(QQ_LANE_SCOPE=user 时同 lane 可混多会话,lane 级 sid 会丢锚)
198
+ const jobSid = item.sessionId ?? sessionId
199
+ list.push({ id, userId, ctx: item.ctx, text: item.text, enqueuedAt: item.enqueuedAt, ...(jobSid ? { sessionId: jobSid } : {}) })
200
+ restored++
201
+ }
202
+ if (list.length > 0) this.jobs.set(laneKey, list)
203
+ return restored
204
+ }
205
+
206
+ /** 按票号跨 lane 删除(/queue drop) */
207
+ drop(userId: string, id: number): boolean {
208
+ for (const [laneKey, list] of this.jobs) {
209
+ if (userIdOfLane(laneKey) !== userId) continue
210
+ const idx = list.findIndex((j) => j.id === id)
211
+ if (idx < 0) continue
212
+ list.splice(idx, 1)
213
+ if (list.length === 0) this.jobs.delete(laneKey)
214
+ return true
215
+ }
216
+ return false
217
+ }
218
+
219
+ /** 清空该用户全部 lane,返回清掉的条数 */
220
+ clear(userId: string): number {
221
+ let n = 0
222
+ for (const [laneKey, list] of this.jobs) {
223
+ if (userIdOfLane(laneKey) !== userId) continue
224
+ n += list.length
225
+ this.jobs.delete(laneKey)
226
+ }
227
+ return n
228
+ }
229
+
230
+ size(laneKey: string): number {
231
+ return this.jobs.get(laneKey)?.length ?? 0
232
+ }
233
+
234
+ /** 该用户全部 lane 的总长度(队列完成回执展示用) */
235
+ sizeUser(userId: string): number {
236
+ let n = 0
237
+ for (const [laneKey, list] of this.jobs) {
238
+ if (userIdOfLane(laneKey) === userId) n += list.length
239
+ }
240
+ return n
241
+ }
242
+ }